import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { readFile } from "node:fs/promises"; import type { MediaKind } from "src/client/client.service"; const run = promisify(execFile); /** Inspect bytes/streams, never the user-controlled filename or Content-Type. */ export async function validateMedia( path: string, kind: MediaKind, ): Promise { if (kind === "image" || kind === "chassisNumber" || kind === "carPlate") { const bytes = await readFile(path); // Documents also accept PDFs. Require both the header and end marker. if (bytes.subarray(0, 5).toString() === "%PDF-") { if (!bytes.subarray(-2048).includes(Buffer.from("%%EOF"))) throw new Error("Invalid PDF"); return; } } const { stdout } = await run( "ffprobe", [ "-v", "error", "-protocol_whitelist", "file,pipe", "-show_streams", "-show_format", "-of", "json", path, ], { timeout: 15000, maxBuffer: 1024 * 1024 }, ); const metadata = JSON.parse(stdout); const imageFormat = String(metadata.format?.format_name || "") .split(",") .some((f: string) => /^(?:image2|image2pipe|.*_pipe|gif|apng|ico|heif)$/.test(f), ); if ( (kind === "video" && imageFormat) || ((kind === "image" || kind === "chassisNumber" || kind === "carPlate") && !imageFormat) ) throw new Error("Wrong media container"); const streams = metadata.streams as Array<{ codec_type?: string; width?: number; height?: number; }>; const type = kind === "voice" ? "audio" : "video"; if (!streams?.some((s) => s.codec_type === type)) throw new Error("Missing media stream"); if (type === "video" && !streams.some((s) => s.width > 0 && s.height > 0)) throw new Error("Invalid dimensions"); await run( "ffmpeg", [ "-v", "error", "-protocol_whitelist", "file,pipe", "-nostdin", "-i", path, "-map", `0:${type === "audio" ? "a" : "v"}:0`, ...(type === "audio" ? ["-t", "0.1"] : ["-frames:v", "1"]), "-f", "null", "-", ], { timeout: 15000, maxBuffer: 1024 * 1024 }, ); }