From 30e1d1956d474a81a0d0fec9ad4f00a928b1a2d5 Mon Sep 17 00:00:00 2001 From: Arnout Kazemier <3rd-Eden@users.noreply.github.com> Date: Wed, 20 Mar 2019 17:41:46 +0100 Subject: [PATCH] [fix] Don't throw on invalid input (#25) --- index.js | 38 ++++++++++++++++++++++++++++++++++---- test.js | 13 +++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index df6f968..a51bb93 100644 --- a/index.js +++ b/index.js @@ -7,11 +7,30 @@ var has = Object.prototype.hasOwnProperty * Decode a URI encoded string. * * @param {String} input The URI encoded string. - * @returns {String} The decoded string. + * @returns {String|Null} The decoded string. * @api private */ function decode(input) { - return decodeURIComponent(input.replace(/\+/g, ' ')); + try { + return decodeURIComponent(input.replace(/\+/g, ' ')); + } catch (e) { + return null; + } +} + +/** + * Attempts to encode a given input. + * + * @param {String} input The string that needs to be encoded. + * @returns {String|Null} The encoded string. + * @api private + */ +function encode(input) { + try { + return encodeURIComponent(input); + } catch (e) { + return null; + } } /** @@ -35,7 +54,10 @@ function querystring(query) { // methods like `toString` or __proto__ are not overriden by malicious // querystrings. // - if (key in result) continue; + // In the case if failed decoding, we want to omit the key/value pairs + // from the result. + // + if (key === null || value === null || key in result) continue; result[key] = value; } @@ -74,7 +96,15 @@ function querystringify(obj, prefix) { value = ''; } - pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(value)); + key = encodeURIComponent(key); + value = encodeURIComponent(value); + + // + // If we failed to encode the strings, we should bail out as we don't + // want to add invalid strings to the query. + // + if (key === null || value === null) continue; + pairs.push(key +'='+ value); } } diff --git a/test.js b/test.js index 0072cd7..6e6d356 100644 --- a/test.js +++ b/test.js @@ -104,5 +104,18 @@ describe('querystringify', function () { assume(obj).is.a('object'); assume(obj['foo bar']).equals('baz+qux'); }); + + it('does not throw on invalid input', function () { + var obj = qs.parse('?%&'); + + assume(obj).is.a('object'); + }); + + it('does not include invalid output', function () { + var obj = qs.parse('?%&'); + + assume(obj).is.a('object'); + assume(obj).is.length(0); + }); }); });