Files
hyperframes/packages/engine/src/services/fileServer.ts
T
Michael WangandClaude Opus 5.5 60fb9d2c5e fix(producer,engine): harden render paths, render slots and local listeners (#7508)
* fix(producer): build the render job before taking a render slot

A request whose options fail the strict render-request validator now gets
a 400 on both the blocking and streaming routes, and its inline project
directory is removed. Validate workers up front like the other overrides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(producer): write compiled sub-compositions only inside the compiled directory

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(engine): keep media work files inside their directory for any element id

Map a media element id to one plain path segment before it names a frame
directory or an intermediate audio file. Ids that already are one plain
segment map to themselves, so existing paths stay the same; the producer
and the distributed plan derive the same segment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(engine): listen on loopback by default in the engine file server

The file server feeds the co-located capture browser, which loads it from
localhost. A caller that wants another interface passes hostname.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(producer): refuse cross-origin browser posts to the standalone render server

A web page on another origin can no longer start a render or lint through
the server's POST routes. Requests without an Origin header (CLI tools,
server-to-server callers) and same-origin pages are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(engine): trim comments on the media path segment and file server host

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(producer): trust the browser's Sec-Fetch-Site verdict for render server posts

A same-origin page behind a reverse proxy that rewrites the Host header sent an
Origin that no longer matched Host, so the cross-origin guard refused it. The
guard now uses Sec-Fetch-Site when the browser sends it and falls back to the
Origin and Host comparison only for browsers that do not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(engine): keep generated media path names apart from plain ids and within filename limits

A plain media id that already ends like a generated name now takes the hashed
branch too, so it can no longer share frame folders or audio work files with
the unsafe id that produced that name. The readable part of a generated name
is capped at 64 UTF-8 bytes before the digest, so long or multibyte ids that
contain separators stay within the 255-byte filename limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 20:26:24 +00:00

167 lines
5.3 KiB
TypeScript

/**
* File Server
*
* Lightweight HTTP server that serves a project directory to headless Chrome.
* Optionally injects scripts into index.html on-the-fly (e.g. runtime, bridge).
* Framework-agnostic — the caller decides what scripts to inject.
*/
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { readFileSync, openSync, fstatSync, closeSync, statSync, constants } from "node:fs";
import { join, extname } from "node:path";
import { injectScriptsIntoHtml } from "@hyperframes/core/compiler";
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".mjs": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".webp": "image/webp",
".avif": "image/avif",
".ico": "image/vnd.microsoft.icon",
".mp4": "video/mp4",
".mov": "video/quicktime",
".webm": "video/webm",
".mp3": "audio/mpeg",
".wav": "audio/wav",
".ogg": "audio/ogg",
".aac": "audio/aac",
".flac": "audio/flac",
".m4a": "audio/mp4",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".otf": "font/otf",
};
export interface FileServerOptions {
projectDir: string;
compiledDir?: string;
port?: number;
/** Scripts injected into <head> of index.html. Default: none. */
headScripts?: string[];
/** Scripts injected before </body> of index.html. Default: none. */
bodyScripts?: string[];
/** Strip embedded runtime scripts from HTML before injection. Default: true. */
stripEmbeddedRuntime?: boolean;
hostname?: string;
}
export interface FileServerHandle {
url: string;
port: number;
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);
}
}
/**
* Resolves the request path against both roots and rejects the pair the
* moment either escapes -- lexically, so a symlinked asset directory still
* resolves (see the containment note at the call site).
*/
function resolveContainedPaths(
projectDir: string,
compiledDir: string | undefined,
relativePath: string,
): { projectPath: string; compiledPath: string | null } | null {
const projectPath = join(projectDir, relativePath);
if (!isWithinProjectRoot(projectDir, projectPath)) return null;
if (!compiledDir) return { projectPath, compiledPath: null };
const compiledPath = join(compiledDir, relativePath);
if (!isWithinProjectRoot(compiledDir, compiledPath)) return null;
return { projectPath, compiledPath };
}
export function createFileServer(options: FileServerOptions): Promise<FileServerHandle> {
const {
projectDir,
compiledDir,
port = 0,
stripEmbeddedRuntime = true,
hostname = "127.0.0.1",
} = options;
const headScripts = options.headScripts ?? [];
const bodyScripts = options.bodyScripts ?? [];
const app = new Hono();
app.get("/*", (c) => {
let requestPath = c.req.path;
if (requestPath === "/") requestPath = "/index.html";
// Remove leading slash
const relativePath = requestPath.replace(/^\//, "");
// Percent escapes can decode into separators and dot segments before the
// join, so a hostile request can name files above either root -- see
// resolveContainedPaths for why the check stays lexical, not realpath.
const resolved = resolveContainedPaths(projectDir, compiledDir, relativePath);
if (!resolved) return c.text("Not found", 404);
const content =
(resolved.compiledPath ? readRegularFile(resolved.compiledPath) : null) ??
readRegularFile(resolved.projectPath);
if (content === null) return c.text("Not found", 404);
const ext = extname(relativePath).toLowerCase();
const contentType = MIME_TYPES[ext] || "application/octet-stream";
if (ext === ".html") {
const rawHtml = content.toString("utf-8");
const html =
relativePath === "index.html"
? injectScriptsIntoHtml(rawHtml, headScripts, bodyScripts, stripEmbeddedRuntime)
: rawHtml;
return c.text(html, 200, { "Content-Type": contentType });
}
return new Response(content, {
status: 200,
headers: { "Content-Type": contentType },
});
});
return new Promise((resolve) => {
const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
const actualPort = info.port;
const url = `http://localhost:${actualPort}`;
resolve({
url,
port: actualPort,
close: () => server.close(),
});
});
});
}