From 042073f1d679b9c7fb7d64660d3c6d372bd1f468 Mon Sep 17 00:00:00 2001 From: Douglas Christopher Wilson Date: Tue, 29 Mar 2022 17:25:05 -0400 Subject: [PATCH] Fix expires option to reject invalid dates --- HISTORY.md | 1 + index.js | 19 +++++++++++++++++-- test/serialize.js | 4 ++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 985e359..f58a165 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -2,6 +2,7 @@ unreleased ========== * Add `priority` option + * Fix `expires` option to reject invalid dates 0.4.2 / 2022-02-02 ================== diff --git a/index.js b/index.js index 57d545e..31f6c7d 100644 --- a/index.js +++ b/index.js @@ -20,6 +20,7 @@ exports.serialize = serialize; * @private */ +var __toString = Object.prototype.toString var decode = decodeURIComponent; var encode = encodeURIComponent; @@ -145,11 +146,13 @@ function serialize(name, val, options) { } if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { + var expires = opt.expires + + if (!isDate(expires) || isNaN(expires.valueOf())) { throw new TypeError('option expires is invalid'); } - str += '; Expires=' + opt.expires.toUTCString(); + str += '; Expires=' + expires.toUTCString() } if (opt.httpOnly) { @@ -205,6 +208,18 @@ function serialize(name, val, options) { return str; } +/** + * Determine if value is a Date. + * + * @param {*} val + * @private + */ + +function isDate (val) { + return __toString.call(val) === '[object Date]' || + val instanceof Date +} + /** * Try decoding a string using a decoding function. * diff --git a/test/serialize.js b/test/serialize.js index 57ac661..06c8207 100644 --- a/test/serialize.js +++ b/test/serialize.js @@ -67,6 +67,10 @@ test('expires', function() { assert.throws(cookie.serialize.bind(cookie, 'foo', 'bar', { expires: Date.now() }), /option expires is invalid/); + + assert.throws(cookie.serialize.bind(cookie, 'foo', 'bar', { + expires: new Date(NaN) + }), /option expires is invalid/) }); test('priority', function () {