Skip to content

Commit

Permalink
[fix] Don't throw on invalid input (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
3rd-Eden authored Mar 20, 2019
1 parent e619535 commit 30e1d19
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
38 changes: 34 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

/**
Expand All @@ -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;
}

Expand Down Expand Up @@ -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);
}
}

Expand Down
13 changes: 13 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});

0 comments on commit 30e1d19

Please sign in to comment.