From 23ab4f41220bad135c19f765052bf0f6a81e6130 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 24 Oct 2026 15:55:21 -0500 Subject: [PATCH] fix(multipart): bound a text field by the body limit, not busboy's 1 MiB (GitHub #39) parseMultipart created busboy with `limits: { parts }` only, so busboy's `fieldSize` default of 1 MiB applied whatever maxBodyBytes allowed. busboy cuts a field at that size and only sets `valueTruncated`, which nothing read: with the body limit raised, a 1,100,000-character field reached the handler as 1,048,576 characters. acquireBody now passes the route's resolved body limit down as `maxFieldBytes`, and parseMultipart gives it to busboy as `fieldSize`. busboy flags a field once it reaches `fieldSize`, so it gets one byte of headroom; otherwise a field of exactly the limit would count as cut. A field that busboy still reports as truncated rejects with HttpError 413, which parseRequestBody already renders with that status, matching how an over-limit body fails. Node and app.fetch (Deno, Bun, edge) share this path. test/multipart-http.test.ts sends a 1,100,000-character field to a route with maxBodyBytes 2,000,000 over both app.fetch and the Node server. test/multipart.test.ts checks the 413 and the exact-limit boundary on parseMultipart directly. Signed-off-by: Diego Resendez --- CHANGELOG.md | 8 ++++++++ src/http/body.ts | 15 ++++++++++----- src/multipart.ts | 16 ++++++++++++++-- test/multipart-http.test.ts | 16 ++++++++++++++++ test/multipart.test.ts | 8 ++++++++ 5 files changed, 56 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b15cdb2..e26150d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -260,6 +260,14 @@ npm treats versions as semver and semver forbids leading zeros. ### Fixed +- **A multipart text field over 1 MiB is no longer cut short** (GitHub #39). busboy applies its + own 1 MiB `fieldSize` default unless told otherwise, so with `maxBodyBytes` raised above that a + 1,100,000-character field reached the handler as its first 1,048,576, and nothing said it had + been cut. A field is now bounded by the route's body limit, the same one the whole body is held + to. If busboy still reports a field as truncated, the request fails with `413` rather than + handing the handler partial data. The Node server and `app.fetch` parse multipart through the + same path, so the fix applies to both. + - **`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..d23586c 100644 --- a/src/http/body.ts +++ b/src/http/body.ts @@ -61,6 +61,7 @@ export async function parseRequestBody( contentType: string, duplicates: 'array' | 'last', maxParts: number, + maxFieldBytes?: number, ): Promise { if (buf !== undefined && contentType.includes('application/json')) { try { @@ -79,9 +80,10 @@ export async function parseRequestBody( if (!boundary) return { error: 'Invalid multipart body' }; try { - return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) }; + return { body: await parseMultipart(buf, boundary, { maxParts, duplicates, maxFieldBytes }) }; } catch (error) { - // HttpError = the busboy peer dep is missing (501); anything else = malformed input (400). + // HttpError = the busboy peer dep is missing (501) or a field is over the limit (413); + // anything else = malformed input (400). if (isHttpError(error)) return { error: error.message, status: error.status }; return { error: 'Invalid multipart body' }; } @@ -114,12 +116,13 @@ export function acquireBody( // this whole path without a single promise, and an `async` wrapper here would allocate one // regardless. Same reason `handle()` is not async. return isPromise(acquired) - ? acquired.then((settled) => parseAcquired(settled, matched, opts, req)) - : parseAcquired(acquired, matched, opts, req); + ? acquired.then((settled) => parseAcquired(settled, limit, matched, opts, req)) + : parseAcquired(acquired, limit, matched, opts, req); } function parseAcquired( acquired: { bytes: Buffer | undefined } | BodyFailure, + limit: number, matched: MatchedRoute, opts: HttpOptions | undefined, req: ErrorRequest, @@ -135,7 +138,9 @@ function parseAcquired( const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000; - return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) => + // A field is bounded by the body limit alone. busboy's own 1 MiB default would otherwise cut any + // larger field that `maxBodyBytes` was raised to admit. + return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts, limit).then((parsed) => 'error' in parsed ? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) } : { body: parsed.body }, diff --git a/src/multipart.ts b/src/multipart.ts index d525388..8873784 100644 --- a/src/multipart.ts +++ b/src/multipart.ts @@ -21,6 +21,8 @@ export interface MultipartBody { export interface MultipartOpts { maxParts: number; duplicates: 'array' | 'last'; + /** Largest text field accepted, in bytes. Unset leaves busboy's own default of 1 MiB. */ + maxFieldBytes?: number; } /** @@ -79,6 +81,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm * @param raw The full (already size-capped) request body. * @param boundary The boundary token (see {@link extractBoundary}). * @throws HttpError 501 when the optional `busboy` peer dependency is not installed. + * @throws HttpError 413 when a text field is larger than `maxFieldBytes`. * @throws Error 'Invalid multipart body' on malformed input or when `maxParts` is exceeded. */ export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): Promise { @@ -93,16 +96,25 @@ export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpt const fail = () => reject(new Error('Invalid multipart body')); let bb: NodeJS.WritableStream & NodeJS.EventEmitter; + // busboy flags a field as truncated once it *reaches* `fieldSize`, so a field of exactly + // `maxFieldBytes` needs one byte of headroom to count as whole. + const fieldSize = opts.maxFieldBytes === undefined ? undefined : opts.maxFieldBytes + 1; + try { bb = busboy({ headers: { 'content-type': `multipart/form-data; boundary=${boundary}` }, - limits: { parts: opts.maxParts }, + limits: { parts: opts.maxParts, fieldSize }, }); } catch { return fail(); } - bb.on('field', (name: string, value: string) => addField(body.fields, name, value, opts.duplicates)); + bb.on('field', (name: string, value: string, info: { valueTruncated: boolean }) => { + // busboy cuts a field at `fieldSize` and only flags it. Partial data is not the field the + // client sent, so refuse the body as too large, like any other over-limit body. + if (info.valueTruncated) return reject(new HttpError(413, 'Payload Too Large')); + addField(body.fields, name, value, opts.duplicates); + }); bb.on('file', (name: string, stream: Readable, info: { filename?: string; mimeType?: string }) => { const chunks: Buffer[] = []; diff --git a/test/multipart-http.test.ts b/test/multipart-http.test.ts index 865bcd0..9a32b5d 100644 --- a/test/multipart-http.test.ts +++ b/test/multipart-http.test.ts @@ -153,6 +153,22 @@ describe('multipart limits on app.fetch (#105)', () => { expect(await r.text()).toContain('Invalid multipart body'); }); + // GitHub #39: busboy's own 1 MiB field limit used to apply whatever maxBodyBytes allowed, and cut + // the field without an error. A field is now bounded only by the body limit, on both adapters. + it('a text field over 1 MiB reaches the handler whole when maxBodyBytes allows it', async () => { + @Route('/') class C { @Post('/u', { maxBodyBytes: 2_000_000 }) u(@body() b: any) { return { length: b.fields.big.length }; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod] }); + const big = () => { const fd = new FormData(); fd.set('big', 'x'.repeat(1_100_000)); return fd; }; + + const viaFetch = await app.fetch(new Request('http://x/u', { method: 'POST', body: big() })); + expect(await viaFetch.json()).toEqual({ length: 1_100_000 }); + + const server = await app.listen(0); + const viaNode = await fetch(`http://127.0.0.1:${(server.address() as any).port}/u`, { method: 'POST', body: big() }); + expect(await viaNode.json()).toEqual({ length: 1_100_000 }); + }); + it('T7: the server-level maxParts applies when the route sets none', async () => { @Route('/') class C { @Post('/u') u(@body() b: any) { return b; } } @Module({ mountpoint: '/', controllers: [C] }) class CMod {} diff --git a/test/multipart.test.ts b/test/multipart.test.ts index fa92033..2efc0ae 100644 --- a/test/multipart.test.ts +++ b/test/multipart.test.ts @@ -79,6 +79,14 @@ describe('parseMultipart', () => { await expect(parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).rejects.toThrow(); }); + // GitHub #39: busboy cuts a field at its size limit and only flags it, so the parser has to refuse + // the body rather than hand the handler partial data. + it('a field over maxFieldBytes → rejects with 413 instead of truncating', async () => { + const b = body([field('a', 'x'.repeat(10))]); + await expect(parseMultipart(b, B, { ...opts, maxFieldBytes: 4 })).rejects.toMatchObject({ status: 413 }); + expect((await parseMultipart(b, B, { ...opts, maxFieldBytes: 10 })).fields.a).toBe('x'.repeat(10)); + }); + it('malformed input with no matching boundary → rejects', async () => { await expect(parseMultipart(Buffer.from('garbage'), B, opts)).rejects.toThrow(); });