From 9db582d2af35936f0347572163a17aeaef290aaf Mon Sep 17 00:00:00 2001 From: Douglas Christopher Wilson Date: Tue, 22 Mar 2022 23:57:02 -0400 Subject: [PATCH] Fix error message for json parse whitespace in strict --- HISTORY.md | 1 + lib/types/json.js | 12 +++++++++--- test/json.js | 8 ++++++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 1e3560e0..b432583a 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,6 +1,7 @@ unreleased ========== + * Fix error message for json parse whitespace in `strict` * Prevent loss of async hooks context * Prevent hanging when request already read * deps: depd@2.0.0 diff --git a/lib/types/json.js b/lib/types/json.js index 9349cbd6..c2745be3 100644 --- a/lib/types/json.js +++ b/lib/types/json.js @@ -37,7 +37,7 @@ module.exports = json * %x0D ) ; Carriage return */ -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex /** * Create a middleware to parse JSON bodies. @@ -152,7 +152,9 @@ function json (options) { function createStrictSyntaxError (str, char) { var index = str.indexOf(char) - var partial = str.substring(0, index) + '#' + var partial = index !== -1 + ? str.substring(0, index) + '#' + : '' try { JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') @@ -173,7 +175,11 @@ function createStrictSyntaxError (str, char) { */ function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] + var match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined } /** diff --git a/test/json.js b/test/json.js index 01193dda..57cbd7ae 100644 --- a/test/json.js +++ b/test/json.js @@ -44,6 +44,14 @@ describe('bodyParser.json()', function () { .expect(200, '{}', done) }) + it('should 400 when only whitespace', function (done) { + request(createServer()) + .post('/') + .set('Content-Type', 'application/json') + .send(' \n') + .expect(400, '[entity.parse.failed] ' + parseError(' '), done) + }) + it('should 400 when invalid content-length', function (done) { var jsonParser = bodyParser.json() var server = createServer(function (req, res, next) {