feat(multipart): pure binary-safe multipart/form-data parser

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-06 20:07:32 -05:00
1 parent d2d4fc1d21
commit 0f7932c696
2 files changed
+194

No files matched your search

+112
View File
@@ -0,0 +1,112 @@
// src/multipart.ts — pure, binary-safe multipart/form-data parser. No server deps.
export interface UploadedFile { filename: string; contentType: string; data: Buffer; size: number }
export interface MultipartBody {
fields: Record<string, string | string[]>;
files: Record<string, UploadedFile | UploadedFile[]>;
}
export interface MultipartOpts { maxParts: number; duplicates: 'array' | 'last' }
const CRLF = Buffer.from('\r\n');
// boundary token from a Content-Type value; supports quoted form.
export function extractBoundary(contentType: string): string | undefined {
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
const b = (m?.[1] ?? m?.[2])?.trim();
return b || undefined;
}
// order-independent, quoted-or-unquoted param lookup within a header value.
// The `(?:^|[;\s])` prefix anchors the key to a param boundary so `name=` does NOT
// match the tail of `filename=`, and `filename=` does not match `filename*=`.
function param(header: string, key: string): string | undefined {
const q = new RegExp(`(?:^|[;\\s])${key}="([^"]*)"`, 'i').exec(header);
if (q) return q[1];
const u = new RegExp(`(?:^|[;\\s])${key}=([^";]+)`, 'i').exec(header);
return u ? u[1].trim() : undefined;
}
function addField(fields: MultipartBody['fields'], name: string, value: string, dup: 'array' | 'last'): void {
if (dup === 'array') {
const ex = fields[name];
if (Array.isArray(ex)) ex.push(value);
else fields[name] = [value];
} else {
fields[name] = value; // last-wins
}
}
function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void {
const ex = files[name];
if (ex === undefined) files[name] = file;
else if (Array.isArray(ex)) ex.push(file);
else files[name] = [ex, file];
}
// Find the next REAL delimiter at/after `from`: a `\r\n--boundary` occurrence that is
// followed by `\r\n` (a part) or `--` (the terminator). This skips false hits where the
// exact `\r\n--boundary` byte sequence appears INSIDE a file body — the data-integrity case.
function findDelim(buf: Buffer, delim: Buffer, from: number): number {
let i = buf.indexOf(delim, from);
while (i !== -1) {
const a = i + delim.length;
if ((buf[a] === 0x0d && buf[a + 1] === 0x0a) || (buf[a] === 0x2d && buf[a + 1] === 0x2d)) return i;
i = buf.indexOf(delim, i + delim.length); // false hit inside a body — keep searching
}
return -1;
}
export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): MultipartBody {
const fields: MultipartBody['fields'] = {};
const files: MultipartBody['files'] = {};
const delim = Buffer.concat([CRLF, Buffer.from(`--${boundary}`)]); // \r\n--boundary
// Normalize: prepend CRLF so the FIRST boundary (which a browser sends with no
// leading CRLF) is also preceded by the delimiter and isn't dropped as preamble.
const buf = Buffer.concat([CRLF, raw]);
let pos = findDelim(buf, delim, 0);
if (pos === -1) throw new Error('Invalid multipart body');
let count = 0;
while (true) {
let start = pos + delim.length;
// terminator "--" immediately after the boundary → done
if (buf[start] === 0x2d && buf[start + 1] === 0x2d) break;
// skip the CRLF that ends the boundary line
if (buf[start] === 0x0d && buf[start + 1] === 0x0a) start += 2;
const next = findDelim(buf, delim, start);
if (next === -1) throw new Error('Invalid multipart body');
if (++count > opts.maxParts) throw new Error('Invalid multipart body');
const part = buf.subarray(start, next);
const sep = part.indexOf('\r\n\r\n');
if (sep === -1) throw new Error('Invalid multipart body');
const headerText = part.subarray(0, sep).toString('utf8');
const partBody = part.subarray(sep + 4);
let disposition = '';
let contentType = '';
for (const line of headerText.split('\r\n')) {
const c = line.indexOf(':');
if (c === -1) continue;
const k = line.slice(0, c).trim().toLowerCase();
const v = line.slice(c + 1).trim();
if (k === 'content-disposition') disposition = v;
else if (k === 'content-type') contentType = v;
}
const name = param(disposition, 'name');
if (name === undefined) throw new Error('Invalid multipart body');
const filename = param(disposition, 'filename');
if (filename !== undefined) {
if (filename === '' && partBody.length === 0) { pos = next; continue; } // unselected file input
addFile(files, name, {
filename,
contentType: contentType || 'application/octet-stream',
data: Buffer.from(partBody), // copy out of the shared buffer
size: partBody.length,
});
} else {
addField(fields, name, partBody.toString('utf8'), opts.duplicates);
}
pos = next;
}
return { fields, files };
}
+82
View File
@@ -0,0 +1,82 @@
import { describe, it, expect } from 'vitest';
import { parseMultipart, extractBoundary } from '../src/multipart';
const B = 'X-BOUND';
function body(parts: string[]): Buffer {
return Buffer.concat([
...parts.map((p) => Buffer.from(`--${B}\r\n${p}\r\n`)),
Buffer.from(`--${B}--\r\n`),
]);
}
const field = (name: string, val: string) => `Content-Disposition: form-data; name="${name}"\r\n\r\n${val}`;
const file = (name: string, fn: string, ct: string, data: string) =>
`Content-Disposition: form-data; name="${name}"; filename="${fn}"\r\nContent-Type: ${ct}\r\n\r\n${data}`;
const opts = { maxParts: 1000, duplicates: 'last' as const };
describe('extractBoundary', () => {
it('plain and quoted', () => {
expect(extractBoundary('multipart/form-data; boundary=abc')).toBe('abc');
expect(extractBoundary('multipart/form-data; boundary="a b"')).toBe('a b');
expect(extractBoundary('multipart/form-data')).toBeUndefined();
});
});
describe('parseMultipart', () => {
it('single text field is NOT lost (first-part off-by-one guard)', () => {
const r = parseMultipart(body([field('title', 'hello')]), B, opts);
expect(r.fields.title).toBe('hello');
});
it('multiple distinct fields', () => {
const r = parseMultipart(body([field('a', '1'), field('b', '2')]), B, opts);
expect(r.fields).toEqual({ a: '1', b: '2' });
});
it("duplicates 'last' vs 'array'", () => {
const b = body([field('t', 'x'), field('t', 'y')]);
expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'last' }).fields.t).toBe('y');
expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'array' }).fields.t).toEqual(['x', 'y']);
});
it('single file: metadata + exact bytes incl. embedded CRLF and boundary-like text', () => {
const payload = 'ab\r\n--X-BOUNDnope\r\ncd';
const r = parseMultipart(body([file('doc', 'a.txt', 'text/plain', payload)]), B, opts);
const f = r.files.doc as any;
expect(f.filename).toBe('a.txt');
expect(f.contentType).toBe('text/plain');
expect(f.size).toBe(Buffer.byteLength(payload));
expect(f.data.toString()).toBe(payload);
});
it('multiple files same name → array', () => {
const r = parseMultipart(body([file('f', '1', 'text/plain', 'a'), file('f', '2', 'text/plain', 'b')]), B, opts);
expect(Array.isArray(r.files.f)).toBe(true);
expect((r.files.f as any).length).toBe(2);
});
it('mixed fields + files', () => {
const r = parseMultipart(body([field('name', 'joe'), file('avatar', 'p.png', 'image/png', 'PNG')]), B, opts);
expect(r.fields.name).toBe('joe');
expect((r.files.avatar as any).filename).toBe('p.png');
});
it('case-insensitive headers + filename-before-name (order independent)', () => {
const part = `content-disposition: form-data; filename="z.bin"; name="up"\r\ncontent-type: application/octet-stream\r\n\r\nDATA`;
const r = parseMultipart(body([part]), B, opts);
expect((r.files.up as any).filename).toBe('z.bin');
});
it('filename="" with empty body is skipped', () => {
const part = `Content-Disposition: form-data; name="up"; filename=""\r\n\r\n`;
const r = parseMultipart(body([part]), B, opts);
expect(r.files.up).toBeUndefined();
});
it('malformed → throws: no boundary present', () => {
expect(() => parseMultipart(Buffer.from('garbage'), B, opts)).toThrow();
});
it('malformed → throws: part without name', () => {
const part = `Content-Disposition: form-data\r\n\r\nx`;
expect(() => parseMultipart(body([part]), B, opts)).toThrow();
});
it('malformed → throws: part with no header/body separator', () => {
const raw = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="a"\r\n--${B}--\r\n`);
expect(() => parseMultipart(raw, B, opts)).toThrow();
});
it('parts over maxParts → throws', () => {
const b = body([field('a', '1'), field('b', '2'), field('c', '3')]);
expect(() => parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).toThrow();
});
});