cors: Add specific support for supporting all origin
All checks were successful
continuous-integration/appveyor/branch AppVeyor build succeeded

This commit is contained in:
Jonatan Nilsson 2023-11-15 09:56:34 +00:00
parent 01a916eb2d
commit d5459cbcb9
3 changed files with 24 additions and 2 deletions

View file

@ -139,6 +139,7 @@ export function CorsHandler(opts = {}) {
exposeHeaders: opts.exposeHeaders || '',
maxAge: opts.maxAge || '',
}
const allowAll = options.allowedOrigins.includes('*')
return function(ctx) {
// Always add vary header on origin. Prevent caches from
@ -154,7 +155,7 @@ export function CorsHandler(opts = {}) {
// Check origin is specified. Nothing needs to be done if
// there is no origin or it doesn't match
let origin = ctx.req.headers['origin']
if (!origin || !options.allowedOrigins.includes(origin)) {
if (!origin || (!allowAll && !options.allowedOrigins.includes(origin))) {
return
}

View file

@ -1,6 +1,6 @@
{
"name": "flaska",
"version": "1.3.4",
"version": "1.3.5",
"description": "Flaska is a micro web-framework for node. It is designed to be fast, simple and lightweight, and is distributed as a single file module with no dependencies.",
"main": "flaska.mjs",
"scripts": {

View file

@ -253,6 +253,27 @@ t.describe('#CorsHandler()', function() {
assert.notOk(ctx.headers['Access-Control-Allow-Headers'])
assert.strictEqual(ctx.status, 204)
})
t.test('should set headers if allowedOrigins has a *', function() {
const assertOrigin = 'http://my.site.here'
corsHandler = CorsHandler({
allowedOrigins: ['*'],
})
ctx.req.headers['origin'] = assertOrigin
ctx.req.headers['access-control-request-method'] = 'GET'
assert.notOk(ctx.headers['Access-Control-Allow-Origin'])
assert.notOk(ctx.headers['Access-Control-Allow-Methods'])
assert.notOk(ctx.headers['Access-Control-Allow-Headers'])
corsHandler(ctx)
assert.strictEqual(ctx.headers['Vary'], 'Origin')
assert.strictEqual(ctx.headers['Access-Control-Allow-Origin'], assertOrigin)
assert.ok(ctx.headers['Access-Control-Allow-Methods'])
assert.strictEqual(ctx.status, 204)
})
})
t.describe('GET/POST/DELETE/PATCH/PUT', function() {