import { Request, Response, NextFunction } from 'express'; import fs from 'fs'; import { assertSafePdf } from '../utils/sanitize.js'; import { ApiError } from '../utils/apiError.js'; /** * Strikte Variante: Datei MUSS eine PDF sein. Sonst 415. Für Routen, die * ausschliesslich PDFs zulassen (z.B. Vollmacht-Upload, PDF-Templates). * * Routen, die auch JPG/PNG akzeptieren (z.B. contract.routes * Vertragsdokumente), nutzen `validateUploadedFile` aus * `uploadFileTypeValidator.ts` – das macht Magic-Byte für ALLE Typen + * PDF-Scan in einer Pipeline. */ export function requireSafeUploadedPdf(req: Request, res: Response, next: NextFunction): void { const file = (req as Request & { file?: Express.Multer.File }).file; if (!file) { next(); return; } try { const buf = fs.readFileSync(file.path); if (buf.length < 5 || buf.subarray(0, 5).toString('latin1') !== '%PDF-') { throw new ApiError(415, 'Datei ist keine gültige PDF.'); } assertSafePdf(buf); next(); } catch (e) { try { fs.unlinkSync(file.path); } catch { /* ignore */ } const status = e instanceof ApiError ? e.statusCode : 415; const message = e instanceof Error ? e.message : 'PDF ungültig'; res.status(status).json({ success: false, error: message }); } }