Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475export const MAX_REQUEST_BODY_BYTES = 1_048_576;
function statusError(message: string, statusCode: number): Error & { statusCode: number } { return Object.assign(new Error(message), { statusCode });}
export function parseContentLengthHeader(contentLength: string | undefined): number | null { if (!contentLength) return null; const parsed = Number.parseInt(contentLength, 10); if (!Number.isFinite(parsed) || parsed < 0) { throw statusError('Invalid Content-Length header', 400); } return parsed;}
// Streams the request body into memory while enforcing a hard byte ceiling. Rejects both// oversized Content-Length declarations up front and streams that exceed the cap mid-read.export async function bufferRequestBodyWithLimit(request: Request, maxBytes = MAX_REQUEST_BODY_BYTES): Promise<Uint8Array | null> { const contentLength = parseContentLengthHeader(request.headers.get('content-length') || undefined); if (contentLength !== null && contentLength > maxBytes) { throw statusError('Request body too large', 413); }
if (!request.body) { return null; }
const reader = request.body.getReader(); const chunks: Uint8Array[] = []; let total = 0;
try { while (true) { const { done, value } = await reader.read(); if (done) break; total += value.byteLength; if (total > maxBytes) { throw statusError('Request body too large', 413); } chunks.push(value); } } finally { reader.releaseLock(); }
const combined = new Uint8Array(total); let offset = 0; for (const chunk of chunks) { combined.set(chunk, offset); offset += chunk.byteLength; }
return combined;}
export function cloneRequestWithBufferedBody(request: Request, body: Uint8Array | null): Request { const headers = new Headers(request.headers);
if (!body || body.byteLength === 0) { headers.delete('content-length'); return new Request(request.url, { method: request.method, headers, }); }
headers.set('content-length', String(body.byteLength)); return new Request(request.url, { method: request.method, headers, body, duplex: 'half' as RequestInit['duplex'], });}