CVE-2023-49803: Origin Validation Error (CWE-346)
value: @koa/cors npm provides Cross-Origin Resource Sharing (CORS) for koa, a web framework for Node.js. Prior to version 5.0.0, the middleware operates in a way that if an allowed origin is not provided, it will return an `Access-Control-Allow-Origin` header with the value of the origin from the request. This behavior completely disables one of the most crucial elements of browsers - the Same Origin Policy (SOP), this could cause a very serious security threat to the users of this middleware. If such behavior is expected, for instance, when middleware is used exclusively for prototypes and not for production applications, it should be heavily emphasized in the documentation along with an indication of the risks associated with such behavior, as many users may not be aware of it. Version 5.0.0 fixes this vulnerability.
CWE description: The product does not properly verify that the source of data or communication is valid.
CVSS v3 base score: 7.5
Published: 2023-12-11T23:15Z
Repository: https://github.com/koajs/cors
Language: JavaScript
Files changed: .github/workflows/nodejs.yml, README.md, index.js, package.json, test/cors.test.js
Commit date: 2023-12-11 09:46:27 +0800
Commit message: Merge pull request from GHSA-qxrj-hx23-xp82

This is a security update for the Same Origin Policy (SOP),
and also a BREAKING CHANGE.

closes https://github.com/koajs/cors/security/advisories/GHSA-qxrj-hx23-xp82
Diff: diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml
index c61567a..9471deb 100644
--- a/.github/workflows/nodejs.yml
+++ b/.github/workflows/nodejs.yml
@@ -10,21 +10,19 @@ on:
       - master
   pull_request:
     branches:
       - main
       - master
-  schedule:
-    - cron: '0 2 * * *'
 
 jobs:
   build:
     runs-on: ${{ matrix.os }}
 
     strategy:
       fail-fast: false
       matrix:
-        node-version: [14, 16, 18]
+        node-version: [14, 16, 18, 20]
         os: [ubuntu-latest]
 
     steps:
     - name: Checkout Git Source
       uses: actions/checkout@v2
diff --git a/README.md b/README.md
index 2f23a50..8eb3bdb 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,6 @@
-@koa/cors
-=======
+# @koa/cors
 
 [![NPM version][npm-image]][npm-url]
 [![Node.js CI](https://github.com/koajs/cors/actions/workflows/nodejs.yml/badge.svg)](https://github.com/koajs/cors/actions/workflows/nodejs.yml)
 [![Test coverage][codecov-image]][codecov-url]
 [![npm download][download-image]][download-url]
@@ -41,11 +40,12 @@ app.use(cors());
 ```js
 /**
  * CORS middleware
  *
  * @param {Object} [options]
- *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is request Origin header
+ *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is '*'
+ *    If `credentials` set and return `true, the `origin` default value will set to the request `Origin` header
  *  - {String|Array} allowMethods `Access-Control-Allow-Methods`, default is 'GET,HEAD,PUT,POST,DELETE,PATCH'
  *  - {String|Array} exposeHeaders `Access-Control-Expose-Headers`
  *  - {String|Array} allowHeaders `Access-Control-Allow-Headers`
  *  - {String|Number} maxAge `Access-Control-Max-Age` in seconds
  *  - {Boolean|Function(ctx)} credentials `Access-Control-Allow-Credentials`, default is false.
@@ -55,10 +55,22 @@ app.use(cors());
  * @return {Function} cors middleware
  * @api public
  */
 ```
 
+## Breaking change between 5.0 and 4.0
+
+The default `origin` is set to `*`, if you want to keep the 4.0 behavior, you can set the `origin` handler like this:
+
+```js
+app.use(cors({
+  origin(ctx) {
+    return ctx.get('Origin') || '*';
+  },
+}));
+```
+
 ## License
 
 [MIT](./LICENSE)
 
 <!-- GITCONTRIBUTOR_START -->
diff --git a/index.js b/index.js
index 41945b8..5be3702 100644
--- a/index.js
+++ b/index.js
@@ -1,14 +1,13 @@
-'use strict';
-
 const vary = require('vary');
 
 /**
  * CORS middleware
  *
  * @param {Object} [options]
- *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is request Origin header
+ *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is '*'
+ *    If `credentials` set and return `true, the `origin` default value will set to the request `Origin` header
  *  - {String|Array} allowMethods `Access-Control-Allow-Methods`, default is 'GET,HEAD,PUT,POST,DELETE,PATCH'
  *  - {String|Array} exposeHeaders `Access-Control-Expose-Headers`
  *  - {String|Array} allowHeaders `Access-Control-Allow-Headers`
  *  - {String|Number} maxAge `Access-Control-Max-Age` in seconds
  *  - {Boolean|Function(ctx)} credentials `Access-Control-Allow-Credentials`
@@ -59,13 +58,15 @@ module.exports = function(options) {
     ctx.vary('Origin');
 
     let origin;
     if (typeof options.origin === 'function') {
       origin = await options.origin(ctx);
-      if (!origin) return await next();
+      if (!origin) {
+        return await next();
+      }
     } else {
-      origin = options.origin || requestOrigin;
+      origin = options.origin || '*';
     }
 
     let credentials;
     if (typeof options.credentials === 'function') {
       credentials = await options.credentials(ctx);
diff --git a/package.json b/package.json
index 3b6fd7e..582c312 100644
--- a/package.json
+++ b/package.json
@@ -44,11 +44,11 @@
   ],
   "engines": {
     "node": ">= 14.0.0"
   },
   "ci": {
-    "version": "14, 16, 18",
+    "version": "14, 16, 18, 20",
     "os": "linux"
   },
   "author": "fengmk2 <fengmk2@gmail.com> (http://github.com/fengmk2)",
   "license": "MIT"
 }
diff --git a/test/cors.test.js b/test/cors.test.js
index 6d0ebda..84a5679 100644
--- a/test/cors.test.js
+++ b/test/cors.test.js
@@ -1,7 +1,5 @@
-'use strict';
-
 const assert = require('assert');
 const Koa = require('koa');
 const request = require('supertest');
 const cors = require('..');
 
@@ -11,36 +9,33 @@ describe('cors.test.js', function() {
     app.use(cors());
     app.use(function(ctx) {
       ctx.body = { foo: 'bar' };
     });
 
-    it('should not set `Access-Control-Allow-Origin` when request Origin header missing', function(done) {
+    it('should set `Access-Control-Allow-Origin` to `*` when request Origin header missing', function(done) {
       request(app.listen())
         .get('/')
         .expect({ foo: 'bar' })
-        .expect(200, function(err, res) {
-          assert(!err);
-          assert(!res.headers['access-control-allow-origin']);
-          done();
-        });
+        .expect('access-control-allow-origin', '*')
+        .expect(200, done);
     });
 
-    it('should set `Access-Control-Allow-Origin` to request origin header', function(done) {
+    it('should set `Access-Control-Allow-Origin` to `*`', function(done) {
       request(app.listen())
         .get('/')
         .set('Origin', 'http://koajs.com')
-        .expect('Access-Control-Allow-Origin', 'http://koajs.com')
+        .expect('Access-Control-Allow-Origin', '*')
         .expect({ foo: 'bar' })
         .expect(200, done);
     });
 
     it('should 204 on Preflight Request', function(done) {
       request(app.listen())
         .options('/')
         .set('Origin', 'http://koajs.com')
         .set('Access-Control-Request-Method', 'PUT')
-        .expect('Access-Control-Allow-Origin', 'http://koajs.com')
+        .expect('Access-Control-Allow-Origin', '*')
         .expect('Access-Control-Allow-Methods', 'GET,HEAD,PUT,POST,DELETE,PATCH')
         .expect(204, done);
     });
 
     it('should not Preflight Request if request missing Access-Control-Request-Method', function(done) {
@@ -85,10 +80,48 @@ describe('cors.test.js', function() {
         .expect({ foo: 'bar' })
         .expect(200, done);
     });
   });
 
+  describe('options.origin set the request Origin header', function() {
+    const app = new Koa();
+    app.use(cors({
+      origin(ctx) {
+        return ctx.get('Origin') || '*';
+      },
+    }));
+    app.use(function(ctx) {
+      ctx.body = { foo: 'bar' };
+    });
+
+    it('should set `Access-Control-Allow-Origin` to request `Origin` header', function(done) {
+      request(app.listen())
+        .get('/')
+        .set('Origin', 'http://koajs.com')
+        .expect('Access-Control-Allow-Origin', 'http://koajs.com')
+        .expect({ foo: 'bar' })
+        .expect(200, done);
+    });
+
+    it('should set `Access-Control-Allow-Origin` to request `origin` header', function(done) {
+      request(app.listen())
+        .get('/')
+        .set('origin', 'http://origin.koajs.com')
+        .expect('Access-Control-Allow-Origin', 'http://origin.koajs.com')
+        .expect({ foo: 'bar' })
+        .expect(200, done);
+    });
+
+    it('should set `Access-Control-Allow-Origin` to `*`, even if no Origin is passed on request', function(done) {
+      request(app.listen())
+        .get('/')
+        .expect('Access-Control-Allow-Origin', '*')
+        .expect({ foo: 'bar' })
+        .expect(200, done);
+    });
+  });
+
   describe('options.secureContext=true', function() {
     const app = new Koa();
     app.use(cors({
       secureContext: true,
     }));
@@ -649,11 +682,15 @@ describe('cors.test.js', function() {
   });
 
   describe('options.headersKeptOnError', function() {
     it('should keep CORS headers after an error', function(done) {
       const app = new Koa();
-      app.use(cors());
+      app.use(cors({
+        origin(ctx) {
+          return ctx.get('Origin') || '*';
+        },
+      }));
       app.use(function(ctx) {
         ctx.body = { foo: 'bar' };
         throw new Error('Whoops!');
       });
 
@@ -666,11 +703,15 @@ describe('cors.test.js', function() {
         .expect(500, done);
     });
 
     it('should not affect OPTIONS requests', function(done) {
       const app = new Koa();
-      app.use(cors());
+      app.use(cors({
+        origin(ctx) {
+          return ctx.get('Origin') || '*';
+        },
+      }));
       app.use(function(ctx) {
         ctx.body = { foo: 'bar' };
         throw new Error('Whoops!');
       });
 
@@ -682,11 +723,15 @@ describe('cors.test.js', function() {
         .expect(204, done);
     });
 
     it('should not keep unrelated headers', function(done) {
       const app = new Koa();
-      app.use(cors());
+      app.use(cors({
+        origin(ctx) {
+          return ctx.get('Origin') || '*';
+        },
+      }));
       app.use(function(ctx) {
         ctx.body = { foo: 'bar' };
         ctx.set('X-Example', 'Value');
         throw new Error('Whoops!');
       });
@@ -750,10 +795,11 @@ describe('cors.test.js', function() {
         .expect('Vary', 'Accept-Encoding, Origin')
         .expect({ foo: 'bar' })
         .expect(200, done);
     });
   });
+
   describe('other middleware has set vary header on Error', function() {
     it('should append `Origin to other `Vary` header', function(done) {
       const app = new Koa();
       app.use(cors());
 

Vulnerable code:   schedule:
    - cron: '0 2 * * *'
        node-version: [14, 16, 18]
@koa/cors
=======
 *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is request Origin header
'use strict';

 *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is request Origin header
      if (!origin) return await next();
      origin = options.origin || requestOrigin;
    "version": "14, 16, 18",
'use strict';

    it('should not set `Access-Control-Allow-Origin` when request Origin header missing', function(done) {
        .expect(200, function(err, res) {
          assert(!err);
          assert(!res.headers['access-control-allow-origin']);
          done();
        });
    it('should set `Access-Control-Allow-Origin` to request origin header', function(done) {
        .expect('Access-Control-Allow-Origin', 'http://koajs.com')
        .expect('Access-Control-Allow-Origin', 'http://koajs.com')
      app.use(cors());
      app.use(cors());
      app.use(cors());
Fixed code:         node-version: [14, 16, 18, 20]
# @koa/cors
 *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is '*'
 *    If `credentials` set and return `true, the `origin` default value will set to the request `Origin` header
## Breaking change between 5.0 and 4.0

The default `origin` is set to `*`, if you want to keep the 4.0 behavior, you can set the `origin` handler like this:

```js
app.use(cors({
  origin(ctx) {
    return ctx.get('Origin') || '*';
  },
}));
```

 *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is '*'
 *    If `credentials` set and return `true, the `origin` default value will set to the request `Origin` header
      if (!origin) {
        return await next();
      }
      origin = options.origin || '*';
    "version": "14, 16, 18, 20",
    it('should set `Access-Control-Allow-Origin` to `*` when request Origin header missing', function(done) {
        .expect('access-control-allow-origin', '*')
        .expect(200, done);
    it('should set `Access-Control-Allow-Origin` to `*`', function(done) {
        .expect('Access-Control-Allow-Origin', '*')
        .expect('Access-Control-Allow-Origin', '*')
  describe('options.origin set the request Origin header', function() {
    const app = new Koa();
    app.use(cors({
      origin(ctx) {
        return ctx.get('Origin') || '*';
      },
    }));
    app.use(function(ctx) {
      ctx.body = { foo: 'bar' };
    });

    it('should set `Access-Control-Allow-Origin` to request `Origin` header', function(done) {
      request(app.listen())
        .get('/')
        .set('Origin', 'http://koajs.com')
        .expect('Access-Control-Allow-Origin', 'http://koajs.com')
        .expect({ foo: 'bar' })
        .expect(200, done);
    });

    it('should set `Access-Control-Allow-Origin` to request `origin` header', function(done) {
      request(app.listen())
        .get('/')
        .set('origin', 'http://origin.koajs.com')
        .expect('Access-Control-Allow-Origin', 'http://origin.koajs.com')
        .expect({ foo: 'bar' })
        .expect(200, done);
    });

    it('should set `Access-Control-Allow-Origin` to `*`, even if no Origin is passed on request', function(done) {
      request(app.listen())
        .get('/')
        .expect('Access-Control-Allow-Origin', '*')
        .expect({ foo: 'bar' })
        .expect(200, done);
    });
  });

      app.use(cors({
        origin(ctx) {
          return ctx.get('Origin') || '*';
        },
      }));
      app.use(cors({
        origin(ctx) {
          return ctx.get('Origin') || '*';
        },
      }));
      app.use(cors({
        origin(ctx) {
          return ctx.get('Origin') || '*';
        },
      }));