import { createBrotliDecompress, createGunzip, createInflate } from 'zlib'; import { Readable } from 'stream'; import { HttpError } from '../error/http-error'; import { BodyOptions } from './body-protocol'; import { FormUtil } from './form-util'; const UNITS: Record = { b: 1, kb: 1 << 10, mb: 1 << 20, gb: 1 << 30 }; type BodyType = 'json' | 'text' | 'raw' | 'urlencoded'; const TYPES: Record = { 'application/json': 'json', 'text/plain': 'text', 'application/octet-stream': 'raw', 'application/x-www-form-urlencoded': 'urlencoded' }; /** `'100kb'` → 102400. */ export function parseBytes(value: number | string): number { if (typeof value === 'number') { return value; } const match = /^\s*(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?\s*$/i.exec(value); if (!match) { throw new TypeError(`Invalid size: ${value}`); } return Math.floor(Number(match[1]) * UNITS[(match[2] || 'b').toLowerCase()]); } /** * Reads the body of a request into `request.body`: JSON (`application/json`), text (`text/plain`), a Buffer * (`application/octet-stream`) or a form (`application/x-www-form-urlencoded`, nested with brackets). Other * requests get `{}`. Failures are {@link HttpError}s: 400 for a malformed body, 413 for a large one, 415 for * an unsupported charset or encoding. */ export class BodyParser { protected readonly limit: number; protected readonly inflate: boolean; protected readonly strict: boolean; protected readonly parameterLimit: number; protected readonly depth: number; constructor(protected readonly options: BodyOptions = {}) { this.limit = parseBytes(options.limit ?? '100kb'); this.inflate = options.inflate !== false; this.strict = options.strict !== false; this.parameterLimit = options.parameterLimit ?? 1000; this.depth = options.depth ?? 32; } async parse(request: any, response?: any): Promise { if (request._body) { return; } request.body = request.body || {}; const headers = request.headers; if (headers['transfer-encoding'] === undefined && isNaN(headers['content-length'])) { return; } const { type, charset } = this.contentType(headers['content-type']); const bodyType = TYPES[type]; if (!bodyType) { return; } const encoding = bodyType === 'raw' ? 'binary' : this.charset(bodyType, charset); const body = await this.read(request, headers); if (this.options.verify) { try { this.options.verify(request, response, body, encoding); } catch (error) { throw new HttpError(403, (error as Error).message); } } request.body = this.convert(bodyType, body, encoding); request._body = true; } /** * The body of the request as the client sent it (decompressed, at most `limit` bytes), whatever its content type, * without parsing it: for signatures computed over the raw bytes, as webhooks have. The request must not have been read. */ raw(request: any): Promise { return this.read(request, request.headers); } protected contentType(header: string | undefined): { type: string, charset?: string } { if (!header) { return { type: '' }; } const [type, ...params] = header.split(';'); let charset: string | undefined; for (const param of params) { const equals = param.indexOf('='); if (equals > 0 && param.slice(0, equals).trim().toLowerCase() === 'charset') { charset = param.slice(equals + 1).trim().replace(/^"(.*)"$/, '$1').toLowerCase(); } } return { type: type.trim().toLowerCase(), charset }; } protected charset(type: BodyType, charset = 'utf-8'): string { const supported = type === 'json' ? charset.startsWith('utf-') : type === 'urlencoded' ? charset === 'utf-8' : this.isKnownCharset(charset); if (!supported) { throw new HttpError(415, `unsupported charset "${charset.toUpperCase()}"`); } return charset; } protected isKnownCharset(charset: string): boolean { try { new TextDecoder(charset); return true; } catch { return false; } } protected convert(type: BodyType, body: Buffer, charset: string): unknown { if (type === 'raw') { return body; } const text = charset === 'utf-8' || charset === 'utf8' ? body.toString('utf8') : new TextDecoder(charset).decode(body); if (type === 'text') { return text; } if (type === 'urlencoded') { try { return FormUtil.parse(text, { parameterLimit: this.parameterLimit, depth: this.depth }); } catch (error) { throw new HttpError(413, (error as Error).message); } } if (text.length === 0) { return {}; } if (this.strict) { const first = /^[\x20\x09\x0a\x0d]*(.)/.exec(text)?.[1]; if (first !== '{' && first !== '[') { throw new HttpError(400, 'JSON body must be an object or an array'); } } try { return JSON.parse(text); } catch (error) { throw new HttpError(400, (error as Error).message); } } protected decoder(request: Readable, encoding: string): Readable { if (encoding === 'identity') { return request; } if (!this.inflate) { throw new HttpError(415, `content encoding unsupported: ${encoding}`); } const decompress = encoding === 'gzip' ? createGunzip() : encoding === 'deflate' ? createInflate() : encoding === 'br' ? createBrotliDecompress() : undefined; if (!decompress) { throw new HttpError(415, `unsupported content encoding "${encoding}"`); } request.pipe(decompress); return decompress; } /** The body, decompressed, at most `limit` bytes. */ protected read(request: Readable, headers: Record): Promise { const encoding = String(headers['content-encoding'] || 'identity').toLowerCase(); const length = encoding === 'identity' && headers['content-length'] !== undefined ? Number(headers['content-length']) : undefined; if (length !== undefined && length > this.limit) { request.resume(); return Promise.reject(new HttpError(413, 'request entity too large')); } let stream: Readable; try { stream = this.decoder(request, encoding); } catch (error) { request.resume(); return Promise.reject(error); } return new Promise((resolve, reject) => { const chunks: Buffer[] = []; let received = 0; let done = false; const finish = (error?: Error) => { if (done) { return; } done = true; stream.off('data', onData); stream.off('end', onEnd); stream.off('error', onError); request.off('aborted', onAborted); if (error) { if (stream !== request) { request.unpipe(stream as unknown as NodeJS.WritableStream); stream.destroy(); } request.resume(); reject(error); } else { resolve(chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, received)); } }; const onData = (chunk: Buffer | string) => { const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk; received += buffer.length; if (received > this.limit) { finish(new HttpError(413, 'request entity too large')); } else { chunks.push(buffer); } }; const onEnd = () => finish(length !== undefined && received !== length ? new HttpError(400, 'request size did not match content length') : undefined); const onError = (error: Error) => finish(new HttpError(400, error.message)); const onAborted = () => finish(new HttpError(400, 'request aborted')); stream.on('data', onData); stream.once('end', onEnd); stream.once('error', onError); request.once('aborted', onAborted); }); } }