Skip to content

Commit

Permalink
fix: use new URL instead of url.parse (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
dead-horse committed Nov 14, 2019
1 parent 7ae83b3 commit 7990aa7
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 4 deletions.
15 changes: 12 additions & 3 deletions app.js
@@ -1,6 +1,7 @@
'use strict';

const url = require('url');
// there is no global.URL in node 8
const URL = require('url').URL;

module.exports = app => {
// put before other core middlewares
Expand All @@ -12,8 +13,16 @@ module.exports = app => {
const origin = ctx.get('origin');
if (!origin) return '';

const parsedUrl = url.parse(origin);
if (!ctx.isSafeDomain || ctx.isSafeDomain(parsedUrl.hostname) || ctx.isSafeDomain(origin)) {
if (typeof ctx.isSafeDomain !== 'function') return origin;

let parsedUrl;
try {
parsedUrl = new URL(origin);
} catch (err) {
return '';
}

if (ctx.isSafeDomain(parsedUrl.hostname) || ctx.isSafeDomain(origin)) {
return origin;
}
return '';
Expand Down
1 change: 1 addition & 0 deletions appveyor.yml
Expand Up @@ -2,6 +2,7 @@ environment:
matrix:
- nodejs_version: '8'
- nodejs_version: '10'
- nodejs_version: '12'

install:
- ps: Install-Product node $env:nodejs_version
Expand Down
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -50,7 +50,7 @@
"url": "https://github.com/eggjs/egg/issues"
},
"ci": {
"version": "8, 10"
"version": "8, 10, 12"
},
"author": "dead_horse"
}
24 changes: 24 additions & 0 deletions test/cors.test.js
Expand Up @@ -108,4 +108,28 @@ describe('test/cors.test.js', () => {
})
.expect(200);
});

it('should not set `Access-Control-Allow-Origin` when origin = http://eggjs.org!.evil.com', () => {
app.mockCsrf();
return request(app.callback())
.get('/')
.set('Origin', 'http://eggjs.org!.evil.com')
.expect(res => {
assert(!res.headers['access-control-allow-origin']);
assert(!res.headers['access-control-allow-credentials']);
})
.expect(200);
});

it('should not set `Access-Control-Allow-Origin` when origin = /foo', () => {
app.mockCsrf();
return request(app.callback())
.get('/')
.set('Origin', '/foo')
.expect(res => {
assert(!res.headers['access-control-allow-origin']);
assert(!res.headers['access-control-allow-credentials']);
})
.expect(200);
});
});

0 comments on commit 7990aa7

Please sign in to comment.