feat(http): configurable bodyDuplicates policy for urlencoded + multipart fields

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-06 20:13:52 -05:00
1 parent 5808da8012
commit ec2e3a0e62
4 files changed
+40 -6

No files matched your search

+2 -2
View File
@@ -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<string, unknown>; 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<string, unknown>; 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<void>((resolve) => server!.listen(port, resolve));
return server;
+5 -4
View File
@@ -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' }));
+10
View File
@@ -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<string, string | string[]> {
const out: Record<string, string | string[]> = {};
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;
+23
View File
@@ -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' });
});
});