index.ts
This file
Path
src/middleware/cors/index.ts
164 lines 路 5.3 KiB 路 TypeScript
Last changed by
fix(cors): append Origin to Vary header on OPTIONS preflight (#5235)Nanasibefore adoption8bf03c3
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165/** * @module * CORS Middleware for Hono. */
import type { Context } from '../../context'import type { MiddlewareHandler } from '../../types'
type CORSOptions = { origin?: | string | string[] | (( origin: string, c: Context ) => Promise<string | undefined | null> | string | undefined | null) allowMethods?: string[] | ((origin: string, c: Context) => Promise<string[]> | string[]) allowHeaders?: string[] maxAge?: number credentials?: boolean exposeHeaders?: string[]}
/** * CORS Middleware for Hono. * * @see {@link https://hono.dev/docs/middleware/builtin/cors} * * @param {CORSOptions} [options] - The options for the CORS middleware. * @param {string | string[] | ((origin: string, c: Context) => Promise<string | undefined | null> | string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header. * @param {string[] | ((origin: string, c: Context) => Promise<string[]> | string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']] - The value of "Access-Control-Allow-Methods" CORS header. * @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header. * @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header. * @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header. * @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header. * @returns {MiddlewareHandler} The middleware handler function. * * @example * ```ts * const app = new Hono() * * app.use('/api/*', cors()) * app.use( * '/api2/*', * cors({ * origin: 'http://example.com', * allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'], * allowMethods: ['POST', 'GET', 'OPTIONS'], * exposeHeaders: ['Content-Length', 'X-Kuma-Revision'], * maxAge: 600, * credentials: true, * }) * ) * * app.all('/api/abc', (c) => { * return c.json({ success: true }) * }) * app.all('/api2/abc', (c) => { * return c.json({ success: true }) * }) * ``` */export const cors = (options?: CORSOptions): MiddlewareHandler => { const opts = { origin: '*', allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY'], allowHeaders: [], exposeHeaders: [], ...options, } satisfies CORSOptions
const exposeHeadersStr = opts.exposeHeaders?.length ? opts.exposeHeaders.join(',') : undefined const allowHeadersStr = opts.allowHeaders?.length ? opts.allowHeaders.join(',') : undefined
const findAllowOrigin = ((optsOrigin) => { if (typeof optsOrigin === 'string') { if (optsOrigin === '*') { return () => optsOrigin } else { return (origin: string) => (optsOrigin === origin ? origin : null) } } else if (typeof optsOrigin === 'function') { return optsOrigin } else { return (origin: string) => (optsOrigin.includes(origin) ? origin : null) } })(opts.origin)
const findAllowMethods = ((optsAllowMethods) => { if (typeof optsAllowMethods === 'function') { return async (origin: string, c: Context) => (await optsAllowMethods(origin, c)).join(',') } else if (Array.isArray(optsAllowMethods)) { const methodsStr = optsAllowMethods.join(',') return () => methodsStr } else { return () => '' } })(opts.allowMethods)
return async function cors(c, next) { function set(key: string, value: string) { c.res.headers.set(key, value) }
const allowOrigin = await findAllowOrigin(c.req.header('origin') || '', c) if (allowOrigin) { set('Access-Control-Allow-Origin', allowOrigin) }
if (opts.credentials) { set('Access-Control-Allow-Credentials', 'true') }
if (exposeHeadersStr) { set('Access-Control-Expose-Headers', exposeHeadersStr) }
if (c.req.method === 'OPTIONS') { if (opts.origin !== '*') { c.res.headers.append('Vary', 'Origin') }
if (opts.maxAge != null) { set('Access-Control-Max-Age', opts.maxAge.toString()) }
const allowMethods = await findAllowMethods(c.req.header('origin') || '', c) if (allowMethods) { set('Access-Control-Allow-Methods', allowMethods) }
let headersStr = allowHeadersStr if (!headersStr) { const requestHeaders = c.req.header('Access-Control-Request-Headers') if (requestHeaders) { headersStr = requestHeaders .split(',') .map((h) => h.trim()) .join(',') } } if (headersStr) { set('Access-Control-Allow-Headers', headersStr) c.res.headers.append('Vary', 'Access-Control-Request-Headers') }
c.res.headers.delete('Content-Length') c.res.headers.delete('Content-Type')
return new Response(null, { headers: c.res.headers, status: 204, statusText: 'No Content', }) } await next()
// Suppose the server sends a response with an Access-Control-Allow-Origin value with an explicit origin (rather than the "*" wildcard). // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin if (opts.origin !== '*') { c.header('Vary', 'Origin', { append: true }) } }}