import { createHash } from 'crypto'; import { FastifyInstance, FastifyRequest } from 'fastify'; import { createWriteStream } from 'fs'; import { Readable } from 'stream'; import { ApiError } from '../common/filters/api-error'; const UPLOAD_ROUTE = '/api/v1/chats/:chatId/attachments'; const PASS_THROUGH_TYPE = 'application/x-messenger-upload'; declare module 'fastify' { interface FastifyRequest { uploadContentType?: string; } } export function registerUploadBody(instance: FastifyInstance): void { instance.addContentTypeParser(PASS_THROUGH_TYPE, (_request, payload, done) => { done(null, payload); }); instance.addHook('onRequest', (request: FastifyRequest, _reply, done) => { if (request.method === 'POST' && request.routeOptions.url === UPLOAD_ROUTE) { request.uploadContentType = request.headers['content-type']; request.headers['content-type'] = PASS_THROUGH_TYPE; } done(); }); } export interface ReceivedBody { size: number; sha256: string; } export function receiveBody( body: Readable, path: string, maxBytes: number, timeoutMs: number, ): Promise { return new Promise((resolve, reject) => { const hash = createHash('sha256'); const out = createWriteStream(path, { flags: 'wx', mode: 0o600 }); let size = 0; let settled = false; const timer = setTimeout(() => body.destroy(), timeoutMs); const settle = (done: () => void): void => { if (settled) { return; } settled = true; clearTimeout(timer); body.off('data', onData); body.off('end', onEnd); body.off('close', onClose); done(); }; const fail = (error: ApiError): void => { settle(() => { out.destroy(); reject(error); }); }; const onData = (chunk: Buffer): void => { size += chunk.length; if (size > maxBytes) { fail(new ApiError('payload_too_large', 'attachment exceeds size limit')); return; } hash.update(chunk); if (!out.write(chunk)) { body.pause(); out.once('drain', () => { if (!settled) { body.resume(); } }); } }; const onEnd = (): void => { settle(() => { out.end(() => resolve({ size, sha256: hash.digest('hex') }), ); }); }; const onClose = (): void => { fail(new ApiError('invalid_request', 'upload was interrupted')); }; out.on('error', () => { fail(new ApiError('unavailable', 'temporary storage unavailable')); }); body.on('data', onData); body.on('end', onEnd); body.on('close', onClose); }); }