From 32776085376a4347cb2fc277baeb91f548086ced Mon Sep 17 00:00:00 2001 From: Einar Pehrson Date: Fri, 10 Jul 2026 12:25:28 +0200 Subject: [PATCH] fix: catch errors in normalizeType instead of letting them throw normalizeType() no longer catches errors from content-type.parse() or media-typer.test(), unlike 1.x's tryNormalizeType. Since content-type@2 became more lenient and can return an empty type string for a malformed Content-Type header (e.g. ";" or an all-whitespace value), that empty string reaches media-typer.test(), which throws on falsy input rather than returning false. This means a request with a malformed but present Content-Type header (combined with a Content-Length or Transfer-Encoding header) crashes typeis()/typeofrequest() with an uncaught TypeError, instead of returning false/null like it does for a missing Content-Type header or other invalid media types. Restore the try/catch so normalizeType degrades to null on any parse/test failure, matching the historical behavior. --- index.js | 8 ++++++-- test/test.js | 11 +++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 37d6da3..89c9b90 100644 --- a/index.js +++ b/index.js @@ -234,7 +234,11 @@ function mimeMatch (expected, actual) { */ function normalizeType (value) { if (!value) return null - var type = contentType.parse(value, { parameters: false }).type - return typer.test(type) ? type : null + try { + var type = contentType.parse(value, { parameters: false }).type + return typer.test(type) ? type : null + } catch (err) { + return null + } } diff --git a/test/test.js b/test/test.js index 4443196..434b676 100644 --- a/test/test.js +++ b/test/test.js @@ -29,6 +29,17 @@ describe('typeis(req, types)', function () { assert.strictEqual(typeis(req, [undefined, null, true, function () {}]), false) }) + it('should not throw on a Content-Type with an empty type token', function () { + // A Content-Type header where the portion before the first ";" (after + // trimming optional whitespace) is empty - e.g. ";" or " " - causes + // content-type@2's lenient parse() to return type: "". media-typer's + // test() then throws on that falsy input instead of returning false, + // and normalizeType() no longer catches it (unlike 1.x's + // tryNormalizeType, which wrapped this in a try/catch). + var req = createRequest(';') + assert.strictEqual(typeis(req, ['urlencoded']), false) + }) + describe('when no body is given', function () { it('should return null', function () { var req = { headers: {} }