diff --git a/lib/response.js b/lib/response.js index f965e539dd2..08c5ea8e925 100644 --- a/lib/response.js +++ b/lib/response.js @@ -759,7 +759,15 @@ res.cookie = function (name, value, options) { if (opts.maxAge != null) { var maxAge = opts.maxAge - 0 - if (!isNaN(maxAge)) { + if (maxAge === Infinity || maxAge === -Infinity || (typeof opts.maxAge === 'number' && isNaN(maxAge))) { + // strip non-finite numeric maxAge (Infinity, -Infinity, NaN) so the + // cookie falls back to a session cookie (no Max-Age). The typeof + // guard ensures non-numeric strings like 'foobar' still flow through + // to cookie.serialize() and throw, rather than being silently dropped. + // (String 'Infinity' coerces to numeric Infinity above and is + // intentionally stripped here, consistent with numeric Infinity.) + delete opts.maxAge + } else if (!isNaN(maxAge)) { opts.expires = new Date(Date.now() + maxAge) opts.maxAge = Math.floor(maxAge / 1000) } diff --git a/test/res.cookie.js b/test/res.cookie.js index 180d1be3452..253fe782872 100644 --- a/test/res.cookie.js +++ b/test/res.cookie.js @@ -183,6 +183,51 @@ describe('res', function(){ .get('/') .expect(500, /option maxAge is invalid/, done) }) + + it('should strip Infinity maxAge and produce a session cookie', function (done) { + var app = express() + + app.use(function (req, res) { + res.cookie('name', 'tobi', { maxAge: Infinity }) + res.end() + }) + + request(app) + .get('/') + .expect(200) + .expect('Set-Cookie', 'name=tobi; Path=/') + .end(done) + }) + + it('should strip -Infinity maxAge and produce a session cookie', function (done) { + var app = express() + + app.use(function (req, res) { + res.cookie('name', 'tobi', { maxAge: -Infinity }) + res.end() + }) + + request(app) + .get('/') + .expect(200) + .expect('Set-Cookie', 'name=tobi; Path=/') + .end(done) + }) + + it('should strip NaN maxAge and produce a session cookie', function (done) { + var app = express() + + app.use(function (req, res) { + res.cookie('name', 'tobi', { maxAge: NaN }) + res.end() + }) + + request(app) + .get('/') + .expect(200) + .expect('Set-Cookie', 'name=tobi; Path=/') + .end(done) + }) }) describe('priority', function () {