feat(cors): Allow async functions for `origin` and `allowMethods` (#4373)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(cors): Allow to pass origin & methods asynchronously * fix api4 -> api8 cors test ---------
authored by Joshua Brooks · committed by GitHub · parent a268569 · Browse files · 2 files·+79 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Josh Brooks <j.brooks@mwam.com>
Diff stats
2 files+79 added−6 removed
- tests:+70 added−0 removed
- other:+9 added−6 removed
Provenance
- Commit
5bfbff8- Tree
be25217- Author
Joshua Brooks <joshua.brooks.france@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
a268569
2 files changed+79 added−6 removed
modified:src/middleware/cors/index.test.ts+70 added
56 unmodified lines57 : ['GET', 'HEAD'],58 })59 )60 61+ app.use(62+ '/api8/*',63+ cors({64+ origin: (origin) =>65+ new Promise<string>((resolve) =>66+ resolve(origin.endsWith('.example.com') ? origin : 'http://example.com')67+ ),68+ })69+ )70+71+ app.use(72+ '/api9/*',73+ cors({74+ origin: (origin) =>75+ new Promise<string>((resolve) => resolve(origin === 'http://example.com' ? origin : '*')),76+ allowMethods: (origin) =>77+ new Promise<string[]>((resolve) =>78+ resolve(79+ origin === 'http://example.com'80+ ? ['GET', 'HEAD', 'POST', 'PATCH', 'DELETE']81+ : ['GET', 'HEAD']82+ )83+ ),84+ })85+ )86+87 app.get('/api/abc', (c) => {88 return c.json({ success: true })89 })90 136 unmodified lines227 res = await app.request(req)228 expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')229 })230 231+ it('Allow origins by promise returning function', async () => {232+ let req = new Request('http://localhost/api8/abc', {233+ headers: {234+ Origin: 'http://subdomain.example.com',235+ },236+ })237+ let res = await app.request(req)238+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://subdomain.example.com')239+240+ req = new Request('http://localhost/api8/abc')241+ res = await app.request(req)242+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')243+244+ req = new Request('http://localhost/api8/abc', {245+ headers: {246+ Referer: 'http://evil-example.com/',247+ },248+ })249+ res = await app.request(req)250+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')251+ })252+253 it('With raw Response object', async () => {254 const res = await app.request('http://localhost/api5/abc')255 256 expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')30 unmodified lines287 const res2 = await app.request(req2)288 expect(res2.headers.get('Access-Control-Allow-Origin')).toBe('*')289 expect(res2.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD')290 })291+292+ it('Allow methods by promise returning function', async () => {293+ const req = new Request('http://localhost/api9/abc', {294+ headers: {295+ Origin: 'http://example.com',296+ },297+ method: 'OPTIONS',298+ })299+ const res = await app.request(req)300+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')301+ expect(res.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD,POST,PATCH,DELETE')302+303+ const req2 = new Request('http://localhost/api9/abc', {304+ headers: {305+ Origin: 'http://example.org',306+ },307+ method: 'OPTIONS',308+ })309+ const res2 = await app.request(req2)310+ expect(res2.headers.get('Access-Control-Allow-Origin')).toBe('*')311+ expect(res2.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD')312+ })313 })modified:src/middleware/cors/index.ts+9 added-6 removed
5 unmodified lines678910111011121314151617184 unmodified lines23242526242527282930313264 unmodified lines9798991009810110210310410521 unmodified lines12712812913012813113213313413524 unmodified lines5 unmodified linesimport type { Context } from '../../context'import type { MiddlewareHandler } from '../../types'
type CORSOptions = { origin: string | string[] | ((origin: string, c: Context) => string | undefined | null) allowMethods?: string[] | ((origin: string, c: Context) => string[]) origin: | string | string[] | ((origin: string, c: Context) => Promise<string> | string | undefined | null) allowMethods?: string[] | ((origin: string, c: Context) => Promise<string[]> | string[]) allowHeaders?: string[] maxAge?: number credentials?: boolean exposeHeaders?: string[]4 unmodified lines * * @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) => string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header. * @param {string[] | ((origin: string, c: Context) => string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header. * @param {string | string[] | ((origin: string, c: Context) => Promise<string> | 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']] - 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.64 unmodified lines function set(key: string, value: string) { c.res.headers.set(key, value) }
const allowOrigin = findAllowOrigin(c.req.header('origin') || '', c) const allowOrigin = await findAllowOrigin(c.req.header('origin') || '', c) if (allowOrigin) { set('Access-Control-Allow-Origin', allowOrigin) }
21 unmodified lines if (opts.maxAge != null) { set('Access-Control-Max-Age', opts.maxAge.toString()) }
const allowMethods = findAllowMethods(c.req.header('origin') || '', c) const allowMethods = await findAllowMethods(c.req.header('origin') || '', c) if (allowMethods.length) { set('Access-Control-Allow-Methods', allowMethods.join(',')) }
24 unmodified lines