From e303cb3a4b6f24cbd448fd5e9c4e4be017b18ef1 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 24 Oct 2026 15:52:28 -0500 Subject: [PATCH 1/2] fix(http): choose the body parser by the media type (GitHub #36) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit parseRequestBody picked JSON, urlencoded or multipart with contentType.includes() on the raw header. That is case-sensitive, so a valid `Application/JSON` reached the handler as a string, and it matches anywhere in the header, so a parameter could choose the parser: `text/plain; x=application/json` was parsed as JSON. The media type is now taken from the part before any `;`, trimmed and lowercased (RFC 9110 §8.3.1), and compared exactly. The boundary is still read from the full header. A type that merely contains one of the three no longer selects its parser. `application/json-patch+json` used to be parsed as JSON and now arrives as text, as other `+json` types always have. CHANGELOG says so. test/http.test.ts sends both cases from the issue, plus their urlencoded equivalents, through the Node server. Signed-off-by: Diego Resendez --- CHANGELOG.md | 8 ++++++++ src/http/body.ts | 18 +++++++++++++++--- test/http.test.ts | 19 +++++++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc1807d..9e4681d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -266,6 +266,14 @@ npm treats versions as semver and semver forbids leading zeros. fails with ` @Module metadata is missing mountpoint`. `mountpoint: ''` still mounts at the root. +- **The body parser is chosen by the media type** (GitHub #36). It was chosen by a substring of + the raw `Content-Type` header, case-sensitively, so `Content-Type: Application/JSON` reached the + handler as a string while `text/plain; x=application/json` was parsed as JSON. The same applied + to urlencoded and multipart bodies. The parser now compares the media type, the part before any + `;`, trimmed and lowercased, exactly. **A type that only contains one of the three no longer + selects its parser:** `application/json-patch+json` used to be parsed as JSON and now arrives as + text, like any other `+json` type always has. Parse it in the handler. + - **`listen()` rejects when the port is taken** (#138). A bind failure such as `EADDRINUSE` or `EACCES` arrives as the server's `error` event, which `listen()` did not handle: the promise never settled, and the error surfaced as an unhandled one. It now rejects with that error. The diff --git a/src/http/body.ts b/src/http/body.ts index b5902fb..c1f7f9d 100644 --- a/src/http/body.ts +++ b/src/http/body.ts @@ -49,6 +49,16 @@ export function declaresOverLimit(contentLength: string | null | undefined, limi return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit; } +/** + * The media type of a Content-Type value: the part before any parameters, trimmed and lowercased, + * since media types are case-insensitive (RFC 9110 §8.3.1). Matching a substring of the raw header + * instead let a parameter choose the parser: `text/plain; x=application/json` was parsed as JSON. + */ +function mediaType(contentType: string): string { + const semi = contentType.indexOf(';'); + return (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase(); +} + /** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */ type ParseResult = { body: unknown } | { error: string; status?: number }; @@ -62,7 +72,9 @@ export async function parseRequestBody( duplicates: 'array' | 'last', maxParts: number, ): Promise { - if (buf !== undefined && contentType.includes('application/json')) { + const type = mediaType(contentType); + + if (buf !== undefined && type === 'application/json') { try { return { body: JSON.parse(buf.toString('utf8')) }; } catch { @@ -70,11 +82,11 @@ export async function parseRequestBody( } } - if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) { + if (buf !== undefined && type === 'application/x-www-form-urlencoded') { return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) }; } - if (buf !== undefined && contentType.includes('multipart/form-data')) { + if (buf !== undefined && type === 'multipart/form-data') { const boundary = extractBoundary(contentType); if (!boundary) return { error: 'Invalid multipart body' }; diff --git a/test/http.test.ts b/test/http.test.ts index 6113aa6..0225be5 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -380,6 +380,25 @@ describe('request hardening', () => { server.close(); }); + // GitHub #36: the parser is chosen by the media type alone, which is case-insensitive. A + // substring match on the raw header parsed `text/plain; x=application/json` as JSON. + it('chooses the body parser by the media type, not by a substring of the header', async () => { + const getUrl = (s: import('http').Server) => `http://127.0.0.1:${(s.address() as any).port}`; + const server = createHttpServer([{ + method: 'POST', pattern: '/echo', transport: 'buffer', + handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ got: req.body }) }), + }]); + await new Promise((r) => server.listen(0, r)); + const post = (contentType: string, body: string) => + fetch(`${getUrl(server)}/echo`, { method: 'POST', headers: { 'content-type': contentType }, body }).then((r) => r.json()); + + expect(await post('Text/Plain; x=application/json', '{"a":1}')).toEqual({ got: '{"a":1}' }); + expect(await post('Application/JSON; charset=utf-8', '{"a":1}')).toEqual({ got: { a: 1 } }); + expect(await post('APPLICATION/X-WWW-FORM-URLENCODED', 'a=1')).toEqual({ got: { a: '1' } }); + expect(await post('text/plain; x=application/x-www-form-urlencoded', 'a=1')).toEqual({ got: 'a=1' }); + server.close(); + }); + it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => { const warn = vi.fn(); const server = createHttpServer( From 79925595b5c3e0721e6a915c10ca57d337260848 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 24 Oct 2026 16:04:45 -0500 Subject: [PATCH 2/2] fix(http): parse every +json media type as JSON (GitHub #36) Exact matching left `application/json-patch+json` arriving as text, where the old substring check had parsed it, and still left the other `+json` types (`application/problem+json`, `application/vnd.api+json`) as text, as they always were. `+json` is the structured-syntax suffix for JSON (RFC 6839), so any media type ending in it is parsed as JSON. `application/jsonx` and parameters that only mention JSON still are not. Signed-off-by: Diego Resendez --- CHANGELOG.md | 6 +++--- src/http/body.ts | 4 +++- test/http.test.ts | 3 +++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e4681d..fa28d7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -270,9 +270,9 @@ npm treats versions as semver and semver forbids leading zeros. the raw `Content-Type` header, case-sensitively, so `Content-Type: Application/JSON` reached the handler as a string while `text/plain; x=application/json` was parsed as JSON. The same applied to urlencoded and multipart bodies. The parser now compares the media type, the part before any - `;`, trimmed and lowercased, exactly. **A type that only contains one of the three no longer - selects its parser:** `application/json-patch+json` used to be parsed as JSON and now arrives as - text, like any other `+json` type always has. Parse it in the handler. + `;`, trimmed and lowercased, exactly. Any `+json` type (RFC 6839) is parsed as JSON too: + `application/problem+json` and `application/vnd.api+json`, which used to arrive as text, now + arrive parsed, and `application/json-patch+json`, which matched the old substring, still does. - **`listen()` rejects when the port is taken** (#138). A bind failure such as `EADDRINUSE` or `EACCES` arrives as the server's `error` event, which `listen()` did not handle: the promise diff --git a/src/http/body.ts b/src/http/body.ts index c1f7f9d..6516223 100644 --- a/src/http/body.ts +++ b/src/http/body.ts @@ -74,7 +74,9 @@ export async function parseRequestBody( ): Promise { const type = mediaType(contentType); - if (buf !== undefined && type === 'application/json') { + // `+json` is the structured-syntax suffix for JSON (RFC 6839): `application/problem+json`, + // `application/vnd.api+json` and `application/json-patch+json` are JSON documents too. + if (buf !== undefined && (type === 'application/json' || type.endsWith('+json'))) { try { return { body: JSON.parse(buf.toString('utf8')) }; } catch { diff --git a/test/http.test.ts b/test/http.test.ts index 0225be5..42a11c1 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -394,6 +394,9 @@ describe('request hardening', () => { expect(await post('Text/Plain; x=application/json', '{"a":1}')).toEqual({ got: '{"a":1}' }); expect(await post('Application/JSON; charset=utf-8', '{"a":1}')).toEqual({ got: { a: 1 } }); + expect(await post('application/vnd.api+json', '{"a":1}')).toEqual({ got: { a: 1 } }); + expect(await post('application/json-patch+json', '[]')).toEqual({ got: [] }); + expect(await post('application/jsonx', '{"a":1}')).toEqual({ got: '{"a":1}' }); expect(await post('APPLICATION/X-WWW-FORM-URLENCODED', 'a=1')).toEqual({ got: { a: '1' } }); expect(await post('text/plain; x=application/x-www-form-urlencoded', 'a=1')).toEqual({ got: 'a=1' }); server.close();