Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@
return headers;
}

function validateCredentialsAndOrigin(options) {
if (options.credentials === true && options.origin === '*') {
throw new Error('Cross-origin requests are not allowed when credentials are set to true with origin: "*". ' +
'See https://fetch.spec.whatwg.org/#cors-protocol-and-credentials');
}
}

function configureMethods(options) {
var methods = options.methods;
if (methods.join) {
Expand Down Expand Up @@ -160,6 +167,8 @@
var headers = [],
method = req.method && req.method.toUpperCase && req.method.toUpperCase();

validateCredentialsAndOrigin(options);

if (method === 'OPTIONS') {
// preflight
headers.push(configureOrigin(options, req));
Expand Down
35 changes: 35 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -729,3 +729,38 @@ FakeResponse.prototype.setHeader = function setHeader (name, value) {
var key = name.toLowerCase()
this._headers[key] = value
}

describe('credentials with origin "*"', function () {
it('throws an error when origin is "*" and credentials is true', function (done) {
var req = fakeRequest('GET');
var res = fakeResponse();
var next = function (err) {
if (err && err.message.indexOf('credentials') !== -1 && err.message.indexOf('origin') !== -1) {
done();
} else {
done(new Error('Expected error about credentials and origin, got: ' + (err ? err.message : 'no error')));
}
};

assert.throws(function () {
cors({ origin: '*', credentials: true })(req, res, next);
}, /Cross-origin requests are not allowed when credentials are set to true with origin/);
done();
});

it('allows origin "*" when credentials is false', function (done) {
var cb = after(1, done);
var req = fakeRequest('GET');
var res = new FakeResponse();

res.on('finish', function () {
assert.equal(res.getHeader('Access-Control-Allow-Origin'), '*');
assert.equal(res.getHeader('Access-Control-Allow-Credentials'), undefined);
cb();
});

cors({ origin: '*', credentials: false })(req, res, function (err) {
cb(err || new Error('should not be called'));
});
});
});