2
0

🐛 Fix allowed origins when embedded in iframe

Closes #1518
This commit is contained in:
Baptiste Arnaud
2024-06-19 09:54:08 +02:00
parent 36c984643a
commit 67f37c02a4
9 changed files with 874 additions and 27 deletions

View File

@@ -11,6 +11,7 @@ import {
StartPreviewChatInput,
} from '@typebot.io/schemas'
import ky from 'ky'
import { CorsError } from '@/utils/CorsError'
type Props = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -102,27 +103,40 @@ export async function startChatQuery({
}
try {
const data = await ky
.post(
`${
isNotEmpty(apiHost) ? apiHost : guessApiHost()
}/api/v1/typebots/${typebotId}/startChat`,
{
json: {
isStreamEnabled: true,
prefilledVariables,
resultId,
isOnlyRegistering: false,
} satisfies Omit<
StartChatInput,
'publicId' | 'textBubbleContentFormat'
>,
timeout: false,
}
)
.json<InitialChatReply>()
const iframeReferrerOrigin =
parent !== window ? new URL(document.referrer).origin : undefined
const response = await ky.post(
`${
isNotEmpty(apiHost) ? apiHost : guessApiHost()
}/api/v1/typebots/${typebotId}/startChat`,
{
headers: {
'x-typebot-iframe-referrer-origin': iframeReferrerOrigin,
},
json: {
isStreamEnabled: true,
prefilledVariables,
resultId,
isOnlyRegistering: false,
} satisfies Omit<
StartChatInput,
'publicId' | 'textBubbleContentFormat'
>,
timeout: false,
}
)
return { data }
const corsAllowOrigin = response.headers.get('access-control-allow-origin')
if (
iframeReferrerOrigin &&
corsAllowOrigin &&
corsAllowOrigin !== '*' &&
!iframeReferrerOrigin.includes(corsAllowOrigin)
)
throw new CorsError(corsAllowOrigin)
return { data: await response.json<InitialChatReply>() }
} catch (error) {
return { error }
}