Files
yara724-api/src/media-policy/validate-media.ts
T
SepehrYahyaee 6b968c0952 fix(workflows): resolve QA blockers and protect case evidence
Fix registrar signing, reviewer re-entry, replacement evidence freshness, owner decision and rating races, multipart objections, vehicle serialization and product reporting.

Validate uploaded media with FFmpeg, serve evidence through expiring signed links, and add targeted regressions plus a dry-run repair for prematurely completed visit cases.
2026-11-22 12:50:22 +03:30

77 lines
2.2 KiB
TypeScript

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<void> {
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 },
);
}