parse-multipart.mjs
41 lines 1.8 KB
Raw
sha256:8915fe406161f95c1681f9469375e7bae5b28c884f00bedbdef65e4b0cd0738d docs(flow): commit FLOW-V0-SPEC.md hygiene for 7A-INT merge Human 10 hours ago
1 /**
2 * Minimal multipart/form-data file parser for the Knowtation gateway.
3 * Used to extract the first file field from a buffered multipart body without
4 * forwarding the binary to another Lambda function (which causes serialization issues).
5 */
6
7 /**
8 * Parse the first file field from a raw multipart/form-data buffer.
9 * @param {Buffer} body - full raw multipart body
10 * @param {string} boundary - boundary string from Content-Type header (without leading --)
11 * @returns {{ filename: string, contentType: string, data: Buffer } | null}
12 */
13 export function parseMultipartFile(body, boundary) {
14 const enc = 'binary';
15 const bodyStr = body.toString(enc);
16 const boundaryLine = '--' + boundary;
17 const parts = bodyStr.split(boundaryLine);
18 for (const part of parts) {
19 if (!part || part.startsWith('--')) continue;
20 const crlfDoubleCrlf = '\r\n\r\n';
21 const headerEnd = part.indexOf(crlfDoubleCrlf);
22 if (headerEnd === -1) continue;
23 const headerSection = part.slice(0, headerEnd);
24 if (!headerSection.toLowerCase().includes('content-disposition')) continue;
25 // Only process parts that have a filename (file fields, not text fields).
26 const filenameMatch = headerSection.match(/filename="([^"]+)"/i);
27 if (!filenameMatch) continue;
28 const ctMatch = headerSection.match(/content-type:\s*([^\r\n]+)/i);
29 const contentType = ctMatch ? ctMatch[1].trim() : 'application/octet-stream';
30 // File data starts after the double CRLF; strip trailing \r\n added by multipart framing.
31 const dataStart = headerEnd + crlfDoubleCrlf.length;
32 let dataStr = part.slice(dataStart);
33 if (dataStr.endsWith('\r\n')) dataStr = dataStr.slice(0, -2);
34 return {
35 filename: filenameMatch[1],
36 contentType,
37 data: Buffer.from(dataStr, enc),
38 };
39 }
40 return null;
41 }
File History 1 commit
sha256:8915fe406161f95c1681f9469375e7bae5b28c884f00bedbdef65e4b0cd0738d docs(flow): commit FLOW-V0-SPEC.md hygiene for 7A-INT merge Human 10 hours ago