Skip to content

Write HTML. Render video. Built for agents.

fix(studio-server): stamping ids at open never reverts a write that lands meanwhile (#4491)

Miguel Ángelb2a449df8e21
diff --git a/packages/studio-server/src/helpers/hfIdPersist.test.ts b/packages/studio-server/src/helpers/hfIdPersist.test.ts
index a5c8c8b6df..87a411b6af 100644
--- a/packages/studio-server/src/helpers/hfIdPersist.test.ts
+++ b/packages/studio-server/src/helpers/hfIdPersist.test.ts
@@ -1,13 +1,34 @@
-import { describe, it, expect, afterEach } from "vitest";
-import { mkdtempSync, writeFileSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { describe, it, expect, afterEach, vi } from "vitest";
+import {
+ existsSync,
+ mkdtempSync,
+ writeFileSync,
+ readFileSync,
+ readdirSync,
+ renameSync,
+ rmSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { stampFileHfIds } from "./hfIdPersist.js";
+const hooks = vi.hoisted(() => ({ minting: undefined as (() => void) | undefined }));
+vi.mock("@hyperframes/parsers/hf-ids", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@hyperframes/parsers/hf-ids")>();
+ return {
+ ...actual,
+ ensureHfIds: (html: string) => {
+ hooks.minting?.();
+ return actual.ensureHfIds(html);
+ },
+ };
+});
+
describe("stampFileHfIds", () => {
const tmpDirs: string[] = [];
afterEach(() => {
+ hooks.minting = undefined;
for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });
tmpDirs.length = 0;
});
@@ -20,7 +41,7 @@ describe("stampFileHfIds", () => {
return file;
}
- it("stamps ids and writes back through the same fd", () => {
+ it("stamps ids and writes them back to the file", () => {
const file = tmpFile(`<div class="clip" data-start="0" data-end="3">Hi</div>`);
const returned = stampFileHfIds(file);
expect(returned).toContain('data-hf-id="hf-');
@@ -36,6 +57,34 @@ describe("stampFileHfIds", () => {
expect(readdirSync(file.replace(/\/[^/]+$/, ""))).toEqual(["scene.html"]);
});
+ it.each([
+ ["in place", (file: string, html: string) => writeFileSync(file, html)],
+ [
+ "by rename",
+ (file: string, html: string) => {
+ writeFileSync(`${file}.tmp`, html);
+ renameSync(`${file}.tmp`, file);
+ },
+ ],
+ ])("keeps a write that lands %s while ids are minted", (_, write) => {
+ const file = tmpFile(`<div class="clip" data-start="0" data-end="3">Hi</div>`);
+ const agentWrite = `<div class="clip" data-start="0" data-end="5">Agent</div>`;
+ hooks.minting = () => write(file, agentWrite);
+
+ stampFileHfIds(file);
+
+ expect(readFileSync(file, "utf-8")).toBe(agentWrite);
+ });
+
+ it("leaves a file deleted while ids are minted deleted", () => {
+ const file = tmpFile(`<div class="clip" data-start="0" data-end="3">Hi</div>`);
+ hooks.minting = () => rmSync(file);
+
+ stampFileHfIds(file);
+
+ expect(existsSync(file)).toBe(false);
+ });
+
it("does not rewrite an already-stamped file", () => {
const file = tmpFile(`<div data-hf-id="hf-keep">Hi</div>`);
const before = readFileSync(file, "utf-8");
diff --git a/packages/studio-server/src/helpers/hfIdPersist.ts b/packages/studio-server/src/helpers/hfIdPersist.ts
index 5e0fc44ea9..29fb876e79 100644
--- a/packages/studio-server/src/helpers/hfIdPersist.ts
+++ b/packages/studio-server/src/helpers/hfIdPersist.ts
@@ -66,13 +66,21 @@ function openNoFollow(filePath: string, flags: number): number | null {
}
}
+function isUnchanged(filePath: string, expected: string): boolean {
+ const fd = openNoFollow(filePath, constants.O_RDONLY);
+ if (fd === null) return false;
+ try {
+ return readFileSync(fd, "utf-8") === expected;
+ } finally {
+ closeSync(fd);
+ }
+}
+
/**
* Read `filePath`, mint any missing `data-hf-id`s, write the stamped content
- * back if new ids were added, and return the stamped content — all through ONE
- * file descriptor. Unlike the check-path / read-path / write-path sequence a
- * route handler would otherwise do, the validation (fstat), read, and write
- * all target the same open inode, so the path cannot be swapped (e.g. for a
- * symlink) between validation and write (CodeQL js/file-system-race).
+ * back if new ids were added, and return the stamped content. Every open of the path is
+ * no-follow (POSIX) and the write renames a sibling temp file over it, so a symlink swapped
+ * in at the path is never read or written through (CodeQL js/file-system-race).
*
* Falls back to read-only stamping when the file isn't writable (read-only
* fs, sandbox) — serving stamped content without persisting is still correct;
@@ -80,8 +88,8 @@ function openNoFollow(filePath: string, flags: number): number | null {
*
* Returns null when the file is missing, unreadable, or not a regular file.
*
- * Best-effort on concurrent saves: a user save landing between the read and
- * the write below can still be overwritten — the next save simply re-persists.
+ * A write that lands while ids are minted is kept: the file is replaced only if
+ * it still holds the bytes that were stamped, else it is left for the next open or save.
*/
export function stampFileHfIds(filePath: string): string | null {
let fd: number | null = openNoFollow(filePath, constants.O_RDWR);
@@ -103,7 +111,7 @@ export function stampFileHfIds(filePath: string): string | null {
const mode = fstatSync(fd).mode;
closeSync(fd);
fd = null;
- replaceFileAtomically(filePath, normalized, mode);
+ if (isUnchanged(filePath, html)) replaceFileAtomically(filePath, normalized, mode);
}
return normalized;
} catch (err) {
diff --git a/packages/studio-server/src/helpers/safePath.test.ts b/packages/studio-server/src/helpers/safePath.test.ts
index 9cefec8f34..6afbea122a 100644
--- a/packages/studio-server/src/helpers/safePath.test.ts
+++ b/packages/studio-server/src/helpers/safePath.test.ts
@@ -1,12 +1,27 @@
+// @vitest-environment node
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { walkDir } from "./safePath";
+const hooks = vi.hoisted(() => ({ unreadable: new Map<string, string>() }));
+vi.mock("node:fs", async (importOriginal) => {
+ const fs = await importOriginal<typeof import("node:fs")>();
+ return {
+ ...fs,
+ readdirSync: ((dir: string, ...rest: unknown[]) => {
+ const code = hooks.unreadable.get(dir);
+ if (code) throw Object.assign(new Error(`${code}: ${dir}`), { code });
+ return (fs.readdirSync as (...args: unknown[]) => unknown)(dir, ...rest);
+ }) as typeof fs.readdirSync,
+ };
+});
+
const tempDirs: string[] = [];
afterEach(() => {
+ hooks.unreadable.clear();
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
@@ -36,4 +51,34 @@ describe("walkDir", () => {
expect(files).toContain("compositions/scene.html");
expect(files).not.toContain(".hyperframes/backup/snapshot.html");
});
+
+ it.each(["EACCES", "EPERM", "ENOENT", "ENOTDIR"])(
+ "skips a subfolder whose listing fails with %s",
+ (code) => {
+ const projectDir = createProjectDir();
+ mkdirSync(join(projectDir, "locked"));
+ mkdirSync(join(projectDir, "compositions"));
+ writeFileSync(join(projectDir, "locked", "hidden.html"), "hidden");
+ writeFileSync(join(projectDir, "compositions", "scene.html"), "scene");
+ writeFileSync(join(projectDir, "index.html"), "root");
+ hooks.unreadable.set(join(projectDir, "locked"), code);
+
+ expect(walkDir(projectDir).sort()).toEqual(["compositions/scene.html", "index.html"]);
+ },
+ );
+
+ it("still throws when a subfolder fails for another reason", () => {
+ const projectDir = createProjectDir();
+ mkdirSync(join(projectDir, "busy"));
+ hooks.unreadable.set(join(projectDir, "busy"), "EMFILE");
+
+ expect(() => walkDir(projectDir)).toThrow("EMFILE");
+ });
+
+ it("still throws when the project folder itself cannot be listed", () => {
+ const projectDir = createProjectDir();
+ hooks.unreadable.set(projectDir, "EACCES");
+
+ expect(() => walkDir(projectDir)).toThrow("EACCES");
+ });
});
diff --git a/packages/studio-server/src/helpers/safePath.ts b/packages/studio-server/src/helpers/safePath.ts
index cc7ff8855a..1715c40ccb 100644
--- a/packages/studio-server/src/helpers/safePath.ts
+++ b/packages/studio-server/src/helpers/safePath.ts
@@ -1,5 +1,5 @@
import { join } from "node:path";
-import { readdirSync } from "node:fs";
+import { readdirSync, type Dirent } from "node:fs";
// `isSafePath` lives at the package root so non-studio-api layers (compiler,
// CLI, engine) can share it without a backwards dependency on studio-api.
@@ -30,10 +30,21 @@ export function isInHiddenOrVendorDir(relPath: string): boolean {
return segments.slice(0, -1).some((seg) => seg.startsWith(".") || seg === "node_modules");
}
-/** Recursively walk a directory and return relative file paths. */
+const UNREADABLE_DIR_CODES = new Set(["EACCES", "EPERM", "ENOENT", "ENOTDIR"]);
+
+/** Recursively walk a directory and return relative file paths. A subfolder that is unreadable
+ * or removed mid-walk is skipped; any other failure, or an unreadable `dir` itself, throws. */
export function walkDir(dir: string, prefix = ""): string[] {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (!prefix || !code || !UNREADABLE_DIR_CODES.has(code)) throw err;
+ return [];
+ }
const files: string[] = [];
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ for (const entry of entries) {
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
if (IGNORE_DIRS.has(entry.name) || shouldIgnoreDir(rel)) continue;
if (entry.isDirectory()) {