fix(media-use): refuse links under .media before reserving, writing or recording

A received project could carry links at .media, at a type folder, at the
next asset name or its .tmp name, or at the preferences store's temp
names, and resolve or prefs record wrote through them to files outside
the project.

- ownMediaDir now checks every folder down to the type folder, making
  each one level at a time, before the lock, the allocator, the record
  append or a project preference write touches anything inside it.
- The allocator ignores ids past nine digits, so a planted huge id can't
  push it back onto a name the project holds, and it skips any name that
  already exists.
- The asset writers and the LUT .tmp writers create new files only.
- The preferences store writes through replaceFile, a random temp name
  created exclusively and renamed into place.

Both copies of manifest.mjs and prefs-store.mjs change together.
This commit is contained in:
Michael Wang
2026-11-20 15:50:09 -08:00
parent 0012c1cb88
commit cfedb19aa4
10 changed files with 273 additions and 75 deletions
+5 -5
View File
@@ -5,10 +5,11 @@ import {
existsSync,
copyFileSync,
statSync,
constants,
} from "node:fs";
import { join, basename } from "node:path";
import { join, basename, dirname } from "node:path";
import { createHash } from "node:crypto";
import { readManifest, appendRecord, normalizePrompt } from "./manifest.mjs";
import { readManifest, appendRecord, normalizePrompt, ownMediaDir } from "./manifest.mjs";
import { globalMediaDir, mediaHome } from "./media-home.mjs";
export { globalMediaDir };
@@ -129,10 +130,9 @@ export function importFromCache(cacheRecord, projectDir, localId, localPath) {
const sha = cacheRecord.sha;
const cachedFile = cacheRecord.cached_path;
mkdirSync(join(projectDir, ".media"), { recursive: true });
ownMediaDir(projectDir, dirname(localPath).replace(/^\.media\/?/, ""));
const fullDest = join(projectDir, localPath);
mkdirSync(join(fullDest, ".."), { recursive: true });
copyFileSync(cachedFile, fullDest);
copyFileSync(cachedFile, fullDest, constants.COPYFILE_EXCL);
const projectRecord = {
...cacheRecord,
+4 -3
View File
@@ -1,6 +1,6 @@
import { fetchMedia, isPublicMediaUrl, readCappedBody } from "./media-fetch.mjs";
import { sanitizeSvg } from "./svg-sanitize.mjs";
import { writeFileSync, copyFileSync, mkdirSync, readFileSync } from "node:fs";
import { writeFileSync, copyFileSync, mkdirSync, readFileSync, constants } from "node:fs";
import { dirname } from "node:path";
// ponytail: bound the download so a hostile/runaway URL can't fill the disk.
@@ -16,7 +16,8 @@ const isSvgPath = (destPath) => /\.svg$/i.test(destPath);
function writeFrozen(destPath, buffer) {
mkdirSync(dirname(destPath), { recursive: true });
const bytes = isSvgPath(destPath) ? Buffer.from(sanitizeSvg(buffer.toString("utf8"))) : buffer;
writeFileSync(destPath, bytes);
// "wx": a new file only, so a link planted at the name fails the write instead of being followed.
writeFileSync(destPath, bytes, { flag: "wx" });
return bytes.byteLength;
}
@@ -47,7 +48,7 @@ export function freezeLocalFile(srcPath, destPath) {
return;
}
mkdirSync(dirname(destPath), { recursive: true });
copyFileSync(srcPath, destPath);
copyFileSync(srcPath, destPath, constants.COPYFILE_EXCL);
}
// Ingest accepts a DIRECT public media URL only — not a platform page. yt-dlp is
@@ -0,0 +1,179 @@
import { strict as assert } from "node:assert";
import {
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
realpathSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { test } from "node:test";
import { appendRecord, withReservedFileSync } from "./manifest.mjs";
import { freezeLocalFile } from "./freeze.mjs";
import { freezeLibraryLut, matchColorLook } from "./lut-preset-provider.mjs";
import { projectPrefsPath, recordPreference } from "./prefs-store.mjs";
// Planting a link needs no privileges on macOS and Linux; Windows needs developer mode for file links.
const posixOnly = { skip: process.platform === "win32" };
/** A project folder and a folder outside it holding one file that must survive every test. */
function withSandbox(fn) {
const root = realpathSync(mkdtempSync(join(tmpdir(), "mu-links-")));
const project = join(root, "project");
const outside = join(root, "outside");
mkdirSync(project);
mkdirSync(outside);
writeFileSync(join(outside, "keep.txt"), "keep me\n");
const outsideUnchanged = () => {
assert.deepEqual(readdirSync(outside), ["keep.txt"]);
assert.equal(readFileSync(join(outside, "keep.txt"), "utf8"), "keep me\n");
};
return Promise.resolve(fn({ root, project, outside, outsideUnchanged })).finally(() =>
rmSync(root, { recursive: true, force: true }),
);
}
function plantLink(target, at) {
mkdirSync(dirname(at), { recursive: true });
symlinkSync(target, at);
}
function reserveAndWrite(project, type, ext) {
return withReservedFileSync(project, type, ext, ({ fullPath, localPath }) => {
writeFileSync(fullPath, "asset", { flag: "wx" });
return localPath;
});
}
test("a reservation refuses a linked .media before taking the lock", posixOnly, () =>
withSandbox(({ project, outside, outsideUnchanged }) => {
symlinkSync(outside, join(project, ".media"));
assert.throws(() => reserveAndWrite(project, "image", ".png"), /leads outside the project/);
outsideUnchanged();
}),
);
for (const [linked, type] of [
["images", "image"],
["audio", "sfx"],
["audio/sfx", "sfx"],
["video", "video"],
["luts", "lut"],
]) {
test(
`a reservation refuses a linked .media/${linked} before making anything in it`,
posixOnly,
() =>
withSandbox(({ project, outside, outsideUnchanged }) => {
plantLink(outside, join(project, ".media", linked));
assert.throws(() => reserveAndWrite(project, type, ".bin"), /leads outside the project/);
outsideUnchanged();
}),
);
}
test("appending a record refuses a linked type folder", posixOnly, () =>
withSandbox(({ project, outside, outsideUnchanged }) => {
plantLink(outside, join(project, ".media", "images"));
assert.throws(
() => appendRecord(project, { id: "image_001", type: "image", path: ".media/images/x.png" }),
/leads outside the project/,
);
outsideUnchanged();
}),
);
test("an id past exact integers never lands on a name the project already holds", posixOnly, () =>
withSandbox(({ project, outside, outsideUnchanged }) => {
const huge = "9007199254740992";
mkdirSync(join(project, ".media", "images"), { recursive: true });
writeFileSync(
join(project, ".media", "manifest.jsonl"),
`${JSON.stringify({ id: `image_${huge}`, type: "image", path: "x" })}\n`,
);
plantLink(join(outside, "planted.png"), join(project, ".media", "images", `image_${huge}.png`));
const source = join(project, "source.png");
writeFileSync(source, "png");
const localPath = withReservedFileSync(project, "image", ".png", ({ fullPath, localPath }) => {
freezeLocalFile(source, fullPath);
return localPath;
});
assert.equal(localPath, ".media/images/image_001.png");
assert.ok(lstatSync(join(project, localPath)).isFile());
outsideUnchanged();
}),
);
test("the asset writers refuse a link at their own name instead of following it", posixOnly, () =>
withSandbox(({ project, outside, outsideUnchanged }) => {
const source = join(project, "source");
writeFileSync(source, "<svg xmlns='http://www.w3.org/2000/svg'/>");
for (const ext of [".png", ".svg"]) {
const dest = join(project, `dest${ext}`);
symlinkSync(join(outside, `target${ext}`), dest);
assert.throws(() => freezeLocalFile(source, dest), /EEXIST/);
}
outsideUnchanged();
}),
);
test("a frozen LUT never writes through a link at its .tmp name", posixOnly, () =>
withSandbox(async ({ project, outside, outsideUnchanged }) => {
const huge = "9007199254740992";
mkdirSync(join(project, ".media", "luts"), { recursive: true });
writeFileSync(
join(project, ".media", "manifest.jsonl"),
`${JSON.stringify({ id: `lut_${huge}`, type: "lut", path: "x" })}\n`,
);
plantLink(
join(outside, "planted.cube"),
join(project, ".media", "luts", `lut_${huge}.cube.tmp`),
);
const match = matchColorLook("teal orange blockbuster");
const frozen = await freezeLibraryLut(match, {
projectDir: project,
type: "lut",
localOnly: true,
});
assert.equal(frozen.localPath, ".media/luts/lut_001.cube");
outsideUnchanged();
}),
);
test("a project preference refuses a linked .media and writes nothing", posixOnly, () =>
withSandbox(({ project, outside, outsideUnchanged }) => {
symlinkSync(outside, join(project, ".media"));
assert.throws(
() => recordPreference({ projectDir: project, key: "aspect", value: "16:9" }),
/leads outside the project/,
);
outsideUnchanged();
}),
);
test("a project preference never writes through links at predictable temp names", posixOnly, () =>
withSandbox(({ project, outside, outsideUnchanged }) => {
const prefs = projectPrefsPath(project);
mkdirSync(dirname(prefs), { recursive: true });
for (let pid = process.pid - 5; pid <= process.pid + 5; pid += 1) {
symlinkSync(join(outside, `planted-${pid}`), `${prefs}.${pid}.tmp`);
}
recordPreference({ projectDir: project, key: "aspect", value: "16:9" });
assert.ok(lstatSync(prefs).isFile());
assert.equal(JSON.parse(readFileSync(prefs, "utf8")).preferences.aspect.value, "16:9");
assert.equal(existsSync(join(outside, `planted-${process.pid}`)), false);
outsideUnchanged();
}),
);
@@ -251,7 +251,7 @@ export async function freezeLibraryLut(match, { projectDir, type, localOnly = fa
assertValidCubeText(cube, `invalid library LUT ${match.id}`);
// Write + validate at .tmp, then atomic rename — same no-orphan guarantee
// as the url path above.
writeFileSync(tmpPath, cube);
writeFileSync(tmpPath, cube, { flag: "wx" });
assertValidCubeFile(tmpPath, `invalid frozen LUT ${localPath}`);
renameSync(tmpPath, fullPath);
return libraryRecord(match, {
+36 -21
View File
@@ -74,21 +74,35 @@ export function readManifest(projectDir) {
}
/**
* The project's `.media` folder, made if missing. Throws when it is a link or resolves outside the project, since
* a project from someone else could carry such a link to send manifest and index writes elsewhere.
* The project's `.media` folder, or the `subdir` inside it, made one level at a time if missing. Throws when any
* level is a link or resolves outside the project, before anything is made inside it, since a project from someone
* else could carry such a link to send writes elsewhere.
*/
export function ownMediaDir(projectDir) {
const dir = mediaDir(projectDir);
mkdirSync(dir, { recursive: true });
if (
lstatSync(dir).isSymbolicLink() ||
realpathSync(dir) !== join(realpathSync(projectDir), ".media")
) {
throw new Error(`${dir} leads outside the project folder; nothing was written there`);
export function ownMediaDir(projectDir, subdir = "") {
mkdirSync(projectDir, { recursive: true });
let dir = mediaDir(projectDir);
let expected = join(realpathSync(projectDir), ".media");
ownFolder(dir, expected);
for (const part of subdir.split("/").filter(Boolean)) {
dir = join(dir, part);
expected = join(expected, part);
ownFolder(dir, expected);
}
return dir;
}
function ownFolder(dir, expected) {
try {
mkdirSync(dir);
} catch (error) {
if (error?.code !== "EEXIST") throw error;
}
const stats = lstatSync(dir);
if (stats.isSymbolicLink() || !stats.isDirectory() || realpathSync(dir) !== expected) {
throw new Error(`${dir} leads outside the project folder; nothing was written there`);
}
}
/** Throws when `path` is a link. */
export function refuseLink(path) {
if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {
@@ -110,9 +124,7 @@ export function replaceFile(path, content) {
}
export function appendRecord(projectDir, record) {
ownMediaDir(projectDir);
const typeDir = typeDirPath(projectDir, record.type);
mkdirSync(typeDir, { recursive: true });
ownMediaDir(projectDir, typeSubdir(record.type));
const p = manifestPath(projectDir);
refuseLink(p);
@@ -252,8 +264,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
@@ -263,9 +274,9 @@ 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 });
ownMediaDir(projectDir, typeSubdir(type));
return withMediaLock(projectDir, () => {
const id = nextFreeId(projectDir, type);
const id = nextFreeId(projectDir, type, ext);
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
// Same shape as core atomicTempPath: an empty file at the final name would be committed.
const markerPath = `${join(projectDir, localPath)}.hf${randomBytes(3).toString("hex")}.tmp`;
@@ -274,9 +285,10 @@ export function allocateId(projectDir, type, ext) {
});
}
// Call under the lock: counts recorded ids and ids reserved by a file not yet recorded.
function nextFreeId(projectDir, type) {
const re = new RegExp(`^${type}_(\\d+)`);
// Call under the lock: counts recorded ids and ids reserved by a file not yet recorded. Ids past nine digits are
// ignored, so a planted huge id can't push the count past exact integers, and a name already taken is skipped.
function nextFreeId(projectDir, type, ext) {
const re = new RegExp(`^${type}_(\\d{1,9})(?!\\d)`);
let max = 0;
for (const r of readManifest(projectDir)) {
if (r.type !== type) continue;
@@ -288,7 +300,10 @@ function nextFreeId(projectDir, type) {
const m = f.match(re);
if (m) max = Math.max(max, parseInt(m[1], 10));
}
return `${type}_${String(max + 1).padStart(3, "0")}`;
const idFor = (n) => `${type}_${String(n).padStart(3, "0")}`;
let next = max + 1;
while (lstatSync(join(typeDir, `${idFor(next)}${ext}`), { throwIfNoEntry: false })) next += 1;
return idFor(next);
}
function reservedFile(projectDir, type, ext) {
+5 -11
View File
@@ -1,8 +1,9 @@
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import * as fs from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { withFileLock } from "./config-lock.mjs";
import { globalMediaDir } from "./media-home.mjs";
import { ownMediaDir, replaceFile } from "./manifest.mjs";
/**
* Remembered defaults — the lightweight tier of HyperFrames user memory.
@@ -70,17 +71,9 @@ function readPrefsFile(path) {
}
}
/** Atomic write (tmp + rename) so a crash never leaves a torn file. */
/** Atomic write (a new temp file under a random name, then rename), so a crash never leaves a torn file. */
function writePrefsFile(path, file) {
const tmp = `${path}.${process.pid}.tmp`;
try {
writeFileSync(tmp, `${JSON.stringify(file, null, 2)}\n`);
renameSync(tmp, path);
} finally {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
replaceFile(path, `${JSON.stringify(file, null, 2)}\n`);
}
function updatePrefsFile(path, update) {
@@ -129,6 +122,7 @@ function dedupe(list) {
* provenance over (the old confirmations vouched for the old value).
*/
function recordProjectTier(projectDir, fullKey, value, projectName, now) {
ownMediaDir(projectDir);
return updatePrefsFile(projectPrefsPath(projectDir), (file) => {
const previous = file.preferences[fullKey];
const keepProvenance = validEntry(previous) && previous.value === value;
+1 -1
View File
@@ -657,7 +657,7 @@ function freezeGeneratedLut(
try {
// Write + validate at .tmp, then atomic rename, so a crash between write and
// validate can't leave an invalid .cube at the final path.
writeFileSync(tmpPath, buildCube(params));
writeFileSync(tmpPath, buildCube(params), { flag: "wx" });
const check = validateCubeFile(tmpPath);
if (!check.ok) throw new Error(check.error);
renameSync(tmpPath, fullPath);
+1 -1
View File
@@ -18,7 +18,7 @@
"files": 13
},
"media-use": {
"hash": "b036fbafc769d248",
"hash": "c163c42866c22486",
"files": 131
},
"remotion-to-hyperframes": {
+36 -21
View File
@@ -74,21 +74,35 @@ export function readManifest(projectDir) {
}
/**
* The project's `.media` folder, made if missing. Throws when it is a link or resolves outside the project, since
* a project from someone else could carry such a link to send manifest and index writes elsewhere.
* The project's `.media` folder, or the `subdir` inside it, made one level at a time if missing. Throws when any
* level is a link or resolves outside the project, before anything is made inside it, since a project from someone
* else could carry such a link to send writes elsewhere.
*/
export function ownMediaDir(projectDir) {
const dir = mediaDir(projectDir);
mkdirSync(dir, { recursive: true });
if (
lstatSync(dir).isSymbolicLink() ||
realpathSync(dir) !== join(realpathSync(projectDir), ".media")
) {
throw new Error(`${dir} leads outside the project folder; nothing was written there`);
export function ownMediaDir(projectDir, subdir = "") {
mkdirSync(projectDir, { recursive: true });
let dir = mediaDir(projectDir);
let expected = join(realpathSync(projectDir), ".media");
ownFolder(dir, expected);
for (const part of subdir.split("/").filter(Boolean)) {
dir = join(dir, part);
expected = join(expected, part);
ownFolder(dir, expected);
}
return dir;
}
function ownFolder(dir, expected) {
try {
mkdirSync(dir);
} catch (error) {
if (error?.code !== "EEXIST") throw error;
}
const stats = lstatSync(dir);
if (stats.isSymbolicLink() || !stats.isDirectory() || realpathSync(dir) !== expected) {
throw new Error(`${dir} leads outside the project folder; nothing was written there`);
}
}
/** Throws when `path` is a link. */
export function refuseLink(path) {
if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {
@@ -110,9 +124,7 @@ export function replaceFile(path, content) {
}
export function appendRecord(projectDir, record) {
ownMediaDir(projectDir);
const typeDir = typeDirPath(projectDir, record.type);
mkdirSync(typeDir, { recursive: true });
ownMediaDir(projectDir, typeSubdir(record.type));
const p = manifestPath(projectDir);
refuseLink(p);
@@ -252,8 +264,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
@@ -263,9 +274,9 @@ 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 });
ownMediaDir(projectDir, typeSubdir(type));
return withMediaLock(projectDir, () => {
const id = nextFreeId(projectDir, type);
const id = nextFreeId(projectDir, type, ext);
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
// Same shape as core atomicTempPath: an empty file at the final name would be committed.
const markerPath = `${join(projectDir, localPath)}.hf${randomBytes(3).toString("hex")}.tmp`;
@@ -274,9 +285,10 @@ export function allocateId(projectDir, type, ext) {
});
}
// Call under the lock: counts recorded ids and ids reserved by a file not yet recorded.
function nextFreeId(projectDir, type) {
const re = new RegExp(`^${type}_(\\d+)`);
// Call under the lock: counts recorded ids and ids reserved by a file not yet recorded. Ids past nine digits are
// ignored, so a planted huge id can't push the count past exact integers, and a name already taken is skipped.
function nextFreeId(projectDir, type, ext) {
const re = new RegExp(`^${type}_(\\d{1,9})(?!\\d)`);
let max = 0;
for (const r of readManifest(projectDir)) {
if (r.type !== type) continue;
@@ -288,7 +300,10 @@ function nextFreeId(projectDir, type) {
const m = f.match(re);
if (m) max = Math.max(max, parseInt(m[1], 10));
}
return `${type}_${String(max + 1).padStart(3, "0")}`;
const idFor = (n) => `${type}_${String(n).padStart(3, "0")}`;
let next = max + 1;
while (lstatSync(join(typeDir, `${idFor(next)}${ext}`), { throwIfNoEntry: false })) next += 1;
return idFor(next);
}
function reservedFile(projectDir, type, ext) {
+5 -11
View File
@@ -1,8 +1,9 @@
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import * as fs from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { withFileLock } from "./config-lock.mjs";
import { globalMediaDir } from "./media-home.mjs";
import { ownMediaDir, replaceFile } from "./manifest.mjs";
/**
* Remembered defaults — the lightweight tier of HyperFrames user memory.
@@ -70,17 +71,9 @@ function readPrefsFile(path) {
}
}
/** Atomic write (tmp + rename) so a crash never leaves a torn file. */
/** Atomic write (a new temp file under a random name, then rename), so a crash never leaves a torn file. */
function writePrefsFile(path, file) {
const tmp = `${path}.${process.pid}.tmp`;
try {
writeFileSync(tmp, `${JSON.stringify(file, null, 2)}\n`);
renameSync(tmp, path);
} finally {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
replaceFile(path, `${JSON.stringify(file, null, 2)}\n`);
}
function updatePrefsFile(path, update) {
@@ -129,6 +122,7 @@ function dedupe(list) {
* provenance over (the old confirmations vouched for the old value).
*/
function recordProjectTier(projectDir, fullKey, value, projectName, now) {
ownMediaDir(projectDir);
return updatePrefsFile(projectPrefsPath(projectDir), (file) => {
const previous = file.preferences[fullKey];
const keepProvenance = validEntry(previous) && previous.value === value;