const isSecFetchSite = (value: string): value is SecFetchSite =>
(secFetchSiteValues as readonly string[]).includes(value)
type IsAllowedSecFetchSiteHandler = (secFetchSite: SecFetchSite, context: Context) => boolean
type IsAllowedSecFetchSiteHandler = (
secFetchSite: SecFetchSite,
context: Context
) => boolean | Promise<boolean>
interface CSRFOptions {
origin?: string | string[] | IsAllowedOriginHandler
secFetchSite?: SecFetchSite | SecFetchSite[] | IsAllowedSecFetchSiteHandler
} else {
return (secFetchSite) => optsSecFetchSite.includes(secFetchSite)
}
})(options?.secFetchSite)
const isAllowedSecFetchSite = (secFetchSite: string | undefined, c: Context) => {
const isAllowedSecFetchSite = async (secFetchSite: string | undefined, c: Context) => {
if (secFetchSite === undefined) {
// denied always when sec-fetch-site header is not present
return false
}
// type guard to check if the value is a valid SecFetchSite
if (!isSecFetchSite(secFetchSite)) {
return false
}
return secFetchSiteHandler(secFetchSite, c)
return await secFetchSiteHandler(secFetchSite, c)
}
return async function csrf(c, next) {
if (
!isSafeMethodRe.test(c.req.method) &&
isRequestedByFormElementRe.test(c.req.header('content-type') || 'text/plain') &&
!isAllowedSecFetchSite(c.req.header('sec-fetch-site'), c) &&
!(await isAllowedSecFetchSite(c.req.header('sec-fetch-site'), c)) &&
!(await isAllowedOrigin(c.req.header('origin'), c))
) {
const res = new Response('Forbidden', { status: 403 })
throw new HTTPException(403, { res })