From ec2e3a0e620a7fc2b1532ef7fd004b31fbc58f84 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 6 Jul 2026 20:13:52 -0500 Subject: [PATCH] feat(http): configurable bodyDuplicates policy for urlencoded + multipart fields Signed-off-by: Diego Resendez --- src/app.ts | 4 ++-- src/http.ts | 9 +++++---- src/multipart.ts | 10 ++++++++++ test/multipart-http.test.ts | 23 +++++++++++++++++++++++ 4 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/app.ts b/src/app.ts index ecc64fb..4a3f30d 100644 --- a/src/app.ts +++ b/src/app.ts @@ -53,7 +53,7 @@ export interface MeshConfig { timeoutMs?: number; } -export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }): App { +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }): App { const bus = new Bus(); const container = new Container(); let server: http.Server | undefined; @@ -362,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me }, })); - server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors }); + server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors, bodyDuplicates: opts.bodyDuplicates }); server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); await new Promise((resolve) => server!.listen(port, resolve)); return server; diff --git a/src/http.ts b/src/http.ts index 106b777..1c0c97c 100644 --- a/src/http.ts +++ b/src/http.ts @@ -10,7 +10,7 @@ import type { Transport } from './metadata'; import type { Bus } from './bus'; import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security'; import type { TlsOptions, SecurityOptions, CorsOptions } from './security'; -import { parseMultipart, extractBoundary } from './multipart'; +import { parseMultipart, extractBoundary, collapseDuplicates } from './multipart'; export interface RequestLimits { maxBodyBytes?: number; // default 1_000_000 @@ -19,7 +19,7 @@ export interface RequestLimits { keepAliveTimeoutMs?: number; // default 5_000 maxParts?: number; // default 1000 } -export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions } +export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' } export type RouteHandler = (req: { method: string; url: string; @@ -258,6 +258,7 @@ export function createHttpServer( } let body: unknown; const ct = String(req.headers['content-type'] ?? ''); + const duplicates = opts?.bodyDuplicates ?? 'last'; if (buf !== undefined && ct.includes('application/json')) { try { body = JSON.parse(buf.toString('utf8')); } catch { @@ -266,7 +267,7 @@ export function createHttpServer( return; } } else if (buf !== undefined && ct.includes('application/x-www-form-urlencoded')) { - body = Object.fromEntries(new URLSearchParams(buf.toString('utf8'))); // duplicates policy added in Task 3 + body = collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates); } else if (buf !== undefined && ct.includes('multipart/form-data')) { const boundary = extractBoundary(ct); if (!boundary) { @@ -274,7 +275,7 @@ export function createHttpServer( res.end(JSON.stringify({ error: 'Invalid multipart body' })); return; } - try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates: 'last' }); } + try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates }); } catch { res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'Invalid multipart body' })); diff --git a/src/multipart.ts b/src/multipart.ts index e4315b5..02fad20 100644 --- a/src/multipart.ts +++ b/src/multipart.ts @@ -35,6 +35,16 @@ function addField(fields: MultipartBody['fields'], name: string, value: string, } } +// Reusable accumulator for any iterable of [key, value] pairs (e.g. URLSearchParams) +// so urlencoded bodies collapse duplicates with the exact same policy as multipart fields. +export function collapseDuplicates( + pairs: Iterable<[string, string]>, dup: 'array' | 'last', +): Record { + const out: Record = {}; + for (const [k, v] of pairs) addField(out, k, v, dup); + return out; +} + function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void { const ex = files[name]; if (ex === undefined) files[name] = file; diff --git a/test/multipart-http.test.ts b/test/multipart-http.test.ts index ad27a11..cd5d550 100644 --- a/test/multipart-http.test.ts +++ b/test/multipart-http.test.ts @@ -50,3 +50,26 @@ describe('multipart over http', () => { expect(r.status).toBe(400); }); }); + +describe('bodyDuplicates', () => { + it('app "array" makes repeated urlencoded fields arrays', async () => { + @Route('/') class C { @Post('/f') f(@body() b: any) { return b; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod], bodyDuplicates: 'array' }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/f`, { + method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2&y=9' }); + expect(await r.json()).toEqual({ x: ['1', '2'], y: ['9'] }); + }); + it('default (no option) keeps urlencoded last-wins', async () => { + @Route('/') class C { @Post('/f') f(@body() b: any) { return b; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/f`, { + method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2' }); + expect(await r.json()).toEqual({ x: '2' }); + }); +});