diff --git a/HISTORY.md b/HISTORY.md index 4bbaf17..1a7aed7 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,6 +1,7 @@ unreleased ========== + * Fix `JSONCookie` to return `undefined` for non-string arguments * deps: cookie@0.1.5 1.3.5 / 2015-05-19 diff --git a/index.js b/index.js index 616b113..f511751 100644 --- a/index.js +++ b/index.js @@ -66,17 +66,19 @@ function cookieParser(secret, options) { * Parse JSON cookie string. * * @param {String} str - * @return {Object} Parsed object or null if not json cookie + * @return {Object} Parsed object or undefined if not json cookie * @public */ function JSONCookie(str) { - if (!str || str.substr(0, 2) !== 'j:') return; + if (typeof str !== 'string' || str.substr(0, 2) !== 'j:') { + return undefined; + } try { return JSON.parse(str.slice(2)); } catch (err) { - // no op + return undefined; } } diff --git a/test/cookieParser.js b/test/cookieParser.js index 6001a4b..027d0bc 100644 --- a/test/cookieParser.js +++ b/test/cookieParser.js @@ -117,6 +117,16 @@ describe('cookieParser()', function(){ }) describe('cookieParser.JSONCookie(str)', function () { + it('should return undefined for non-string arguments', function () { + assert.strictEqual(cookieParser.JSONCookie(), undefined) + assert.strictEqual(cookieParser.JSONCookie(undefined), undefined) + assert.strictEqual(cookieParser.JSONCookie(null), undefined) + assert.strictEqual(cookieParser.JSONCookie(42), undefined) + assert.strictEqual(cookieParser.JSONCookie({}), undefined) + assert.strictEqual(cookieParser.JSONCookie([]), undefined) + assert.strictEqual(cookieParser.JSONCookie(function(){}), undefined) + }) + it('should return undefined for non-JSON cookie string', function () { assert.strictEqual(cookieParser.JSONCookie(''), undefined) assert.strictEqual(cookieParser.JSONCookie('foo'), undefined)