From 12053567ef2caa8f4191298bc9d010017bb0f233 Mon Sep 17 00:00:00 2001 From: Tyreal Hu Date: Fri, 19 Aug 2022 23:48:27 +0800 Subject: [PATCH] fix: must specify an origin value instead of "*" wildcard (#85) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS Co-authored-by: 胡文彬 --- .gitignore | 2 ++ index.js | 4 ++++ test/cors.test.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/.gitignore b/.gitignore index 8280239..c67c953 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ *.out *.pid *.gz +.idea +.DS_Store pids logs diff --git a/index.js b/index.js index 9915e82..69ccc85 100644 --- a/index.js +++ b/index.js @@ -75,6 +75,10 @@ module.exports = function(options) { credentials = !!options.credentials; } + if (credentials && origin === '*') { + origin = requestOrigin; + } + const headersSet = {}; function set(key, value) { diff --git a/test/cors.test.js b/test/cors.test.js index 6c8c22c..02b0613 100644 --- a/test/cors.test.js +++ b/test/cors.test.js @@ -889,4 +889,46 @@ describe('cors.test.js', function() { }); }); + describe('options.origin=*, and options.credentials=true', function() { + const app = new Koa(); + app.use(cors({ + origin: '*', + credentials: true, + })); + + app.use(function(ctx) { + ctx.body = { foo: 'bar' }; + }); + + it('Access-Control-Allow-Origin should be request.origin, and Access-Control-Allow-Credentials should be true', function(done) { + request(app.listen()) + .get('/') + .set('Origin', 'http://koajs.com') + .expect('Access-Control-Allow-Credentials', 'true') + .expect('Access-Control-Allow-Origin', 'http://koajs.com') + .expect({ foo: 'bar' }) + .expect(200, done); + }); + }); + + describe('options.origin=*, and options.credentials=false', function() { + const app = new Koa(); + app.use(cors({ + origin: '*', + credentials: false, + })); + + app.use(function(ctx) { + ctx.body = { foo: 'bar' }; + }); + + it('Access-Control-Allow-Origin should be *', function(done) { + request(app.listen()) + .get('/') + .set('Origin', 'http://koajs.com') + .expect('Access-Control-Allow-Origin', '*') + .expect({ foo: 'bar' }) + .expect(200, done); + }); + }); });