Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(render): serve engine and producer files through checked descriptors (#3725)
James Russobe86a1ec7d5c
diff --git a/packages/engine/src/services/fileServer.file-race.test.ts b/packages/engine/src/services/fileServer.file-race.test.tsnew file mode 100644index 0000000000..c934e2292e--- /dev/null+++ b/packages/engine/src/services/fileServer.file-race.test.ts@@ -0,0 +1,212 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as fs from "node:fs";+import { execFileSync } from "node:child_process";+import { createServer } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createFileServer, type FileServerHandle } from "./fileServer.js";++const hooks = vi.hoisted(() => ({+ checked: (_path: fs.PathLike) => {},+ beforeRead: () => {},+ opened: new Map<number, fs.PathLike>(),+ active: new Set<number>(),+}));++vi.mock("node:fs", async (importOriginal) => {+ const actual = await importOriginal<typeof fs>();+ return {+ ...actual,+ openSync: (path: fs.PathLike, flags: number | string) => {+ const fd = actual.openSync(path, flags);+ hooks.opened.set(fd, path);+ hooks.active.add(fd);+ return fd;+ },+ closeSync: (fd: number) => {+ actual.closeSync(fd);+ hooks.active.delete(fd);+ },+ statSync: (path: fs.PathLike) => {+ const stat = actual.statSync(path);+ hooks.checked(path);+ return stat;+ },+ fstatSync: (fd: number) => {+ const stat = actual.fstatSync(fd);+ const path = hooks.opened.get(fd);+ if (path) hooks.checked(path);+ return stat;+ },+ readFileSync: (path: fs.PathOrFileDescriptor, encoding?: BufferEncoding) => {+ hooks.beforeRead();+ return encoding ? actual.readFileSync(path, encoding) : actual.readFileSync(path);+ },+ };+});++describe("file server checked reads", () => {+ let root: string;+ let projectDir: string;+ let compiledDir: string;+ let server: FileServerHandle | undefined;++ beforeEach(() => {+ root = fs.mkdtempSync(join(tmpdir(), "hf-server-read-"));+ projectDir = join(root, "project");+ compiledDir = join(root, "compiled");+ fs.mkdirSync(projectDir);+ fs.mkdirSync(compiledDir);+ hooks.opened.clear();+ hooks.active.clear();+ });++ afterEach(() => {+ server?.close();+ server = undefined;+ hooks.checked = () => {};+ hooks.beforeRead = () => {};+ vi.restoreAllMocks();+ fs.rmSync(root, { recursive: true, force: true });+ });++ function expectClosed() {+ // HTTP sockets can reuse an already-closed fd before fetch resolves.+ // Track successful real closes instead of probing stale descriptor numbers.+ expect(hooks.opened.size).toBeGreaterThan(0);+ expect(hooks.active.size).toBe(0);+ }++ it.each([+ ["project", "html"],+ ["project", "bin"],+ ["compiled", "html"],+ ["compiled", "bin"],+ ])("reads the checked %s .%s despite replacement", async (source, ext) => {+ const name = `asset.${ext}`;+ const file = join(source === "compiled" ? compiledDir : projectDir, name);+ fs.writeFileSync(join(projectDir, name), "project bytes");+ fs.writeFileSync(file, "checked bytes");+ hooks.checked = (path) => {+ if (path !== file) return;+ hooks.checked = () => {};+ fs.renameSync(file, join(root, "original"));+ fs.writeFileSync(file, "replacement bytes");+ };+ server = await createFileServer({ projectDir, compiledDir });+ const response = await fetch(`${server.url}/${name}`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("checked bytes");+ expectClosed();+ });++ it.each(["missing", "directory", "non-directory parent"])(+ "falls back from a compiled %s",+ async (kind) => {+ fs.mkdirSync(join(projectDir, "assets"));+ fs.writeFileSync(join(projectDir, "assets", "file.bin"), "project bytes");+ if (kind === "directory")+ fs.mkdirSync(join(compiledDir, "assets", "file.bin"), { recursive: true });+ if (kind === "non-directory parent") fs.writeFileSync(join(compiledDir, "assets"), "blocker");+ server = await createFileServer({ projectDir, compiledDir });+ const response = await fetch(`${server.url}/assets/file.bin`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("project bytes");+ expectClosed();+ },+ );++ it.skipIf(process.platform === "win32")("skips a compiled FIFO without blocking", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "project bytes");+ execFileSync("mkfifo", [join(compiledDir, "file.bin")]);+ server = await createFileServer({ projectDir, compiledDir });+ const response = await fetch(`${server.url}/file.bin`);+ expect(await response.text()).toBe("project bytes");+ expectClosed();+ });++ it.skipIf(process.platform === "win32")("falls back from a compiled Unix socket", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "project bytes");+ const socket = createServer();+ await new Promise<void>((resolve) => socket.listen(join(compiledDir, "file.bin"), resolve));+ try {+ server = await createFileServer({ projectDir, compiledDir });+ const response = await fetch(`${server.url}/file.bin`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("project bytes");+ expectClosed();+ } finally {+ await new Promise<void>((resolve, reject) =>+ socket.close((error) => (error ? reject(error) : resolve())),+ );+ }+ });++ it("serves an empty compiled file instead of falling back", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "project bytes");+ fs.writeFileSync(join(compiledDir, "file.bin"), "");+ server = await createFileServer({ projectDir, compiledDir });+ const response = await fetch(`${server.url}/file.bin`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("");+ expectClosed();+ });++ it("continues serving symlinked assets", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "project bytes");+ fs.symlinkSync(+ projectDir,+ join(compiledDir, "assets"),+ process.platform === "win32" ? "junction" : "dir",+ );+ server = await createFileServer({ projectDir, compiledDir });+ const response = await fetch(`${server.url}/assets/file.bin`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("project bytes");+ expectClosed();+ });++ it("keeps missing files and directories at 404", async () => {+ fs.mkdirSync(join(projectDir, "folder"));+ server = await createFileServer({ projectDir });+ for (const path of ["missing", "folder", "missing/child"]) {+ const response = await fetch(`${server.url}/${path}`);+ expect(response.status).toBe(404);+ expect(await response.text()).toBe("Not found");+ }+ });++ it("injects scripts only into the selected index HTML", async () => {+ const html = "<html><head></head><body>compiled</body></html>";+ fs.writeFileSync(join(projectDir, "index.html"), "project");+ fs.writeFileSync(join(compiledDir, "index.html"), html);+ fs.writeFileSync(join(compiledDir, "other.html"), html);+ server = await createFileServer({+ projectDir,+ compiledDir,+ headScripts: ["window.headTest = 1;"],+ bodyScripts: ["window.bodyTest = 1;"],+ });+ const response = await fetch(server.url);+ expect(response.headers.get("content-type")).toBe("text/html; charset=utf-8");+ const text = await response.text();+ expect(text).toContain("compiled");+ expect(text).toContain("window.headTest = 1;");+ expect(text).toContain("window.bodyTest = 1;");+ expect(await (await fetch(`${server.url}/other.html`)).text()).toBe(html);+ expectClosed();+ });++ it.each(["stat", "read"])("closes the selected file when %s fails", async (step) => {+ fs.writeFileSync(join(projectDir, "file.bin"), "bytes");+ const fail = () => {+ throw new Error("Injected failure");+ };+ if (step === "stat") hooks.checked = fail;+ else hooks.beforeRead = fail;+ vi.spyOn(console, "error").mockImplementation(() => {});+ server = await createFileServer({ projectDir });+ expect((await fetch(`${server.url}/file.bin`)).status).toBe(500);+ expectClosed();+ });+});diff --git a/packages/engine/src/services/fileServer.ts b/packages/engine/src/services/fileServer.tsindex f3e8cdc61a..04b4a62fe2 100644--- a/packages/engine/src/services/fileServer.ts+++ b/packages/engine/src/services/fileServer.ts@@ -8,7 +8,7 @@import { Hono } from "hono";import { serve } from "@hono/node-server";-import { readFileSync, existsSync, statSync } from "node:fs";+import { readFileSync, openSync, fstatSync, closeSync, statSync, constants } from "node:fs";import { join, extname } from "node:path";import { injectScriptsIntoHtml } from "@hyperframes/core/compiler";@@ -59,6 +59,31 @@ export interface FileServerHandle {close: () => void;}+function readRegularFile(filePath: string): Buffer<ArrayBuffer> | null {+ let fd: number;+ try {+ // Do not block on a named pipe before fstat can reject non-regular files.+ fd = openSync(filePath, constants.O_RDONLY | constants.O_NONBLOCK);+ } catch (error) {+ if (+ error instanceof Error &&+ "code" in error &&+ (error.code === "ENOENT" || error.code === "ENOTDIR")+ )+ return null;+ // Platforms report different open errors for directories and sockets.+ // This check only classifies a failed open; no read follows it.+ if (!statSync(filePath, { throwIfNoEntry: false })?.isFile()) return null;+ throw error;+ }+ try {+ if (!fstatSync(fd).isFile()) return null;+ return readFileSync(fd);+ } finally {+ closeSync(fd);+ }+}+export function createFileServer(options: FileServerOptions): Promise<FileServerHandle> {const { projectDir, compiledDir, port = 0, stripEmbeddedRuntime = true } = options;@@ -74,20 +99,16 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer// Remove leading slashconst relativePath = requestPath.replace(/^\//, "");const compiledPath = compiledDir ? join(compiledDir, relativePath) : null;- const hasCompiledFile = Boolean(- compiledPath && existsSync(compiledPath) && statSync(compiledPath).isFile(),- );- const filePath = hasCompiledFile ? (compiledPath as string) : join(projectDir, relativePath);-- if (!existsSync(filePath) || !statSync(filePath).isFile()) {- return c.text("Not found", 404);- }+ const content =+ (compiledPath ? readRegularFile(compiledPath) : null) ??+ readRegularFile(join(projectDir, relativePath));+ if (content === null) return c.text("Not found", 404);- const ext = extname(filePath).toLowerCase();+ const ext = extname(relativePath).toLowerCase();const contentType = MIME_TYPES[ext] || "application/octet-stream";if (ext === ".html") {- const rawHtml = readFileSync(filePath, "utf-8");+ const rawHtml = content.toString("utf-8");const html =relativePath === "index.html"? injectScriptsIntoHtml(rawHtml, headScripts, bodyScripts, stripEmbeddedRuntime)@@ -95,7 +116,6 @@ export function createFileServer(options: FileServerOptions): Promise<FileServerreturn c.text(html, 200, { "Content-Type": contentType });}- const content = readFileSync(filePath);return new Response(content, {status: 200,headers: { "Content-Type": contentType },diff --git a/packages/producer/scripts/test-classification.mjs b/packages/producer/scripts/test-classification.mjsindex a582c40380..717cb2d492 100644--- a/packages/producer/scripts/test-classification.mjs+++ b/packages/producer/scripts/test-classification.mjs@@ -19,6 +19,7 @@ const INTEGRATION_TEST_FILES = new Set(["src/services/distributed/planSizeCap.test.ts","src/services/distributed/renderChunk.test.ts","src/services/fileServer.test.ts",+ "src/services/fileServer.file-race.test.ts","src/services/healthWorker.test.ts","src/services/assetMediaType.test.ts","src/services/htmlCompiler.mediaType.test.ts",diff --git a/packages/producer/src/services/fileServer.file-race.test.ts b/packages/producer/src/services/fileServer.file-race.test.tsnew file mode 100644index 0000000000..9d9f44538d--- /dev/null+++ b/packages/producer/src/services/fileServer.file-race.test.ts@@ -0,0 +1,334 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as fs from "node:fs";+import { execFileSync } from "node:child_process";+import { createServer } from "node:net";+import { Readable } from "node:stream";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createFileServer, type FileServerHandle } from "./fileServer.js";++const hooks = vi.hoisted(() => ({+ checked: (_path: fs.PathLike) => {},+ beforeRead: () => {},+ opened: new Map<number, fs.PathLike>(),+ active: new Set<number>(),+ failStream: false,+ failCreation: false,+ streams: new Array<fs.ReadStream>(),+}));++vi.mock("node:fs", async (importOriginal) => {+ const actual = await importOriginal<typeof fs>();+ return {+ ...actual,+ openSync: (path: fs.PathLike, flags: number | string) => {+ const fd = actual.openSync(path, flags);+ hooks.opened.set(fd, path);+ hooks.active.add(fd);+ return fd;+ },+ closeSync: (fd: number) => {+ actual.closeSync(fd);+ hooks.active.delete(fd);+ },+ statSync: (path: fs.PathLike) => {+ const stat = actual.statSync(path);+ hooks.checked(path);+ return stat;+ },+ fstatSync: (fd: number) => {+ const stat = actual.fstatSync(fd);+ const path = hooks.opened.get(fd);+ if (path) hooks.checked(path);+ return stat;+ },+ readFile: (+ path: fs.PathOrFileDescriptor,+ encoding: BufferEncoding,+ callback: (error: NodeJS.ErrnoException | null, data?: string) => void,+ ) => {+ try {+ hooks.beforeRead();+ } catch (error) {+ callback(error instanceof Error ? error : new Error(String(error)));+ return;+ }+ actual.readFile(path, encoding, callback);+ },+ createReadStream: (path: fs.PathLike, options?: Parameters<typeof fs.createReadStream>[1]) => {+ if (hooks.failCreation) throw new Error("Injected stream construction failure");+ const stream = actual.createReadStream(path, options);+ hooks.streams.push(stream);+ const fd = typeof options === "object" ? options.fd : undefined;+ if (typeof fd === "number") stream.on("close", () => hooks.active.delete(fd));+ if (hooks.failStream)+ queueMicrotask(() => stream.destroy(new Error("Injected stream failure")));+ return stream;+ },+ };+});++describe("producer file server checked reads", () => {+ let root: string;+ let projectDir: string;+ let compiledDir: string;+ let server: FileServerHandle | undefined;++ beforeEach(() => {+ root = fs.mkdtempSync(join(tmpdir(), "hf-server-read-"));+ projectDir = join(root, "project");+ compiledDir = join(root, "compiled");+ fs.mkdirSync(projectDir);+ fs.mkdirSync(compiledDir);+ hooks.opened.clear();+ hooks.active.clear();+ hooks.streams = [];+ hooks.failStream = false;+ hooks.failCreation = false;+ });++ afterEach(() => {+ server?.close();+ server = undefined;+ hooks.checked = () => {};+ hooks.beforeRead = () => {};+ vi.restoreAllMocks();+ fs.rmSync(root, { recursive: true, force: true });+ });++ async function expectClosed() {+ // HTTP sockets can reuse an already-closed fd before fetch resolves.+ // Track successful real closes instead of probing stale descriptor numbers.+ expect(hooks.opened.size).toBeGreaterThan(0);+ await vi.waitFor(() => expect(hooks.active.size).toBe(0));+ }++ it.each([+ ["project", "html"],+ ["project", "bin"],+ ["project", "range"],+ ["compiled", "html"],+ ["compiled", "bin"],+ ["compiled", "range"],+ ])("reads the checked %s .%s despite replacement", async (source, ext) => {+ const name = `asset.${ext === "range" ? "bin" : ext}`;+ const file = join(source === "compiled" ? compiledDir : projectDir, name);+ fs.writeFileSync(join(projectDir, name), "project bytes");+ fs.writeFileSync(file, "checked bytes");+ hooks.checked = (path) => {+ if (path !== file) return;+ hooks.checked = () => {};+ fs.renameSync(file, join(root, "original"));+ fs.writeFileSync(file, "replacement bytes");+ };+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir, compiledDir });+ const response = await fetch(+ `${server.url}/${name}`,+ ext === "range" ? { headers: { Range: "bytes=1-4" } } : {},+ );+ expect(response.status).toBe(ext === "range" ? 206 : 200);+ if (ext === "range") {+ expect(response.headers.get("content-range")).toBe("bytes 1-4/13");+ expect(await response.text()).toBe("heck");+ } else {+ expect(await response.text()).toContain("checked bytes");+ if (ext === "bin") expect(response.headers.get("content-length")).toBe("13");+ }+ await expectClosed();+ });++ it.each(["missing", "directory", "non-directory parent"])(+ "falls back from a compiled %s",+ async (kind) => {+ fs.mkdirSync(join(projectDir, "assets"));+ fs.writeFileSync(join(projectDir, "assets", "file.bin"), "project bytes");+ if (kind === "directory")+ fs.mkdirSync(join(compiledDir, "assets", "file.bin"), { recursive: true });+ if (kind === "non-directory parent") fs.writeFileSync(join(compiledDir, "assets"), "blocker");+ server = await createFileServer({+ headScripts: [],+ bodyScripts: [],+ projectDir,+ compiledDir,+ });+ const response = await fetch(`${server.url}/assets/file.bin`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("project bytes");+ await expectClosed();+ },+ );++ it.skipIf(process.platform === "win32")("skips a compiled FIFO without blocking", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "project bytes");+ execFileSync("mkfifo", [join(compiledDir, "file.bin")]);+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir, compiledDir });+ const response = await fetch(`${server.url}/file.bin`);+ expect(await response.text()).toBe("project bytes");+ await expectClosed();+ });++ it.skipIf(process.platform === "win32")("falls back from a compiled Unix socket", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "project bytes");+ const socket = createServer();+ await new Promise<void>((resolve) => socket.listen(join(compiledDir, "file.bin"), resolve));+ try {+ server = await createFileServer({+ headScripts: [],+ bodyScripts: [],+ projectDir,+ compiledDir,+ });+ const response = await fetch(`${server.url}/file.bin`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("project bytes");+ await expectClosed();+ } finally {+ await new Promise<void>((resolve, reject) =>+ socket.close((error) => (error ? reject(error) : resolve())),+ );+ }+ });++ it("serves an empty compiled file instead of falling back", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "project bytes");+ fs.writeFileSync(join(compiledDir, "file.bin"), "");+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir, compiledDir });+ const response = await fetch(`${server.url}/file.bin`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("");+ await expectClosed();+ });++ it("continues serving symlinked assets", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "project bytes");+ fs.symlinkSync(+ projectDir,+ join(compiledDir, "assets"),+ process.platform === "win32" ? "junction" : "dir",+ );+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir, compiledDir });+ const response = await fetch(`${server.url}/assets/file.bin`);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("project bytes");+ await expectClosed();+ });++ it("keeps missing files and directories at 404", async () => {+ fs.mkdirSync(join(projectDir, "folder"));+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir });+ for (const path of ["missing", "folder", "missing/child"]) {+ const response = await fetch(`${server.url}/${path}`);+ expect(response.status).toBe(404);+ expect(await response.text()).toBe("Not found");+ }+ });++ it("injects scripts only into the selected index HTML", async () => {+ const html = "<html><head></head><body>compiled</body></html>";+ fs.writeFileSync(join(projectDir, "index.html"), "project");+ fs.writeFileSync(join(compiledDir, "index.html"), html);+ fs.writeFileSync(join(compiledDir, "other.html"), html);+ server = await createFileServer({+ projectDir,+ compiledDir,+ headScripts: ["window.headTest = 1;"],+ bodyScripts: ["window.bodyTest = 1;"],+ });+ const response = await fetch(server.url);+ expect(response.headers.get("content-type")).toBe("text/html; charset=utf-8");+ const text = await response.text();+ expect(text).toContain("compiled");+ expect(text).toContain("window.headTest = 1;");+ expect(text).toContain("window.bodyTest = 1;");+ const other = await (await fetch(`${server.url}/other.html`)).text();+ expect(other).toContain("compiled");+ expect(other).not.toContain("window.headTest = 1;");+ expect(other).not.toContain("window.bodyTest = 1;");+ await expectClosed();+ });++ it.each(["full", "range"])("closes a %s stream after a read error", async (kind) => {+ fs.writeFileSync(join(projectDir, "file.bin"), "checked bytes");+ hooks.failStream = true;+ vi.spyOn(console, "error").mockImplementation(() => {});+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir });+ const url = server.url;+ await expect(async () => {+ const response = await fetch(+ `${url}/file.bin`,+ kind === "range" ? { headers: { Range: "bytes=1-4" } } : {},+ );+ await response.arrayBuffer();+ }).rejects.toThrow();+ await expectClosed();+ });++ it.each(["creation", "conversion"])(+ "closes the descriptor after stream %s fails",+ async (stage) => {+ fs.writeFileSync(join(projectDir, "file.bin"), "checked bytes");+ if (stage === "creation") hooks.failCreation = true;+ else+ vi.spyOn(Readable, "toWeb").mockImplementationOnce(() => {+ throw new Error("Injected conversion failure");+ });+ vi.spyOn(console, "error").mockImplementation(() => {});+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir });+ expect((await fetch(`${server.url}/file.bin`)).status).toBe(500);+ await expectClosed();+ },+ );++ it.each(["full", "range"])("closes a %s stream when the client cancels", async (kind) => {+ const file = join(projectDir, "file.bin");+ fs.writeFileSync(file, "");+ fs.truncateSync(file, 32 * 1024 * 1024);+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir });+ const response = await fetch(+ `${server.url}/file.bin`,+ kind === "range" ? { headers: { Range: "bytes=1-" } } : {},+ );+ expect(response.status).toBe(kind === "range" ? 206 : 200);+ await response.body?.cancel();+ await expectClosed();+ });++ it.each(["full", "range", "unsatisfiable"])(+ "closes a %s HEAD response without creating a stream",+ async (kind) => {+ fs.writeFileSync(join(projectDir, "file.bin"), "checked bytes");+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir });+ const response = await fetch(`${server.url}/file.bin`, {+ method: "HEAD",+ headers: kind === "full" ? {} : { Range: kind === "range" ? "bytes=1-4" : "bytes=99-" },+ });+ expect(response.status).toBe(kind === "full" ? 200 : kind === "range" ? 206 : 416);+ expect(await response.text()).toBe("");+ expect(hooks.streams).toHaveLength(0);+ await expectClosed();+ },+ );++ it("closes an unsatisfiable GET without creating a stream", async () => {+ fs.writeFileSync(join(projectDir, "file.bin"), "checked bytes");+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir });+ const response = await fetch(`${server.url}/file.bin`, { headers: { Range: "bytes=99-" } });+ expect(response.status).toBe(416);+ expect(response.headers.get("content-range")).toBe("bytes */13");+ expect(hooks.streams).toHaveLength(0);+ await expectClosed();+ });++ it.each(["stat", "read"])("closes the selected file when %s fails", async (step) => {+ fs.writeFileSync(join(projectDir, "file.html"), "bytes");+ const fail = () => {+ throw new Error("Injected failure");+ };+ if (step === "stat") hooks.checked = fail;+ else hooks.beforeRead = fail;+ vi.spyOn(console, "error").mockImplementation(() => {});+ server = await createFileServer({ headScripts: [], bodyScripts: [], projectDir });+ expect((await fetch(`${server.url}/file.html`)).status).toBe(500);+ await expectClosed();+ });+});diff --git a/packages/producer/src/services/fileServer.ts b/packages/producer/src/services/fileServer.tsindex 33ceade0b9..24d4136952 100644--- a/packages/producer/src/services/fileServer.ts+++ b/packages/producer/src/services/fileServer.ts@@ -11,8 +11,19 @@import { Hono } from "hono";import { serve } from "@hono/node-server";import type { IncomingMessage } from "node:http";-import { existsSync, realpathSync, statSync, createReadStream } from "node:fs";-import { readFile } from "node:fs/promises";+import {+ existsSync,+ realpathSync,+ statSync,+ createReadStream,+ openSync,+ fstatSync,+ closeSync,+ constants,+ readFile,+} from "node:fs";+import { promisify } from "node:util";+import { Readable } from "node:stream";import { join, extname, resolve, sep } from "node:path";import { injectScriptsAtHeadStart, injectScriptsIntoHtml } from "@hyperframes/core/compiler";@@ -21,6 +32,8 @@ import { getVerifiedHyperframeRuntimeSource } from "./hyperframeRuntimeLoader.jsimport { getHfEarlyStub } from "../generated/hf-early-stub-inline.js";import { defaultLogger, type ProducerLogger } from "../logger.js";+const readFileAsync = promisify(readFile);+export { injectScriptsAtHeadStart };type PathModuleLike = {@@ -714,6 +727,34 @@ export function closeFileServerSafely(}}+function openRegularFile(filePath: string) {+ let fd: number;+ try {+ // Reject FIFOs with fstat without waiting for a writer to connect.+ fd = openSync(filePath, constants.O_RDONLY | constants.O_NONBLOCK);+ } catch (error) {+ if (+ error instanceof Error &&+ "code" in error &&+ (error.code === "ENOENT" || error.code === "ENOTDIR")+ )+ return null;+ // A failed open of a directory/socket has platform-specific errors.+ // Classifying it here never authorizes a later pathname read.+ if (!statSync(filePath, { throwIfNoEntry: false })?.isFile()) return null;+ throw error;+ }+ let accepted = false;+ try {+ const stat = fstatSync(fd);+ if (!stat.isFile()) return null;+ accepted = true;+ return { fd, stat, filePath };+ } finally {+ if (!accepted) closeSync(fd);+ }+}+export function createFileServer(options: FileServerOptions): Promise<FileServerHandle> {const { projectDir, compiledDir, port = 0, stripEmbeddedRuntime = true } = options;@@ -757,118 +798,105 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer// containment, so a request like `GET /../etc/passwd` would otherwise// be served straight off the filesystem. Keep this lexical so project// symlinks to sibling asset directories behave like preview mode.- let filePath: string | null = null;- if (compiledDir) {- const candidate = join(compiledDir, relativePath);- if (- existsSync(candidate) &&- isPathInside(candidate, compiledDir) &&- statSync(candidate).isFile()- ) {- filePath = candidate;- }- }- if (!filePath) {- const candidate = join(projectDir, relativePath);- if (- existsSync(candidate) &&- isPathInside(candidate, projectDir) &&- statSync(candidate).isFile()- ) {- filePath = candidate;- }+ let file: ReturnType<typeof openRegularFile> = null;+ for (const root of compiledDir ? [compiledDir, projectDir] : [projectDir]) {+ const candidate = join(root, relativePath);+ if (isPathInside(candidate, root)) file = openRegularFile(candidate);+ if (file) break;}- if (!filePath) {+ if (!file) {if (!/favicon\.ico$/i.test(requestPath)) {console.warn(`[FileServer] 404 Not Found: ${requestPath}`);}return c.text("Not found", 404);}- const ext = extname(filePath).toLowerCase();- const contentType = MIME_TYPES[ext] || "application/octet-stream";-- if (ext === ".html") {- // Use the async read here so we don't block the Node event loop while- // reading an HTML file (typically small, but a 200KB+ AI-generated- // composition during a concurrent render still costs a ms of stall).- // The injection step is sync — it's pure string ops on the buffered- // HTML — but the read itself is the only step that touches the disk.- const rawHtml = await readFile(filePath, "utf-8");- const isIndex = relativePath === "index.html";- let html = rawHtml;- if (preHeadScripts.length > 0) {- html = injectScriptsAtHeadStart(html, preHeadScripts);+ const { fd, stat, filePath } = file;+ let streamOwnsFd = false;+ try {+ const ext = extname(filePath).toLowerCase();+ const contentType = MIME_TYPES[ext] || "application/octet-stream";++ if (ext === ".html") {+ // Use the async read here so we don't block the Node event loop while+ // reading an HTML file (typically small, but a 200KB+ AI-generated+ // composition during a concurrent render still costs a ms of stall).+ // The injection step is sync — it's pure string ops on the buffered+ // HTML — but the read itself is the only step that touches the disk.+ const rawHtml = await readFileAsync(fd, "utf-8");+ const isIndex = relativePath === "index.html";+ let html = rawHtml;+ if (preHeadScripts.length > 0) {+ html = injectScriptsAtHeadStart(html, preHeadScripts);+ }+ html = isIndex+ ? injectScriptsIntoHtml(html, headScripts, bodyScripts, stripEmbeddedRuntime)+ : html;+ return c.text(html, 200, { "Content-Type": contentType });}- html = isIndex- ? injectScriptsIntoHtml(html, headScripts, bodyScripts, stripEmbeddedRuntime)- : html;- return c.text(html, 200, { "Content-Type": contentType });- }- // Stream binary file content rather than buffering it with readFileSync.- // On video-heavy compositions Chrome requests several 32MB video files- // back-to-back through this server; each readFileSync(32MB) blocked the- // Node event loop long enough to wedge concurrent /health responses (see- // renderOrchestrator.ts:1277-1306 documenting the same regression class).- // createReadStream() pipes bounded chunks asynchronously, so the event- // loop stays responsive even when several large assets are in flight- // simultaneously. Chrome reassembles the chunks transparently.- //- // We also honor `Range:` requests (RFC 7233) so Chrome's <video> element- // can seek into and partial-load large media without re-pulling the whole- // file. `Accept-Ranges: bytes` is advertised on every response (including- // full-body 200s) so the client knows ranges are supported.- const stat = statSync(filePath);- const totalSize = stat.size;- const rangeHeader = c.req.header("range");- const rangeRequest = parseRangeHeader(rangeHeader, totalSize);-- if (rangeRequest.kind === "unsatisfiable") {- // 416 Range Not Satisfiable. RFC 7233 §4.4 mandates `Content-Range`- // carry the total length as `bytes */<size>` so clients know how to- // re-issue a valid range.- return new Response(null, {- status: 416,- headers: {- "Content-Type": contentType,- "Content-Range": `bytes */${totalSize}`,- "Accept-Ranges": "bytes",- },- });- }+ // Stream binary file content rather than buffering it with readFileSync.+ // On video-heavy compositions Chrome requests several 32MB video files+ // back-to-back through this server; each readFileSync(32MB) blocked the+ // Node event loop long enough to wedge concurrent /health responses (see+ // renderOrchestrator.ts:1277-1306 documenting the same regression class).+ // createReadStream() pipes bounded chunks asynchronously, so the event+ // loop stays responsive even when several large assets are in flight+ // simultaneously. Chrome reassembles the chunks transparently.+ //+ // We also honor `Range:` requests (RFC 7233) so Chrome's <video> element+ // can seek into and partial-load large media without re-pulling the whole+ // file. `Accept-Ranges: bytes` is advertised on every response (including+ // full-body 200s) so the client knows ranges are supported.+ const totalSize = stat.size;+ const rangeHeader = c.req.header("range");+ const rangeRequest = parseRangeHeader(rangeHeader, totalSize);++ if (rangeRequest.kind === "unsatisfiable") {+ // 416 Range Not Satisfiable. RFC 7233 §4.4 mandates `Content-Range`+ // carry the total length as `bytes */<size>` so clients know how to+ // re-issue a valid range.+ return new Response(null, {+ status: 416,+ headers: {+ "Content-Type": contentType,+ "Content-Range": `bytes */${totalSize}`,+ "Accept-Ranges": "bytes",+ },+ });+ }- if (rangeRequest.kind === "satisfiable") {- const { start, end } = rangeRequest;- const length = end - start + 1;- const stream = createReadStream(filePath, { start, end });- const webStream = Readable.toWeb(stream) as unknown as ReadableStream;- return new Response(webStream, {- status: 206,+ const range = rangeRequest.kind === "satisfiable" ? rangeRequest : null;+ const responseOptions = {+ status: range ? 206 : 200,headers: {"Content-Type": contentType,- "Content-Length": String(length),- "Content-Range": `bytes ${start}-${end}/${totalSize}`,+ "Content-Length": String(range ? range.end - range.start + 1 : totalSize),"Accept-Ranges": "bytes",+ ...(range ? { "Content-Range": `bytes ${range.start}-${range.end}/${totalSize}` } : {}),},+ };+ // HEAD has no body consumer to take ownership of a stream's descriptor.+ if (c.req.method === "HEAD") return new Response(null, responseOptions);+ const stream = createReadStream(filePath, {+ fd,+ autoClose: true,+ ...(range ? { start: range.start, end: range.end } : {}),});+ streamOwnsFd = true;+ try {+ const webStream = Readable.toWeb(stream) as unknown as ReadableStream;+ return new Response(webStream, responseOptions);+ } catch (error) {+ stream.destroy();+ throw error;+ }+ } finally {+ // Streams close on completion, error or cancellation. HTML/416/errors+ // before stream creation remain owned by this request.+ if (!streamOwnsFd) closeSync(fd);}-- // No Range header (or malformed/multi-range): full-body 200 with- // Accept-Ranges advertised so the client knows future Range requests- // are supported. Node Readable -> Web ReadableStream so Hono's- // Response can consume it. Node 18+ supports Readable.toWeb directly.- const stream = createReadStream(filePath);- const webStream = Readable.toWeb(stream) as unknown as ReadableStream;- return new Response(webStream, {- status: 200,- headers: {- "Content-Type": contentType,- "Content-Length": String(totalSize),- "Accept-Ranges": "bytes",- },- });});return new Promise((resolve) => {