fix(cli): writes into a project folder never follow a link already there (#8334)

* fix(cli): writes into a project folder never follow a link already there

normalize-audio, media-use generate, transcript-cut, transcribe, the SFX credits and
heygen-tts no longer write through a link at their output or temp names. A .media/.lock
that is a folder or a link fails at once instead of spinning, and media-use type
folders are checked before they are made.

* fix(cli): every other in-place project write goes through the shared writer

upgrade's wrapper rewrite, media-treatment, beats, snapshot descriptions, motionShot and
measure extract no longer write through a link at their output.

* fix(cli): the credits file is read without following a link, in one step

* chore(skills): regenerate the skills manifest for the media-use change

* fix(cli): upgrade keeps a wrapper script's mode when it rewrites the pin

Also: transcript-cut makes its staging folder only once it encodes, and a linked media type
folder is named as a link rather than as leading outside the project.

* fix(cli): upgrade reads a wrapper's mode and text from one open file
This commit is contained in:
Miguel Ángel
2026-11-21 03:36:53 +00:00
committed by GitHub
parent 63d1bb5596
commit 4a50fb2798
22 changed files with 508 additions and 124 deletions
+3 -2
View File
@@ -1,6 +1,7 @@
import { failCommand } from "../utils/commandResult.js";
import { defineCommand } from "../utils/defineCommand.js";
import { existsSync, readFileSync, mkdirSync, statSync, writeFileSync } from "node:fs";
import { existsSync, readFileSync, mkdirSync, statSync } from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { join, dirname, resolve } from "node:path";
import {
analyzeMusicFromSignal,
@@ -170,7 +171,7 @@ export default defineCommand({
if (!isSafePath(project.dir, outPath))
fail(`Beat file path resolves outside the project: ${rel}`);
mkdirSync(dirname(outPath), { recursive: true });
writeFileSync(outPath, serializeBeats(result.beatTimes, result.beatStrengths, rel));
replaceFileAtomically(outPath, serializeBeats(result.beatTimes, result.beatStrengths, rel));
report(`beats/${rel}.json`, result, Boolean(args.json));
},
});
+61 -23
View File
@@ -1,10 +1,11 @@
// Pixels from the original, as project media: a still at one moment or a clip over a window, cropped to a region,
// frame-exact, recorded in the media ledger as cut from the original. A rebuild reuses footage, photos and people
// this way instead of drawing or generating them.
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { createStagingDir } from "@hyperframes/core/atomic-file";
import { makeOutputFolder } from "../../utils/outputFolder.js";
import { tmpdir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";
import { basename, dirname, join, relative, resolve } from "node:path";
import { defineCommand } from "../../utils/defineCommand.js";
import type { Example } from "../_examples.js";
import { jsonArg, num, roiArg, runMeasure, videoAndRoi, videoArg } from "../../measure/command.js";
@@ -18,6 +19,17 @@ import {
type VideoInfo,
} from "../../measure/media.js";
function encodeOnto(out: string, encode: (staged: string) => void): void {
const staging = createStagingDir(dirname(out), ".hf-extract-");
try {
const staged = join(staging, basename(out));
encode(staged);
renameSync(staged, out);
} finally {
rmSync(staging, { recursive: true, force: true });
}
}
export const examples: Example[] = [
[
"A photo from the original at 3.2 s, cropped to its box",
@@ -76,7 +88,9 @@ export async function cutStill(info: VideoInfo, at: number, roi: Roi, out: strin
try {
const full = join(work, "frame.png");
writeFileSync(full, png);
runFfmpeg(["-y", "-i", full, "-vf", crop(roi), "-frames:v", "1", out]);
encodeOnto(out, (staged) =>
runFfmpeg(["-y", "-i", full, "-vf", crop(roi), "-frames:v", "1", staged]),
);
} finally {
rmSync(work, { recursive: true, force: true });
}
@@ -100,25 +114,36 @@ export function cutClip(
const sound = Boolean(opts.audio && info.audio);
// Frames picked by index, as diff and the event map count them: a seek keeps whichever frame is showing at the
// seek time, which at some rates is the one before k0.
runFfmpeg([
...["-y", "-i", info.path],
...[
"-vf",
`trim=start_frame=${k0}:end_frame=${k1},setpts=PTS-STARTPTS,${crop(roi)},format=yuv420p`,
],
...["-r", info.fpsText, "-c:v", "libx264", "-crf", String(opts.crf ?? 14), "-preset", "medium"],
...(sound
? [
"-af",
`atrim=start=${a}:end=${k1 / info.fps},asetpts=PTS-STARTPTS`,
"-c:a",
"aac",
"-b:a",
"192k",
]
: ["-an"]),
...["-movflags", "+faststart", out],
]);
encodeOnto(out, (staged) =>
runFfmpeg([
...["-y", "-i", info.path],
...[
"-vf",
`trim=start_frame=${k0}:end_frame=${k1},setpts=PTS-STARTPTS,${crop(roi)},format=yuv420p`,
],
...[
"-r",
info.fpsText,
"-c:v",
"libx264",
"-crf",
String(opts.crf ?? 14),
"-preset",
"medium",
],
...(sound
? [
"-af",
`atrim=start=${a}:end=${k1 / info.fps},asetpts=PTS-STARTPTS`,
"-c:a",
"aac",
"-b:a",
"192k",
]
: ["-an"]),
...["-movflags", "+faststart", staged],
]),
);
return {
window: [round(a, 3), round(k1 / info.fps, 3)],
frames: n,
@@ -138,7 +163,20 @@ export function cutSound(info: VideoInfo, from: number, to: number, out: string)
: /\.mp3$/i.test(out)
? ["-c:a", "libmp3lame", "-q:a", "2"]
: ["-c:a", "aac", "-b:a", "256k"];
runFfmpeg(["-y", "-ss", String(a), "-i", info.path, "-t", String(b - a), "-vn", ...codec, out]);
encodeOnto(out, (staged) =>
runFfmpeg([
"-y",
"-ss",
String(a),
"-i",
info.path,
"-t",
String(b - a),
"-vn",
...codec,
staged,
]),
);
return { window: [round(a, 3), round(b, 3)], duration: round(b - a, 3) };
}
+3 -2
View File
@@ -1,4 +1,5 @@
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { relative, resolve } from "node:path";
import {
HF_COLOR_GRADING_ATTR,
@@ -734,7 +735,7 @@ async function prepareMutation(args: MediaTreatmentCommandArgs) {
const lintResult = await lintHyperframeHtml(result.html);
const findings = lintResult.findings.filter(({ code }) => code.startsWith("color_grading_"));
const lint = { ok: findings.every(({ severity }) => severity !== "error"), findings };
if (result.changed && !dryRun) writeFileSync(filePath, result.html);
if (result.changed && !dryRun) replaceFileAtomically(filePath, result.html);
const action: "clear" | "apply" = result.targets.every(({ value }) => value === null)
? "clear"
+5 -4
View File
@@ -12,7 +12,8 @@ import { launchWithPageNetwork } from "../browser/pageNetwork.js";
// exactly what it's editing. All geometry + SVG live in ./motionShotLayout.ts
// (pure, tested); this file only drives the browser and SAMPLES.
import { statSync, writeFileSync } from "node:fs";
import { statSync } from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { makeOutputFolder } from "../utils/outputFolder.js";
import { dirname, resolve } from "node:path";
import { pageNavigationTimeoutMs } from "../utils/renderArgs.js";
@@ -676,7 +677,7 @@ async function captureGhostOnionSkin(
)) as string;
const b64 = String(dataUrl).replace(/^data:image\/png;base64,/, "");
if (!b64) throw new Error("ghost composite returned no data");
writeFileSync(outPath, Buffer.from(b64, "base64"));
replaceFileAtomically(outPath, Buffer.from(b64, "base64"));
return outPath;
}
@@ -734,7 +735,7 @@ async function captureRenderedSvgStrip(
await new Promise((resolveWait) => setTimeout(resolveWait, 60));
const output = await page.screenshot({ type: "png" });
if (!output) throw new Error("screenshot returned no data");
writeFileSync(outPath, output as Uint8Array);
replaceFileAtomically(outPath, output as Uint8Array);
return outPath;
}
@@ -777,7 +778,7 @@ async function captureMarkerOnionSkin(
const buf = await page.screenshot({ type: "png" });
if (!buf) throw new Error("screenshot returned no data");
writeFileSync(outPath, buf as Uint8Array);
replaceFileAtomically(outPath, buf as Uint8Array);
return outPath;
}
@@ -1,4 +1,12 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import {
lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCommand } from "citty";
@@ -71,6 +79,40 @@ describe("absolute normalize-audio command", () => {
});
});
// fails without the fix: the rewrite went through a link at its pid-named temp file, onto a file outside.
describe("normalize-audio --write never writes through a link at its temp name", () => {
it("leaves the link's target alone and writes the composition in the project", async () => {
const root = mkdtempSync(join(tmpdir(), "hf-normalize-link-test-"));
const log = vi.spyOn(console, "log").mockImplementation(() => {});
try {
const dir = join(root, "project");
mkdirSync(dir);
const outside = join(root, "outside.txt");
writeFileSync(outside, "keep me");
const path = join(dir, "index.html");
writeFileSync(
path,
`<audio id="voice" src="voice.wav" data-volume="0" data-duration="2"></audio>`,
);
writeFileSync(join(dir, "voice.wav"), "audio bytes");
symlinkSync(outside, `${path}.hf-normalize-${process.pid}.tmp`);
measureAudio.mockResolvedValue({ integratedLufs: -20, truePeakDbfs: -12.3 });
await runCommand(normalizeAudioCommand, {
rawArgs: [dir, "--target", "voice", "--json", "--write"],
});
expect(readFileSync(outside, "utf8")).toBe("keep me");
expect(readFileSync(path, "utf8")).toMatch(/data-volume="(?!0")/);
expect(lstatSync(path).isSymbolicLink()).toBe(false);
} finally {
log.mockRestore();
measureAudio.mockReset();
rmSync(root, { recursive: true, force: true });
}
});
});
describe("normalize-audio on a clip inside a mounted scene", () => {
it("measures it and writes the gain into the scene file", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-normalize-scene-test-"));
+3 -8
View File
@@ -1,4 +1,5 @@
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { relative, resolve } from "node:path";
import {
absoluteLoudnessPlan,
@@ -122,12 +123,6 @@ async function measuredPlan(
);
}
function writeAtomically(path: string, contents: string): void {
const temporary = `${path}.hf-normalize-${process.pid}.tmp`;
writeFileSync(temporary, contents);
renameSync(temporary, path);
}
function parsedTolerance(raw: string): number {
const tolerance = Number(raw);
if (!Number.isFinite(tolerance) || tolerance < 0) {
@@ -195,7 +190,7 @@ async function normalizeAudio(options: NormalizeAudioOptions): Promise<Normalize
const heldByLimit = targetTag.volume > 0 && heldAtLimit(plan, tolerance);
const wrote = options.write && !withinTolerance && !heldByLimit;
if (wrote) {
writeAtomically(
replaceFileAtomically(
filePath,
updateAudioVolume(readFileSync(filePath, "utf8"), targetTag.id, plan.volume),
);
+2 -3
View File
@@ -54,10 +54,9 @@ import {
mkdirSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { createStagingDir } from "@hyperframes/core/atomic-file";
import { createStagingDir, replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { sumOf } from "../measure/media.js";
import { resolve, join, relative, isAbsolute, basename, posix } from "node:path";
import {
@@ -2166,7 +2165,7 @@ export default defineCommand({
}
const descPath = join(snapshotDir, "descriptions.md");
writeFileSync(descPath, descriptions.join("\n"));
replaceFileAtomically(descPath, descriptions.join("\n"));
describedPath = descPath;
log(` ${c.dim("descriptions.md")} (Gemini frame analysis)`);
}
@@ -1,5 +1,13 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import {
chmodSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -91,6 +99,19 @@ describe("upgradeProjectPins", () => {
expect(readFileSync(publish, "utf8")).toContain("hyperframes@0.7.55");
});
// fails without the fix: the rewritten wrapper came back 0644, so `./render.sh` no longer ran.
it.skipIf(process.platform === "win32")("keeps an executable wrapper executable", async () => {
const d = project({});
const wrapper = join(d, "render.sh");
writeFileSync(wrapper, "npx --yes hyperframes@0.7.48 render\n");
chmodSync(wrapper, 0o755);
await upgradeProjectPins(d, { json: false, check: false });
expect(readFileSync(wrapper, "utf8")).toContain("hyperframes@0.7.55");
expect(statSync(wrapper).mode & 0o777).toBe(0o755);
});
it.skipIf(process.platform === "win32")(
"leaves the target of a package.json.tmp link untouched",
async () => {
+22 -3
View File
@@ -4,7 +4,15 @@ import { defineCommand } from "../utils/defineCommand.js";
import type { Example } from "./_examples.js";
import * as clack from "../ui/prompts.js";
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, writeFileSync, readdirSync } from "node:fs";
import {
closeSync,
constants,
existsSync,
fstatSync,
openSync,
readdirSync,
readFileSync,
} from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { join, resolve } from "node:path";
import { c } from "../ui/colors.js";
@@ -273,6 +281,15 @@ export function resolveProjectArgs(
return { dir: project, check: opts.check, json: opts.json };
}
function readWrapper(path: string): { mode: number; text: string } {
const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
try {
return { mode: fstatSync(fd).mode & 0o7777, text: readFileSync(fd, "utf-8") };
} finally {
closeSync(fd);
}
}
export async function upgradeProjectPins(
dir: string,
opts: { json: boolean; check: boolean },
@@ -292,7 +309,8 @@ export async function upgradeProjectPins(
.filter((entry) => entry.isFile() && entry.name.endsWith(".sh"))
.map((entry) => {
const path = resolve(dir, entry.name);
return { path, rewrite: rewritePinnedHyperframesText(readFileSync(path, "utf-8"), latest) };
const { mode, text } = readWrapper(path);
return { path, mode, rewrite: rewritePinnedHyperframesText(text, latest) };
});
if (rewrite.changed && !opts.check) {
raw.scripts = rewrite.scripts;
@@ -300,7 +318,8 @@ export async function upgradeProjectPins(
}
if (!opts.check) {
for (const wrapper of wrapperRewrites) {
if (wrapper.rewrite.changed) writeFileSync(wrapper.path, wrapper.rewrite.text, "utf-8");
if (wrapper.rewrite.changed)
replaceFileAtomically(wrapper.path, wrapper.rewrite.text, wrapper.mode);
}
}
const from = new Set(rewrite.fromVersions);
@@ -1,6 +1,6 @@
import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
import { withReservedFile, withReservedFileSync } from "./manifest.mjs";
import { withReservedFile, withReservedFileSync, writeTempBeside } from "./manifest.mjs";
import { freezeUrl } from "./freeze.mjs";
import { tokenOverlap } from "./match.mjs";
import { buildCube } from "./cube-build.mjs";
@@ -245,13 +245,13 @@ export async function freezeLibraryLut(match, { projectDir, type, localOnly = fa
if (match.params) {
return withReservedFileSync(projectDir, type, ".cube", ({ id, localPath, fullPath }) => {
const tmpPath = `${fullPath}.tmp`;
let tmpPath = null;
try {
const cube = buildCube(match.params);
assertValidCubeText(cube, `invalid library LUT ${match.id}`);
// Write + validate at .tmp, then atomic rename — same no-orphan guarantee
// Write + validate at a temp file, then atomic rename — same no-orphan guarantee
// as the url path above.
writeFileSync(tmpPath, cube);
tmpPath = writeTempBeside(fullPath, cube);
assertValidCubeFile(tmpPath, `invalid frozen LUT ${localPath}`);
renameSync(tmpPath, fullPath);
return libraryRecord(match, {
@@ -261,7 +261,7 @@ export async function freezeLibraryLut(match, { projectDir, type, localOnly = fa
via: match.url ? "params-fallback" : "params",
});
} finally {
rmSync(tmpPath, { force: true });
if (tmpPath) rmSync(tmpPath, { force: true });
}
});
}
+39 -17
View File
@@ -9,7 +9,6 @@ import {
writeSync,
rmSync,
renameSync,
statSync,
lstatSync,
realpathSync,
constants,
@@ -89,6 +88,22 @@ export function ownMediaDir(projectDir) {
return dir;
}
/** The project's own folder for `type` under `.media`, made if missing; throws when any folder on the way is a link. */
export function ownTypeDir(projectDir, type) {
let dir = ownMediaDir(projectDir);
// Each folder is looked at before it is made, so nothing is ever made through a link.
for (const part of typeSubdir(type).split("/")) {
dir = join(dir, part);
if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {
throw new Error(
`${dir} is a link; media is written only into real folders, so nothing was written there`,
);
}
mkdirSync(dir, { recursive: true });
}
return dir;
}
/** Throws when `path` is a link. */
export function refuseLink(path) {
if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {
@@ -96,18 +111,29 @@ export function refuseLink(path) {
}
}
/** Replaces the file at `path` with `content` by writing a temp file beside it and renaming it over, so a link there is replaced, never followed. */
export function replaceFile(path, content) {
/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */
export function writeTempBeside(path, content) {
// Same shape as core atomicTempPath, which Studio's project history skips.
const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`;
try {
writeFileSync(temp, content, { flag: "wx" });
renameRidingWindowsHolds(temp, path);
} catch (error) {
// EEXIST: the random name belongs to another writer, so it is left alone.
if (error?.code !== "EEXIST") rmSync(temp, { force: true });
throw error;
}
return temp;
}
/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */
export function replaceFile(path, content) {
const temp = writeTempBeside(path, content);
try {
renameRidingWindowsHolds(temp, path);
} catch (error) {
rmSync(temp, { force: true });
throw error;
}
}
// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file.
@@ -127,9 +153,7 @@ function renameRidingWindowsHolds(from, to) {
}
export function appendRecord(projectDir, record) {
ownMediaDir(projectDir);
const typeDir = typeDirPath(projectDir, record.type);
mkdirSync(typeDir, { recursive: true });
ownTypeDir(projectDir, record.type);
const p = manifestPath(projectDir);
refuseLink(p);
@@ -246,13 +270,12 @@ function withLock(dir, fn) {
break;
} catch (err) {
if (err.code !== "EEXIST") throw err;
try {
if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
rmSync(lock, { force: true }); // steal a stale lock from a dead holder
continue;
}
} catch {
continue; // lock vanished between check and stat — retry the acquire
const held = lstatSync(lock, { throwIfNoEntry: false });
if (!held) continue; // released between the open and the look: retry the acquire
if (!held.isFile()) throw new Error(`${lock} is not a lock file; remove it and try again`);
if (Date.now() - held.mtimeMs > LOCK_STALE_MS) {
rmSync(lock, { force: true }); // steal a stale lock from a dead holder
continue;
}
if (Date.now() - start > LOCK_TIMEOUT_MS) {
throw new Error("media-use: timed out acquiring .media/.lock");
@@ -269,8 +292,7 @@ function withLock(dir, fn) {
/** Runs `fn` holding the project's `.media/.lock`, so concurrent resolves take turns on what it guards. */
export function withMediaLock(projectDir, fn) {
mkdirSync(mediaDir(projectDir), { recursive: true });
return withLock(mediaDir(projectDir), fn);
return withLock(ownMediaDir(projectDir), fn);
}
// Atomically allocate the next free id for `type` AND reserve it on disk, so a
@@ -280,7 +302,7 @@ export function withMediaLock(projectDir, fn) {
// O_EXCL-create an empty marker under core's atomic temp name, which Studio's
// project history skips. Returns { id, localPath, markerPath }.
export function allocateId(projectDir, type, ext) {
mkdirSync(typeDirPath(projectDir, type), { recursive: true });
ownTypeDir(projectDir, type);
return withMediaLock(projectDir, () => {
const id = nextFreeId(projectDir, type);
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
@@ -7,6 +7,7 @@ import {
mkdirSync,
existsSync,
readdirSync,
symlinkSync,
} from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
@@ -23,6 +24,7 @@ import {
mediaDir,
typeDirPath,
typeSubdir,
withMediaLock,
} from "./manifest.mjs";
import { regenerateIndex, generateIndexContent } from "./index-gen.mjs";
import {
@@ -376,6 +378,43 @@ function runTests() {
// --- run ---
// fails without the fix: a .media/.lock that is a folder or a dead link spun forever at full CPU.
test("the media lock refuses a lock that is a folder or a link, at once", () => {
for (const plant of [
(lock) => mkdirSync(lock),
(lock) => symlinkSync(join(lock, "..", "gone"), lock),
]) {
const project = mkdtempSync(join(tmpdir(), "mu-lock-"));
try {
mkdirSync(join(project, ".media"));
plant(join(project, ".media", ".lock"));
const started = Date.now();
assert.throws(() => withMediaLock(project, () => "ran"), /not a lock file/);
assert.ok(Date.now() - started < 5000);
} finally {
rmSync(project, { recursive: true, force: true });
}
}
});
// fails without the fix: a linked .media/audio folder took reserved files and records outside the project.
test("a media type folder that is a link is refused before anything is made through it", () => {
const project = mkdtempSync(join(tmpdir(), "mu-typedir-"));
const outside = mkdtempSync(join(tmpdir(), "mu-outside-"));
try {
mkdirSync(join(project, ".media"));
symlinkSync(outside, join(project, ".media", "audio"));
assert.throws(
() => allocateId(project, "sfx", ".mp3"),
/is a link; media is written only into real folders/,
);
assert.deepEqual(readdirSync(outside), []);
} finally {
rmSync(project, { recursive: true, force: true });
rmSync(outside, { recursive: true, force: true });
}
});
let passed = 0;
let failed = 0;
for (const { name, fn } of tests) {
+34 -5
View File
@@ -2,7 +2,17 @@
// Anonymous use is rate limited (20 requests a minute, 200 a day); callers fall
// back to the bundled library when it is unavailable.
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import {
closeSync,
constants,
mkdirSync,
openSync,
readFileSync,
renameSync,
rmSync,
writeFileSync,
} from "node:fs";
import { dirname } from "node:path";
const OPENVERSE_AUDIO_URL = "https://api.openverse.org/v1/audio/";
@@ -117,18 +127,37 @@ export function writeSfxCredit(creditsPath, file, sound) {
// The sound may come from a saved record, not this run's pick: clean it again here.
const sourceUrl = httpsUrl(sound.sourceUrl, SOURCE_HOSTS);
const source = sourceUrl ? ` Source: ${sourceUrl}` : "";
const line = `- \`${file}\`: ${oneLine(sound.credit)}${source}`;
const name = oneLine(file);
const line = `- \`${name}\`: ${oneLine(sound.credit)}${source}`;
let prior = "";
let fd;
try {
prior = readFileSync(creditsPath, "utf8");
fd = openSync(creditsPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
} catch (error) {
if (error.code === "ELOOP")
throw new Error(`${creditsPath} is a link; nothing was written through it`);
if (error.code !== "ENOENT") throw error;
}
if (fd !== undefined) {
try {
prior = readFileSync(fd, "utf8");
} finally {
closeSync(fd);
}
}
const kept = prior
.split("\n")
.filter((l) => l.startsWith("- ") && !l.startsWith(`- \`${file}\`:`));
.filter((l) => l.startsWith("- ") && !l.startsWith(`- \`${name}\`:`));
const header =
"# Sound effect credits\n\nThese sounds are licensed CC BY: credit them wherever the video is published.\n\n";
mkdirSync(dirname(creditsPath), { recursive: true });
writeFileSync(creditsPath, `${header}${[...kept, line].join("\n")}\n`);
// The audio skill ships this file alone, so it cannot use manifest.mjs's replaceFile.
const temp = `${creditsPath}.hf${randomBytes(3).toString("hex")}.tmp`;
writeFileSync(temp, `${header}${[...kept, line].join("\n")}\n`, { flag: "wx" });
try {
renameSync(temp, creditsPath);
} catch (error) {
rmSync(temp, { force: true });
throw error;
}
}
@@ -1,5 +1,13 @@
import { strict as assert } from "node:assert";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import {
lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
@@ -217,3 +225,38 @@ test("earlier credit lines survive a new credit", () => {
rmSync(dir, { recursive: true, force: true });
}
});
// fails without the fix: a linked CREDITS.md had its target overwritten with the project's text.
test("credits are never written through a link at the credits file", () => {
const dir = mkdtempSync(join(tmpdir(), "openverse-credits-link-"));
try {
const outside = join(dir, "outside.txt");
writeFileSync(outside, "keep me\n- secret line\n");
const path = join(dir, "project", ".media", "audio", "sfx", "CREDITS.md");
mkdirSync(join(dir, "project", ".media", "audio", "sfx"), { recursive: true });
symlinkSync(outside, path);
const by = { license: "by", credit: '"Pop" by Ana', sourceUrl: "https://freesound.org/s/1" };
assert.throws(() => writeSfxCredit(path, "assets/sfx/pop.mp3", by), /link/);
assert.equal(readFileSync(outside, "utf8"), "keep me\n- secret line\n");
assert.ok(lstatSync(path).isSymbolicLink());
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
// fails without the fix: a record path with a newline added lines of its own to the credits file.
test("a file name with a line break or backtick stays one credit line", () => {
const dir = mkdtempSync(join(tmpdir(), "openverse-credits-line-"));
try {
const path = join(dir, "CREDITS.md");
const by = { license: "by", credit: '"Pop" by Ana', sourceUrl: "https://freesound.org/s/1" };
writeSfxCredit(path, "a.mp3`\n- injected line", by);
const lines = readFileSync(path, "utf8")
.split("\n")
.filter((l) => l.startsWith("- "));
assert.equal(lines.length, 1);
assert.doesNotMatch(lines[0], /\n|`a\.mp3`.*`/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+8 -7
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { existsSync, statSync, writeFileSync, renameSync, rmSync, realpathSync } from "node:fs";
import { existsSync, statSync, renameSync, rmSync, realpathSync } from "node:fs";
import { resolve, join, extname, basename, relative, isAbsolute, sep } from "node:path";
import { parseArgs } from "node:util";
import {
@@ -12,8 +12,9 @@ import {
findByPrompt,
findByEntity,
nextId,
typeDirPath,
ownTypeDir,
withMediaLock,
writeTempBeside,
withReservedFile,
withReservedFileSync,
} from "./lib/manifest.mjs";
@@ -653,16 +654,16 @@ function freezeGeneratedLut(
},
) {
return withReservedFileSync(projectDir, type, ".cube", ({ id, localPath, fullPath }) => {
const tmpPath = `${fullPath}.tmp`;
let tmpPath = null;
try {
// Write + validate at .tmp, then atomic rename, so a crash between write and
// Write + validate at a temp file, then atomic rename, so a crash between write and
// validate can't leave an invalid .cube at the final path.
writeFileSync(tmpPath, buildCube(params));
tmpPath = writeTempBeside(fullPath, buildCube(params));
const check = validateCubeFile(tmpPath);
if (!check.ok) throw new Error(check.error);
renameSync(tmpPath, fullPath);
} catch (err) {
rmSync(tmpPath, { force: true });
if (tmpPath) rmSync(tmpPath, { force: true });
throw new Error(`${validationErrorPrefix}: ${err.message}`);
}
return {
@@ -1351,7 +1352,7 @@ async function result(record, source, match = recordedMatch(record)) {
// Under the media lock: two resolves at once each read, then rewrite, the whole credits file.
if (provider === OPENVERSE_SFX_PROVIDER)
withMediaLock(projectDir, () =>
writeSfxCredit(join(typeDirPath(projectDir, "sfx"), "CREDITS.md"), record.path, {
writeSfxCredit(join(ownTypeDir(projectDir, "sfx"), "CREDITS.md"), record.path, {
license,
credit,
sourceUrl,
+1 -1
View File
@@ -18,7 +18,7 @@
"files": 13
},
"media-use": {
"hash": "cebaf2c0fa1d49ca",
"hash": "e31a0f67f111ee82",
"files": 131
},
"remotion-to-hyperframes": {
@@ -2,7 +2,17 @@
// Anonymous use is rate limited (20 requests a minute, 200 a day); callers fall
// back to the bundled library when it is unavailable.
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import {
closeSync,
constants,
mkdirSync,
openSync,
readFileSync,
renameSync,
rmSync,
writeFileSync,
} from "node:fs";
import { dirname } from "node:path";
const OPENVERSE_AUDIO_URL = "https://api.openverse.org/v1/audio/";
@@ -117,18 +127,37 @@ export function writeSfxCredit(creditsPath, file, sound) {
// The sound may come from a saved record, not this run's pick: clean it again here.
const sourceUrl = httpsUrl(sound.sourceUrl, SOURCE_HOSTS);
const source = sourceUrl ? ` Source: ${sourceUrl}` : "";
const line = `- \`${file}\`: ${oneLine(sound.credit)}${source}`;
const name = oneLine(file);
const line = `- \`${name}\`: ${oneLine(sound.credit)}${source}`;
let prior = "";
let fd;
try {
prior = readFileSync(creditsPath, "utf8");
fd = openSync(creditsPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
} catch (error) {
if (error.code === "ELOOP")
throw new Error(`${creditsPath} is a link; nothing was written through it`);
if (error.code !== "ENOENT") throw error;
}
if (fd !== undefined) {
try {
prior = readFileSync(fd, "utf8");
} finally {
closeSync(fd);
}
}
const kept = prior
.split("\n")
.filter((l) => l.startsWith("- ") && !l.startsWith(`- \`${file}\`:`));
.filter((l) => l.startsWith("- ") && !l.startsWith(`- \`${name}\`:`));
const header =
"# Sound effect credits\n\nThese sounds are licensed CC BY: credit them wherever the video is published.\n\n";
mkdirSync(dirname(creditsPath), { recursive: true });
writeFileSync(creditsPath, `${header}${[...kept, line].join("\n")}\n`);
// The audio skill ships this file alone, so it cannot use manifest.mjs's replaceFile.
const temp = `${creditsPath}.hf${randomBytes(3).toString("hex")}.tmp`;
writeFileSync(temp, `${header}${[...kept, line].join("\n")}\n`, { flag: "wx" });
try {
renameSync(temp, creditsPath);
} catch (error) {
rmSync(temp, { force: true });
throw error;
}
}
+39 -17
View File
@@ -9,7 +9,6 @@ import {
writeSync,
rmSync,
renameSync,
statSync,
lstatSync,
realpathSync,
constants,
@@ -89,6 +88,22 @@ export function ownMediaDir(projectDir) {
return dir;
}
/** The project's own folder for `type` under `.media`, made if missing; throws when any folder on the way is a link. */
export function ownTypeDir(projectDir, type) {
let dir = ownMediaDir(projectDir);
// Each folder is looked at before it is made, so nothing is ever made through a link.
for (const part of typeSubdir(type).split("/")) {
dir = join(dir, part);
if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {
throw new Error(
`${dir} is a link; media is written only into real folders, so nothing was written there`,
);
}
mkdirSync(dir, { recursive: true });
}
return dir;
}
/** Throws when `path` is a link. */
export function refuseLink(path) {
if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {
@@ -96,18 +111,29 @@ export function refuseLink(path) {
}
}
/** Replaces the file at `path` with `content` by writing a temp file beside it and renaming it over, so a link there is replaced, never followed. */
export function replaceFile(path, content) {
/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */
export function writeTempBeside(path, content) {
// Same shape as core atomicTempPath, which Studio's project history skips.
const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`;
try {
writeFileSync(temp, content, { flag: "wx" });
renameRidingWindowsHolds(temp, path);
} catch (error) {
// EEXIST: the random name belongs to another writer, so it is left alone.
if (error?.code !== "EEXIST") rmSync(temp, { force: true });
throw error;
}
return temp;
}
/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */
export function replaceFile(path, content) {
const temp = writeTempBeside(path, content);
try {
renameRidingWindowsHolds(temp, path);
} catch (error) {
rmSync(temp, { force: true });
throw error;
}
}
// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file.
@@ -127,9 +153,7 @@ function renameRidingWindowsHolds(from, to) {
}
export function appendRecord(projectDir, record) {
ownMediaDir(projectDir);
const typeDir = typeDirPath(projectDir, record.type);
mkdirSync(typeDir, { recursive: true });
ownTypeDir(projectDir, record.type);
const p = manifestPath(projectDir);
refuseLink(p);
@@ -246,13 +270,12 @@ function withLock(dir, fn) {
break;
} catch (err) {
if (err.code !== "EEXIST") throw err;
try {
if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
rmSync(lock, { force: true }); // steal a stale lock from a dead holder
continue;
}
} catch {
continue; // lock vanished between check and stat — retry the acquire
const held = lstatSync(lock, { throwIfNoEntry: false });
if (!held) continue; // released between the open and the look: retry the acquire
if (!held.isFile()) throw new Error(`${lock} is not a lock file; remove it and try again`);
if (Date.now() - held.mtimeMs > LOCK_STALE_MS) {
rmSync(lock, { force: true }); // steal a stale lock from a dead holder
continue;
}
if (Date.now() - start > LOCK_TIMEOUT_MS) {
throw new Error("media-use: timed out acquiring .media/.lock");
@@ -269,8 +292,7 @@ function withLock(dir, fn) {
/** Runs `fn` holding the project's `.media/.lock`, so concurrent resolves take turns on what it guards. */
export function withMediaLock(projectDir, fn) {
mkdirSync(mediaDir(projectDir), { recursive: true });
return withLock(mediaDir(projectDir), fn);
return withLock(ownMediaDir(projectDir), fn);
}
// Atomically allocate the next free id for `type` AND reserve it on disk, so a
@@ -280,7 +302,7 @@ export function withMediaLock(projectDir, fn) {
// O_EXCL-create an empty marker under core's atomic temp name, which Studio's
// project history skips. Returns { id, localPath, markerPath }.
export function allocateId(projectDir, type, ext) {
mkdirSync(typeDirPath(projectDir, type), { recursive: true });
ownTypeDir(projectDir, type);
return withMediaLock(projectDir, () => {
const id = nextFreeId(projectDir, type);
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
+12 -15
View File
@@ -2,15 +2,8 @@
import "./lib/windows-exe-search.mjs";
import { execFileSync } from "node:child_process";
import {
existsSync,
readFileSync,
writeFileSync,
copyFileSync,
renameSync,
mkdtempSync,
rmSync,
} from "node:fs";
import { existsSync, readFileSync, writeFileSync, renameSync, mkdtempSync, rmSync } from "node:fs";
import { randomBytes } from "node:crypto";
import { homedir, tmpdir } from "node:os";
import { basename, extname, join, resolve } from "node:path";
import { parseArgs, stripVTControlCharacters } from "node:util";
@@ -95,10 +88,16 @@ function resolveParakeet() {
// Write via a sibling temp + atomic rename so a SIGKILL mid-write can't leave a
// truncated transcript at outPath (downstream reads it as valid JSON).
// The temp name is random and created exclusively, so a link beside the target is never written through.
function atomicWrite(target, data) {
const tmp = `${target}.tmp-${process.pid}`;
writeFileSync(tmp, data);
renameSync(tmp, target);
const tmp = `${target}.hf${randomBytes(3).toString("hex")}.tmp`;
writeFileSync(tmp, data, { flag: "wx" });
try {
renameSync(tmp, target);
} catch (error) {
rmSync(tmp, { force: true });
throw error;
}
}
function report(engine, wordCount) {
@@ -175,9 +174,7 @@ function runCli(cliEngine) {
const produced = join(workDir, "transcript.json");
if (!existsSync(produced))
throw new Error("hyperframes transcribe produced no transcript.json");
const tmp = `${outPath}.tmp-${process.pid}`;
copyFileSync(produced, tmp);
renameSync(tmp, outPath); // atomic publish
atomicWrite(outPath, readFileSync(produced));
let words;
try {
const t = JSON.parse(readFileSync(outPath, "utf8"));
@@ -213,3 +213,46 @@ test(
}
},
);
// fails without the fix: the transcript went through a link at `<out>.tmp-<pid>`, onto a file outside.
test(
"the transcript is never written through a link beside it",
{ skip: process.platform === "win32" },
() => {
const root = mkdtempSync(join(tmpdir(), "media-use-transcribe-link-"));
try {
const outside = join(root, "outside.txt");
writeFileSync(outside, "keep me");
const out = join(root, "in.transcribe.json");
const cli = join(root, "cli.mjs");
// The stand-in runs as this script's child, so its parent pid is the one the temp name would use.
writeFileSync(
cli,
`import { symlinkSync, writeFileSync } from "node:fs";\nconst a = process.argv.slice(2);\n` +
`symlinkSync(${JSON.stringify(outside)}, ${JSON.stringify(out)} + ".tmp-" + process.ppid);\n` +
`writeFileSync(a[a.indexOf("--dir") + 1] + "/transcript.json", '[{"text":"a","start":0,"end":1}]');\n` +
`console.log('{"ok":true,"engine":"whisper"}');\n`,
);
writeFileSync(join(root, "in.wav"), "");
const script = fileURLToPath(new URL("./transcribe.mjs", import.meta.url));
const env = { ...process.env, HYPERFRAMES_CLI_ENTRY: cli, HOME: root };
delete env.HYPERFRAMES_PARAKEET;
execFileSync(
process.execPath,
[script, "--input", join(root, "in.wav"), "--engine", "whisper", "--json"],
{
encoding: "utf8",
env: {
...env,
HYPERFRAMES_MEDIA_HOME: join(root, "home"),
HYPERFRAMES_NO_TELEMETRY: "1",
},
},
);
assert.equal(readFileSync(outside, "utf8"), "keep me");
assert.match(readFileSync(out, "utf8"), /"text"/);
} finally {
rmSync(root, { recursive: true, force: true });
}
},
);
+6 -2
View File
@@ -90,6 +90,8 @@ function run() {
const outPath = resolve(args.out);
mkdirSync(dirname(outPath), { recursive: true });
const tmpDir = mkdtempSync(join(tmpdir(), "media-use-cut-"));
// The encode lands in a new private folder beside --out, so nothing already next to it is written through.
let outDir = null;
const keptSeconds = sumDurations(segments);
const totalSeconds = probeDuration(inputPath);
@@ -122,9 +124,10 @@ function run() {
listPath,
parts.map((part) => `file '${escapeConcatPath(part)}'`).join("\n") + "\n",
);
// Encode to a sibling temp (same extension so ffmpeg picks the right muxer),
// Encode to a temp beside --out (same extension so ffmpeg picks the right muxer),
// then atomic-rename so a SIGKILL mid-encode can't leave a truncated outPath.
const tmpOut = `${outPath}.part${extname(outPath) || ".mp4"}`;
outDir = mkdtempSync(join(dirname(outPath), ".media-use-cut-"));
const tmpOut = join(outDir, `out${extname(outPath) || ".mp4"}`);
// --copy already produced final-codec segments, so concat can stream-copy.
// Otherwise the PCM intermediates are encoded here, once, for the whole file.
const concatCodecs = args.copy
@@ -142,6 +145,7 @@ function run() {
renameSync(tmpOut, outPath);
} finally {
rmSync(tmpDir, { recursive: true, force: true });
if (outDir) rmSync(outDir, { recursive: true, force: true });
}
// Stream copy can only cut on keyframes; on sparse-keyframe footage the snap
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { lstatSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
@@ -339,3 +339,41 @@ test("a kept range starting on a 30 fps frame keeps that frame", { skip: !HAS_FF
);
assert.equal(frames, 88, `expected 88 frames, got ${frames}`);
});
// fails without the fix: ffmpeg encoded through a link at `<out>.part<ext>`, onto a file outside.
test("the cut is never encoded through a link beside --out", { skip: !HAS_FFMPEG }, (t) => {
const { dir, cleanup } = fixture();
t.after(cleanup);
const source = join(dir, "source.wav");
execFileSync("ffmpeg", [
"-y",
"-hide_banner",
"-loglevel",
"error",
"-f",
"lavfi",
"-i",
"sine=duration=1",
source,
]);
const transcriptPath = join(dir, "transcript.json");
writeFileSync(transcriptPath, JSON.stringify({ words: [{ text: "tone", start: 0, end: 1 }] }));
const outside = join(dir, "outside.txt");
writeFileSync(outside, "keep me");
const output = join(dir, "out.wav");
symlinkSync(outside, `${output}.part.wav`);
const result = run([
"--input",
source,
"--transcript",
transcriptPath,
"--keep",
"0.1-0.6",
"--out",
output,
"--json",
]);
assert.equal(result.status, 0, result.stderr || result.stdout);
assert.equal(readFileSync(outside, "utf8"), "keep me");
assert.ok(lstatSync(output).isFile());
});