fix(cli): media-use resolve reads each asset as one local self-contained container (#8713)

probe() and the vendored grade analyzer ran ffprobe and ffmpeg on project files with every reader
and the default protocols, so a media-named list, manifest or script under assets/ could open
other files, and a script reader could run its script. Every read that resolve starts (--adopt,
--from --source, --for, --analyze) now passes -protocol_whitelist file and a self-contained
container list before the file. The vendored analyzer's limits are now at least as strict as the
core module's, and the parity test fails when a vendored read allows a reader the core one would
not, or drops the file-only protocol. mp3, wav, mp4 and png assets keep their metadata.
This commit is contained in:
Michael Wang
2026-11-24 12:54:08 +00:00
committed by GitHub
parent 7a7471e7cf
commit 7975ecc423
6 changed files with 170 additions and 7 deletions
@@ -1,5 +1,6 @@
import { execFileSync } from "node:child_process";
import { resolve } from "node:path";
import { assertLiteralMediaPath } from "./literal-media-input.mjs";
// The binaries media-use spawns: HYPERFRAMES_FFMPEG_PATH / HYPERFRAMES_FFPROBE_PATH when set, else PATH.
// A set path that is not a working ffmpeg/ffprobe throws, so a broken override never reads as "no metadata".
@@ -35,3 +36,14 @@ function isWorking(path, name) {
export const ffmpegBinary = () => configuredOr("ffmpeg", "HYPERFRAMES_FFMPEG_PATH");
export const ffprobeBinary = () => configuredOr("ffprobe", "HYPERFRAMES_FFPROBE_PATH");
// Containers that hold their own media and name no other file. A project's file is opened only with these, so no
// list, manifest, script, device or text-art reader runs on it, and nothing it names is opened.
export const SELF_CONTAINED_FORMATS =
"mov,matroska,mxf,avi,mpeg,mpegts,mpegvideo,flv,asf,ogg,wav,mp3,aac,flac,aiff,gif,ico,image2,png_pipe,jpeg_pipe,webp_pipe,bmp_pipe,tiff_pipe";
/** ffmpeg or ffprobe options, placed before the file, that read it as one local self-contained container. */
export function selfContainedInput(file) {
assertLiteralMediaPath(file);
return ["-protocol_whitelist", "file", "-format_whitelist", SELF_CONTAINED_FORMATS];
}
@@ -2,6 +2,7 @@
// packages/core/src/mediaGradeAnalyzer.vendoredParity.test.ts guards behavior drift.
import { execFileSync } from "node:child_process";
import { basename, extname } from "node:path";
import { selfContainedInput } from "./ff-binaries.mjs";
import { assertLiteralMediaPath } from "./literal-media-input.mjs";
const IMAGE_EXT = new Set([".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".tif", ".tiff"]);
@@ -39,6 +40,7 @@ function probeMedia(mediaPath, ffprobePath) {
[
"-v",
"error",
...selfContainedInput(mediaPath),
"-select_streams",
"v:0",
"-show_entries",
@@ -230,6 +232,7 @@ function readSignalStats(ffmpegPath, mediaPath, seekSeconds, frames) {
"-v",
"error",
...keyframeSeek,
...selfContainedInput(mediaPath),
"-i",
mediaPath,
"-vf",
@@ -1,6 +1,6 @@
import { strict as assert } from "node:assert";
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, unlinkSync } from "node:fs";
import { existsSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { test } from "node:test";
@@ -294,3 +294,15 @@ test("grade analysis refuses a file whose name reads as an ffmpeg pattern", () =
/pattern of other files/,
);
});
test("grade analysis reads no file a media-named list points at", { skip: FFMPEG_SKIP }, () => {
const dir = mkdtempSync(join(tmpdir(), "mu-grade-list-"));
try {
makeFrame(dir, "frame.png", "0x808080");
const list = join(dir, "clip.mp4");
writeFileSync(list, "ffconcat version 1.0\nfile 'frame.png'\n");
assert.throws(() => analyzeMediaGrade(list), /grade analysis failed/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+5 -4
View File
@@ -1,7 +1,6 @@
import { execFileSync } from "node:child_process";
import { extname } from "node:path";
import { ffprobeBinary } from "./ff-binaries.mjs";
import { assertLiteralMediaPath } from "./literal-media-input.mjs";
import { ffprobeBinary, selfContainedInput } from "./ff-binaries.mjs";
const IMAGE_EXT = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".ico"]);
const AUDIO_EXT = new Set([".mp3", ".wav", ".ogg", ".m4a", ".aac"]);
@@ -12,12 +11,14 @@ export function probe(filePath) {
const ffprobe = ffprobeBinary();
try {
assertLiteralMediaPath(filePath);
// execFileSync (no shell) so a hostile filename like `"; rm -rf ~; ".png`
// can't break out of the quoting — filePath is passed as a literal argv entry.
const raw = execFileSync(
ffprobe,
["-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", "--", filePath],
[
...["-v", "quiet", ...selfContainedInput(filePath), "-print_format", "json"],
...["-show_format", "-show_streams", "--", filePath],
],
{ encoding: "utf8", timeout: 5000 },
);
const info = JSON.parse(raw);
+58 -1
View File
@@ -4,7 +4,8 @@ import { chmodSync, mkdtempSync, writeFileSync, existsSync, rmSync } from "node:
import { join } from "node:path";
import { tmpdir } from "node:os";
import { probe } from "./probe.mjs";
import childProcess from "node:child_process";
import { SELF_CONTAINED_FORMATS } from "./ff-binaries.mjs";
import childProcess, { spawnSync } from "node:child_process";
import { syncBuiltinESMExports } from "node:module";
function mockProbe(t, streams, format = { duration: "2" }) {
@@ -235,3 +236,59 @@ test("a file whose name reads as an ffmpeg pattern is never probed", (t) => {
});
assert.equal(calls.mock.callCount(), 0);
});
test("probe reads a file only as one local self-contained container", (t) => {
let seen = [];
t.mock.method(childProcess, "execFileSync", (_binary, args) => {
seen = args;
return JSON.stringify({ streams: [AUDIO_STREAM], format: { duration: "3" } });
});
syncBuiltinESMExports();
t.after(() => {
t.mock.restoreAll();
syncBuiltinESMExports();
});
probe("/project/assets/song.mp3");
const at = (flag) => seen.indexOf(flag);
assert.equal(seen[at("-protocol_whitelist") + 1], "file");
assert.equal(seen[at("-format_whitelist") + 1], SELF_CONTAINED_FORMATS);
assert.ok(at("-format_whitelist") < seen.indexOf("/project/assets/song.mp3"));
});
const realFfprobe = spawnSync("ffprobe", ["-version"]).status === 0;
test(
"ordinary assets keep their metadata, and a list or manifest named as media reads as nothing",
{ skip: !realFfprobe },
(t) => {
const dir = mkdtempSync(join(tmpdir(), "mu-probe-lists-"));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const make = (name, args) =>
spawnSync("ffmpeg", ["-v", "error", "-y", ...args, join(dir, name)], { stdio: "ignore" });
make("tone.mp3", ["-f", "lavfi", "-i", "sine=duration=1"]);
make("tone.wav", ["-f", "lavfi", "-i", "sine=duration=1"]);
make("clip.mp4", ["-f", "lavfi", "-i", "color=red:s=32x32:d=1"]);
make("still.png", ["-f", "lavfi", "-i", "color=red:s=32x32", "-frames:v", "1"]);
for (const name of ["tone.mp3", "tone.wav", "clip.mp4", "still.png"]) {
assert.ok(probe(join(dir, name)).codec, name);
}
// Each names the real clip next to it, which ffmpeg would open if it read the list.
const lists = {
"concat.mp4": "ffconcat version 1.0\nfile 'clip.mp4'\n",
"playlist.mp4": "#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nclip.mp4\n#EXT-X-ENDLIST\n",
"manifest.mp4":
'<?xml version="1.0"?><MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static">' +
'<Period><AdaptationSet><Representation id="1" bandwidth="1"><BaseURL>clip.mp4</BaseURL>' +
"</Representation></AdaptationSet></Period></MPD>",
};
for (const [name, text] of Object.entries(lists)) {
writeFileSync(join(dir, name), text);
assert.deepEqual(probe(join(dir, name)), {
duration: null,
width: null,
height: null,
codec: null,
});
}
},
);
@@ -1,7 +1,11 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, onTestFinished } from "vitest";
import {
analyzeMediaGrade,
formatMeasuredNote,
gradeSampleTimes,
parseMediaTreatmentSignalStats,
@@ -109,6 +113,80 @@ describe("vendored media grade analyzer parity", () => {
});
});
// Stand-in ffprobe and ffmpeg that log every call's arguments and answer as the analyzers expect: a demuxer listing
// (for the core module's format list), probe JSON, and signal stats.
function standIns(dir: string): {
ffprobePath: string;
ffmpegPath: string;
calls: () => string[][];
} {
mkdirSync(dir, { recursive: true });
const log = join(dir, "calls.log");
const listing = [
"mov,mp4,m4a,3gp,3g2,mj2",
...["matroska,webm", "mxf", "avi", "mpeg", "mpegts", "mpegvideo", "flv", "asf", "ogg"],
...["wav", "mp3", "aac", "flac", "aiff", "gif", "ico", "image2", "png_pipe", "jpeg_pipe"],
...["webp_pipe", "bmp_pipe", "tiff_pipe", "hls", "concat", "dash", "avisynth", "tty"],
]
.map((name) => ` D ${name} demuxer`)
.join("\\n");
const script = [
"#!/bin/sh",
`for a in "$@"; do printf '%s\\n' "$a"; done >> '${log}'`,
`echo @@END@@ >> '${log}'`,
'case " $* " in',
` *" -demuxers "*) printf '${listing}\\n' ;;`,
` *"-show_entries"*) echo '{"streams":[{"pix_fmt":"yuv420p","duration":"2"}],"format":{"duration":"2"}}' ;;`,
` *) printf '${SIGNALSTATS.replaceAll("\n", "\\n")}\\n' ;;`,
"esac",
].join("\n");
for (const name of ["ffprobe", "ffmpeg"]) {
writeFileSync(join(dir, name), `${script}\n`);
chmodSync(join(dir, name), 0o755);
}
const calls = () =>
readFileSync(log, "utf8")
.split("@@END@@\n")
.map((call) => call.split("\n").filter(Boolean))
.filter((call) => call.length > 0 && !call.includes("-demuxers"));
return { ffprobePath: join(dir, "ffprobe"), ffmpegPath: join(dir, "ffmpeg"), calls };
}
/** The readers a call allows for `file`, from its `-format_whitelist`; null when it sets none before the file. */
function readersFor(call: string[], file: string): Set<string> | null {
const at = call.indexOf("-format_whitelist");
if (at < 0 || at > call.indexOf(file)) return null;
return new Set(call[at + 1]!.split(","));
}
describe.skipIf(process.platform === "win32")("vendored analyzer input limits", () => {
it("open each file with no reader the core module would not use, and only from a local file", async () => {
const root = mkdtempSync(join(tmpdir(), "grade-inputs-"));
onTestFinished(() => rmSync(root, { recursive: true, force: true }));
const file = join(root, "clip.mp4");
writeFileSync(file, "not read");
const core = standIns(join(root, "core"));
analyzeMediaGrade(file, core);
const vendored = standIns(join(root, "vendored"));
const analyzer = await import(
new URL("../../../packages/cli/src/media-use/lib/grade-analyzer.mjs", import.meta.url).href
);
analyzer.analyzeMediaGrade(file, vendored);
const coreCalls = core.calls();
const vendoredCalls = vendored.calls();
expect(coreCalls.length).toBeGreaterThanOrEqual(2);
expect(vendoredCalls.length).toBe(coreCalls.length);
vendoredCalls.forEach((call, index) => {
const allowed = readersFor(coreCalls[index]!, file);
const ours = readersFor(call, file);
expect(allowed, coreCalls[index]!.join(" ")).not.toBeNull();
expect(ours, call.join(" ")).not.toBeNull();
expect([...ours!].filter((reader) => !allowed!.has(reader))).toEqual([]);
expect(call[call.indexOf("-protocol_whitelist") + 1]).toBe("file");
});
});
});
describe("signal-stats frame headers", () => {
it.each([
["frame:123 pts:42 pts_time:-12.5", -12.5],