Skip to content
Myr

index.ts

This file

Path

src/middleware/csrf/index.ts

151 lines · 5.4 KiB · TypeScript

Last changed by

fix(csrf): exempt OPTIONS request from CSRF validation (#5250)John Emerson Requizobefore adoptioneea9735

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–27why, one step back
1/**
2 * @module3 * CSRF Protection Middleware for Hono.4 */56import type { Context } from '../../context'7import { HTTPException } from '../../http-exception'8import type { MiddlewareHandler } from '../../types'910type IsAllowedOriginHandler = (origin: string, context: Context) => boolean | Promise<boolean>1112const secFetchSiteValues = ['same-origin', 'same-site', 'none', 'cross-site'] as const13type SecFetchSite = (typeof secFetchSiteValues)[number]1415const isSecFetchSite = (value: string): value is SecFetchSite =>16 (secFetchSiteValues as readonly string[]).includes(value)1718type IsAllowedSecFetchSiteHandler = (19 secFetchSite: SecFetchSite,20 context: Context21) => boolean | Promise<boolean>2223interface CSRFOptions {24 origin?: string | string[] | IsAllowedOriginHandler25 secFetchSite?: SecFetchSite | SecFetchSite[] | IsAllowedSecFetchSiteHandler26}27

fix(csrf): exempt OPTIONS request from CSRF validation (#5250)John Emerson Requizobefore adoptioneea9735

line 28why, one step back
28const isSafeMethodRe = /^(GET|HEAD|OPTIONS)$/

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 29–151why, one step back
29const isRequestedByFormElementRe =
30 /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i3132/**33 * CSRF Protection Middleware for Hono.34 *35 * Protects against Cross-Site Request Forgery attacks by validating request origins36 * and sec-fetch-site headers. The request is allowed if either validation passes.37 *38 * @see {@link https://hono.dev/docs/middleware/builtin/csrf}39 *40 * @param {CSRFOptions} [options] - The options for the CSRF protection middleware.41 * @param {string|string[]|(origin: string, context: Context) => boolean} [options.origin] -42 * Allowed origins for requests.43 * - string: Single allowed origin (e.g., 'https://example.com')44 * - string[]: Multiple allowed origins45 * - function: Custom validation logic46 * - Default: Only same origin as the request URL47 * @param {string|string[]|(secFetchSite: string, context: Context) => boolean} [options.secFetchSite] -48 * Sec-Fetch-Site header validation. Standard values include 'same-origin', 'same-site', 'cross-site', 'none'.49 * - string: Single allowed value (e.g., 'same-origin')50 * - string[]: Multiple allowed values (e.g., ['same-origin', 'same-site'])51 * - function: Custom validation with access to context52 * - Default: Only allows 'same-origin'53 * @returns {MiddlewareHandler} The middleware handler function.54 *55 * @example56 * ```ts57 * const app = new Hono()58 *59 * // Default: both origin and sec-fetch-site validation60 * app.use('*', csrf())61 *62 * // Allow specific origins63 * app.use('*', csrf({ origin: 'https://example.com' }))64 * app.use('*', csrf({ origin: ['https://app.com', 'https://api.com'] }))65 *66 * // Allow specific sec-fetch-site values67 * app.use('*', csrf({ secFetchSite: 'same-origin' }))68 * app.use('*', csrf({ secFetchSite: ['same-origin', 'same-site'] }))69 *70 * // Dynamic sec-fetch-site validation71 * app.use('*', csrf({72 * secFetchSite: (secFetchSite, c) => {73 * // Always allow same-origin74 * if (secFetchSite === 'same-origin') return true75 * // Allow cross-site for webhook endpoints76 * if (secFetchSite === 'cross-site' && c.req.path.startsWith('/webhook/')) {77 * return true78 * }79 * return false80 * }81 * }))82 *83 * // Dynamic origin validation84 * app.use('*', csrf({85 * origin: (origin, c) => {86 * // Allow same origin87 * if (origin === new URL(c.req.url).origin) return true88 * // Allow specific trusted domains89 * return ['https://app.example.com', 'https://admin.example.com'].includes(origin)90 * }91 * }))92 * ```93 */94export const csrf = (options?: CSRFOptions): MiddlewareHandler => {95 const originHandler: IsAllowedOriginHandler = ((optsOrigin) => {96 if (!optsOrigin) {97 return (origin, c) => origin === new URL(c.req.url).origin98 } else if (typeof optsOrigin === 'string') {99 return (origin) => origin === optsOrigin100 } else if (typeof optsOrigin === 'function') {101 return optsOrigin102 } else {103 return (origin) => optsOrigin.includes(origin)104 }105 })(options?.origin)106 const isAllowedOrigin = async (origin: string | undefined, c: Context) => {107 if (origin === undefined) {108 // denied always when origin header is not present109 return false110 }111 return await originHandler(origin, c)112 }113114 const secFetchSiteHandler: IsAllowedSecFetchSiteHandler = ((optsSecFetchSite) => {115 if (!optsSecFetchSite) {116 // Default: only allow same-origin117 return (secFetchSite) => secFetchSite === 'same-origin'118 } else if (typeof optsSecFetchSite === 'string') {119 return (secFetchSite) => secFetchSite === optsSecFetchSite120 } else if (typeof optsSecFetchSite === 'function') {121 return optsSecFetchSite122 } else {123 return (secFetchSite) => optsSecFetchSite.includes(secFetchSite)124 }125 })(options?.secFetchSite)126 const isAllowedSecFetchSite = async (secFetchSite: string | undefined, c: Context) => {127 if (secFetchSite === undefined) {128 // denied always when sec-fetch-site header is not present129 return false130 }131 // type guard to check if the value is a valid SecFetchSite132 if (!isSecFetchSite(secFetchSite)) {133 return false134 }135 return await secFetchSiteHandler(secFetchSite, c)136 }137138 return async function csrf(c, next) {139 if (140 !isSafeMethodRe.test(c.req.method) &&141 isRequestedByFormElementRe.test(c.req.header('content-type') || 'text/plain') &&142 !(await isAllowedSecFetchSite(c.req.header('sec-fetch-site'), c)) &&143 !(await isAllowedOrigin(c.req.header('origin'), c))144 ) {145 const res = new Response('Forbidden', { status: 403 })146 throw new HTTPException(403, { res })147 }148149 await next()150 }151}