Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(cli): replace pre-planted links when writing capture files (#4298)
Leonel Rivas42eb6e9ad2ca
diff --git a/packages/cli/src/capture/captureFile.test.ts b/packages/cli/src/capture/captureFile.test.tsnew file mode 100644index 0000000000..fb83b61763--- /dev/null+++ b/packages/cli/src/capture/captureFile.test.ts@@ -0,0 +1,124 @@+import {+ linkSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { writeCaptureFileSync } from "./captureFile.js";++const temporaryDirectories: string[] = [];++afterEach(() => {+ for (const directory of temporaryDirectories.splice(0))+ rmSync(directory, { recursive: true, force: true });+});++function scratch(): { outputDir: string; victim: string } {+ const root = mkdtempSync(join(tmpdir(), "hyperframes-capture-file-"));+ temporaryDirectories.push(root);+ const outputDir = join(root, "capture");+ mkdirSync(outputDir);+ const victim = join(root, "victim.txt");+ writeFileSync(victim, "do not touch");+ return { outputDir, victim };+}++// Creating symlinks needs elevated rights on Windows, and POSIX modes don't apply there.+const posixOnly = it.skipIf(process.platform === "win32");++describe("writeCaptureFileSync", () => {+ posixOnly("replaces a pre-planted symlink instead of writing through it", () => {+ const { outputDir, victim } = scratch();+ const target = join(outputDir, "page.html");+ symlinkSync(victim, target);++ writeCaptureFileSync(target, "<html></html>", "utf-8");++ expect(readFileSync(victim, "utf8")).toBe("do not touch");+ expect(readFileSync(target, "utf8")).toBe("<html></html>");+ expect(lstatSync(target).isSymbolicLink()).toBe(false);+ });++ it("replaces a pre-planted hard link instead of truncating the shared file", () => {+ const { outputDir, victim } = scratch();+ const target = join(outputDir, "tokens.json");+ linkSync(victim, target);++ writeCaptureFileSync(target, "{}");++ expect(readFileSync(victim, "utf8")).toBe("do not touch");+ expect(readFileSync(target, "utf8")).toBe("{}");+ });++ it("still overwrites a capture file written earlier in the run", () => {+ const { outputDir } = scratch();+ const target = join(outputDir, "page.html");+ writeCaptureFileSync(target, "first attempt");++ writeCaptureFileSync(target, "partial bundle");++ expect(readFileSync(target, "utf8")).toBe("partial bundle");+ });++ posixOnly("creates the file readable by the owner only", () => {+ const { outputDir } = scratch();+ const target = join(outputDir, "meta.json");++ writeCaptureFileSync(target, "{}");++ expect(lstatSync(target).mode & 0o777).toBe(0o600);+ });++ it("keeps a caller's exclusive-create flag", () => {+ const { outputDir } = scratch();+ const target = join(outputDir, "meta.json");+ writeCaptureFileSync(target, "real meta");++ expect(() => writeCaptureFileSync(target, "partial meta", { flag: "wx" })).toThrow(+ expect.objectContaining({ code: "EEXIST" }),+ );+ expect(readFileSync(target, "utf8")).toBe("real meta");+ });++ posixOnly("refuses a pre-planted symlink under a caller's exclusive-create flag", () => {+ const { outputDir, victim } = scratch();+ const target = join(outputDir, "meta.json");+ symlinkSync(victim, target);++ expect(() => writeCaptureFileSync(target, "partial meta", { flag: "wx" })).toThrow(+ expect.objectContaining({ code: "EEXIST" }),+ );+ expect(readFileSync(victim, "utf8")).toBe("do not touch");+ });++ it("cleans up only what it created, even when the final rename fails", () => {+ const { outputDir } = scratch();+ const neighbour = join(outputDir, ".capture-keep");+ writeFileSync(neighbour, "someone else's file");+ mkdirSync(join(outputDir, "occupied"));++ writeCaptureFileSync(join(outputDir, "a.txt"), "a");+ expect(() => writeCaptureFileSync(join(outputDir, "occupied"), "b")).toThrow();++ expect(readFileSync(neighbour, "utf8")).toBe("someone else's file");+ expect(readdirSync(outputDir).sort()).toEqual([".capture-keep", "a.txt", "occupied"]);+ });++ it("leaves no temporary file behind, even when the final rename fails", () => {+ const { outputDir } = scratch();+ writeCaptureFileSync(join(outputDir, "a.txt"), "a");+ mkdirSync(join(outputDir, "occupied"));++ expect(() => writeCaptureFileSync(join(outputDir, "occupied"), "b")).toThrow();++ expect(readdirSync(outputDir).sort()).toEqual(["a.txt", "occupied"]);+ });+});diff --git a/packages/cli/src/capture/captureFile.ts b/packages/cli/src/capture/captureFile.tsindex 185269c249..a1128d53ce 100644--- a/packages/cli/src/capture/captureFile.ts+++ b/packages/cli/src/capture/captureFile.ts@@ -1,10 +1,42 @@-import { writeFileSync } from "node:fs";+import { mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { basename, dirname, join } from "node:path";+type WriteOptions = Parameters<typeof writeFileSync>[2];++// Writes are staged in a private directory next to the target and renamed over+// it, the same publication pattern as the producer's font cache (#3669).+// `rename` replaces the directory entry itself, so a symlink or hard link+// pre-planted at the target is swapped out instead of written through, while+// intentional overwrites (the deadline partial bundle rewriting files from the+// in-progress attempt) keep working. The staging directory is created fresh by+// this call, so nothing in it can be pre-planted and cleanup only ever removes+// what this call made.+function publishCaptureFileSync(+ path: string,+ data: string | NodeJS.ArrayBufferView,+ options: Exclude<WriteOptions, string>,+): void {+ const stagingDir = mkdtempSync(join(dirname(path), ".capture-"));+ try {+ const staged = join(stagingDir, basename(path));+ writeCaptureFileSync(staged, data, { ...options, flag: "wx" });+ renameSync(staged, path);+ } finally {+ rmSync(stagingDir, { recursive: true, force: true });+ }+}++// A caller that passes its own flag keeps those semantics. Exclusive create+// (`wx`) is already safe on its own: O_EXCL refuses anything at the target,+// symlinks included.export function writeCaptureFileSync(path: string,data: string | NodeJS.ArrayBufferView,- options?: Parameters<typeof writeFileSync>[2],+ options?: WriteOptions,): void {const normalized = typeof options === "string" ? { encoding: options } : options;+ if (normalized?.flag === undefined || normalized.flag === "w") {+ return publishCaptureFileSync(path, data, normalized);+ }writeFileSync(path, data, { ...normalized, mode: 0o600 });}diff --git a/packages/cli/src/capture/contactSheet.test.ts b/packages/cli/src/capture/contactSheet.test.tsindex 03cae017b8..9833edf2e8 100644--- a/packages/cli/src/capture/contactSheet.test.ts+++ b/packages/cli/src/capture/contactSheet.test.ts@@ -1,4 +1,12 @@-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import {+ existsSync,+ lstatSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import sharp from "sharp";@@ -67,6 +75,34 @@ describe("createContactSheet", () => {rmSync(dir, { recursive: true, force: true });}}, 60_000);++ it.skipIf(process.platform === "win32")(+ "replaces a pre-planted symlink at the sheet path instead of writing through it",+ async () => {+ const dir = tempDir();+ try {+ const image = join(dir, "a.png");+ const victim = join(dir, "victim.txt");+ const out = join(dir, "contact-sheet.jpg");+ await sharp({+ create: { width: 16, height: 9, channels: 3, background: { r: 255, g: 0, b: 0 } },+ })+ .png()+ .toFile(image);+ writeFileSync(victim, "do not touch");+ symlinkSync(victim, out);++ await createContactSheet([image], out, { cellWidth: 16, maxImages: 1 });++ expect(readFileSync(victim, "utf8")).toBe("do not touch");+ await expect(sharp(out).metadata()).resolves.toMatchObject({ format: "jpeg" });+ expect(lstatSync(out).isSymbolicLink()).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ 60_000,+ );});describe("contact-sheet capture budget", () => {diff --git a/packages/cli/src/capture/contactSheet.ts b/packages/cli/src/capture/contactSheet.tsindex bd58f89499..69e2180bd8 100644--- a/packages/cli/src/capture/contactSheet.ts+++ b/packages/cli/src/capture/contactSheet.ts@@ -107,11 +107,13 @@ export async function createContactSheet(},}).composite(overlays);- if (extname(outputPath).toLowerCase() === ".png") {- await sheet.png().toFile(outputPath);- } else {- await sheet.jpeg({ quality }).toFile(outputPath);- }+ // Encode to a buffer and write through the capture writer rather than+ // `toFile`, which opens the path itself and would follow a planted link.+ const encoded =+ extname(outputPath).toLowerCase() === ".png"+ ? await sheet.png().toBuffer()+ : await sheet.jpeg({ quality }).toBuffer();+ writeCaptureFileSync(outputPath, encoded);return outputPath;}diff --git a/packages/cli/src/capture/mediaCapture.test.ts b/packages/cli/src/capture/mediaCapture.test.tsindex b866370759..3307763f12 100644--- a/packages/cli/src/capture/mediaCapture.test.ts+++ b/packages/cli/src/capture/mediaCapture.test.ts@@ -1,10 +1,12 @@import {existsSync,+ lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,+ symlinkSync,writeFileSync,} from "node:fs";import { tmpdir } from "node:os";@@ -218,3 +220,82 @@ describe("Lottie capture rejects unsafe persistence", () => {expect(readdirSync(dir)).toEqual([]);});});++describe("media previews replace pre-planted links", () => {+ const PNG = Buffer.from("\x89PNG preview");++ it.skipIf(process.platform === "win32")(+ "writes a Lottie preview without following a pre-planted symlink",+ async () => {+ const dir = tempDir();+ const lottieDir = join(dir, "assets", "lottie");+ const previewPath = join(lottieDir, "previews", "logo-preview.png");+ const victim = join(dir, "victim.txt");+ mkdirSync(join(dir, "extracted"), { recursive: true });+ mkdirSync(join(lottieDir, "previews"), { recursive: true });+ writeFileSync(+ join(lottieDir, "logo.json"),+ JSON.stringify({ w: 100, h: 100, fr: 30, ip: 0, op: 30, layers: [] }),+ );+ writeFileSync(victim, "do not touch");+ symlinkSync(victim, previewPath);+ const previewPage = {+ setRequestInterception: vi.fn(async () => undefined),+ on: vi.fn(),+ setViewport: vi.fn(async () => undefined),+ setContent: vi.fn(async () => undefined),+ evaluate: vi.fn(async () => undefined),+ waitForFunction: vi.fn(async () => undefined),+ screenshot: vi.fn(async () => PNG),+ close: vi.fn(async () => undefined),+ };+ const browser = { newPage: vi.fn(async () => previewPage) } as unknown as Browser;++ await renderLottiePreviews(browser, lottieDir, dir);++ expect(readFileSync(victim, "utf8")).toBe("do not touch");+ expect(readFileSync(previewPath)).toEqual(PNG);+ expect(lstatSync(previewPath).isSymbolicLink()).toBe(false);+ },+ );++ it.skipIf(process.platform === "win32")(+ "writes a video preview without following a pre-planted symlink",+ async () => {+ const dir = tempDir();+ const previewPath = join(dir, "assets", "videos", "previews", "video-0-preview.png");+ const victim = join(dir, "victim.txt");+ mkdirSync(join(dir, "extracted"), { recursive: true });+ mkdirSync(join(dir, "assets", "videos", "previews"), { recursive: true });+ writeFileSync(victim, "do not touch");+ symlinkSync(victim, previewPath);+ const descriptor = {+ src: "https://video.example/hero.mp4",+ filename: "hero.mp4",+ width: 640,+ height: 360,+ sourceWidth: 640,+ sourceHeight: 360,+ top: 0,+ left: 0,+ heading: "Hero",+ caption: "Demo",+ ariaLabel: "",+ };+ const evaluate = vi.fn(async (expression: unknown) =>+ typeof expression === "function" ? { x: 0, y: 0, width: 640, height: 360 } : [descriptor],+ );+ const page = { evaluate, screenshot: vi.fn(async () => PNG) } as unknown as Page;+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(null, { status: 404 })),+ );++ await captureVideoManifest(page, dir, () => {});++ expect(readFileSync(victim, "utf8")).toBe("do not touch");+ expect(readFileSync(previewPath)).toEqual(PNG);+ expect(lstatSync(previewPath).isSymbolicLink()).toBe(false);+ },+ );+});diff --git a/packages/cli/src/capture/mediaCapture.ts b/packages/cli/src/capture/mediaCapture.tsindex b9122f2e52..bf178b86df 100644--- a/packages/cli/src/capture/mediaCapture.ts+++ b/packages/cli/src/capture/mediaCapture.ts@@ -187,11 +187,8 @@ export async function renderLottiePreviews(.waitForFunction(() => (window as any).__READY === true, { timeout: 5000 }).catch(() => {});if (liveRemainingMs(budget, 1) > 0) {- await previewPage.screenshot({- path: join(previewDir, previewName),- type: "png",- omitBackground: true,- });+ const shot = await previewPage.screenshot({ type: "png", omitBackground: true });+ writeCaptureFileSync(join(previewDir, previewName), shot);preview = `assets/lottie/previews/${previewName}`;}} catch {@@ -523,8 +520,8 @@ export async function captureVideoManifest(if (rect && rect.width >= 10) {await new Promise((r) => setTimeout(r, 200)); // let decoder settleif (liveRemainingMs(opts ?? {}, 1) > 0) {- await page.screenshot({- path: join(previewDir, previewName),+ const shot = await page.screenshot({+ type: "png",clip: {x: Math.max(0, rect.x),y: Math.max(0, rect.y),@@ -532,6 +529,7 @@ export async function captureVideoManifest(height: Math.min(rect.height, 1080),},});+ writeCaptureFileSync(join(previewDir, previewName), shot);preview = `assets/videos/previews/${previewName}`;}}diff --git a/packages/cli/src/commands/capture.test.ts b/packages/cli/src/commands/capture.test.tsindex 7bf7fbbba7..c0ff7ee6e3 100644--- a/packages/cli/src/commands/capture.test.ts+++ b/packages/cli/src/commands/capture.test.ts@@ -1,5 +1,13 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { mkdtempSync, rmSync } 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 { CliRuntimeError } from "../utils/commandResult.js";@@ -218,4 +226,33 @@ describe("capture command — vision control", () => {rmSync(dir, { recursive: true, force: true });}});++ it.skipIf(process.platform === "win32")(+ "writes BLOCKED.md without following a pre-planted symlink",+ async () => {+ const root = mkdtempSync(join(tmpdir(), "hf-capture-blocked-"));+ const dir = join(root, "capture");+ const victim = join(root, "victim.txt");+ mkdirSync(dir);+ writeFileSync(victim, "do not touch");+ symlinkSync(victim, join(dir, "BLOCKED.md"));+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});+ captureWebsiteMock.mockRejectedValueOnce(new Error("blocked by the site"));++ try {+ await expect(+ captureCommand.run!({+ args: { url: "https://example.com", output: dir, json: true },+ } as never),+ ).rejects.toBeInstanceOf(CliRuntimeError);++ expect(readFileSync(victim, "utf8")).toBe("do not touch");+ expect(readFileSync(join(dir, "BLOCKED.md"), "utf8")).toContain("# Capture Failed");+ expect(lstatSync(join(dir, "BLOCKED.md")).isSymbolicLink()).toBe(false);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ },+ );});diff --git a/packages/cli/src/commands/capture.ts b/packages/cli/src/commands/capture.tsindex 94c8d1702e..e7740e0449 100644--- a/packages/cli/src/commands/capture.ts+++ b/packages/cli/src/commands/capture.ts@@ -269,11 +269,12 @@ export default defineCommand({} catch (err) {const errMsg = normalizeErrorMessage(err);try {- const { mkdirSync, writeFileSync } = await import("node:fs");+ const { mkdirSync } = await import("node:fs");const { formatCaptureFailureReason } = await import("../capture/captureTimeout.js");+ const { writeCaptureFileSync } = await import("../capture/captureFile.js");mkdirSync(outputDir, { recursive: true });const reason = formatCaptureFailureReason(errMsg);- writeFileSync(+ writeCaptureFileSync(`${outputDir}/BLOCKED.md`,`# Capture Failed\n\n${reason}\n\nURL: ${url}\n\n## What to try\n\n- Re-run with a longer timeout: \`--timeout 60000\`\n- The site may block headless browsers (anti-bot protection)\n- Try capturing a different page on the same domain\n`,"utf-8",