From d5459cbcb97f2946b5829fcc5b8bb010a28ec884 Mon Sep 17 00:00:00 2001 From: Jonatan Nilsson Date: Wed, 15 Nov 2023 09:56:34 +0000 Subject: [PATCH] cors: Add specific support for supporting all origin --- flaska.mjs | 3 ++- package.json | 2 +- test/middlewares.test.mjs | 21 +++++++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/flaska.mjs b/flaska.mjs index 1f8d176..db51c89 100644 --- a/flaska.mjs +++ b/flaska.mjs @@ -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 } diff --git a/package.json b/package.json index ec66df1..d3bc283 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/test/middlewares.test.mjs b/test/middlewares.test.mjs index e365aad..8857520 100644 --- a/test/middlewares.test.mjs +++ b/test/middlewares.test.mjs @@ -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() {