Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(server): contain static file requests within their served roots (#4217)
Dery Ferdikacc19b8c8121d
diff --git a/packages/cli/src/server/studioServer.pathSafety.test.ts b/packages/cli/src/server/studioServer.pathSafety.test.tsnew file mode 100644index 0000000000..1ee03ad6ee--- /dev/null+++ b/packages/cli/src/server/studioServer.pathSafety.test.ts@@ -0,0 +1,73 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as fs from "node:fs";+import * as path from "node:path";+import { createStudioServer } from "./studioServer.js";+import {+ cleanupStudioServerRoot,+ makeStudioServerRoot,+ writeStudioIndexHtml,+} from "./studioServerTestFixture.js";++/**+ * The static SPA handlers resolve the raw request path against the bundle+ * directory. Hono decodes percent escapes when routing, so an encoded+ * separator or dot segment in the request must never walk out of the bundle+ * root — browsers would not send those shapes, but anything that can reach+ * the bound port can. These tests pin containment at the handler.+ */++const hooks = vi.hoisted(() => ({ studioDir: "" }));++// The bundle directory is resolved from __dirname at server construction, so+// point that one `resolve(<...>/server, "studio")` call at a temp tree.+// fallow-ignore-next-line code-duplication+vi.mock("node:path", async (importOriginal) => {+ const actual = await importOriginal<typeof path>();+ return {+ ...actual,+ resolve: (...parts: string[]) =>+ hooks.studioDir && parts.length === 2 && parts[0]?.endsWith("server") && parts[1] === "studio"+ ? hooks.studioDir+ : actual.resolve(...parts),+ };+});++let root: string;+let server: Awaited<ReturnType<typeof createStudioServer>>;++beforeEach(async () => {+ const fixture = makeStudioServerRoot("hf-studio-containment-");+ root = fixture.root;+ hooks.studioDir = fixture.studioDir;+ fs.writeFileSync(path.join(root, "studio-marker.txt"), "STUDIO-MARKER");+ writeStudioIndexHtml(hooks.studioDir);+ server = await createStudioServer({ projectDir: fixture.projectDir });+});++afterEach(() => {+ cleanupStudioServerRoot(server, root, () => (hooks.studioDir = ""));+});++describe("static file path containment", () => {+ // A percent-encoded backslash decodes to a real separator on Windows, so+ // two encoded hops walk from the bundle root to the temp root above it.+ it.each(["/assets/..%5c..%5cstudio-marker.txt", "/icons/..%5c..%5cstudio-marker.txt"])(+ "rejects encoded traversal %s",+ async (requestPath) => {+ const response = await server.app.request(requestPath);+ expect(response.status).toBe(404);+ expect(await response.text()).not.toContain("STUDIO-MARKER");+ },+ );++ it("still serves the SPA shell and bundle assets", async () => {+ const shell = await server.app.request("/");+ expect(shell.status).toBe(200);+ expect(await shell.text()).toContain("Studio");++ fs.writeFileSync(path.join(hooks.studioDir, "assets", "app.js"), "export {};");+ const asset = await server.app.request("/assets/app.js");+ expect(asset.status).toBe(200);+ expect(await asset.text()).toContain("export {};");+ });+});diff --git a/packages/cli/src/server/studioServer.staticAssets.test.ts b/packages/cli/src/server/studioServer.staticAssets.test.tsindex 39a5c11f87..94a514d3ba 100644--- a/packages/cli/src/server/studioServer.staticAssets.test.ts+++ b/packages/cli/src/server/studioServer.staticAssets.test.ts@@ -1,8 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import * as fs from "node:fs";import * as path from "node:path";-import { tmpdir } from "node:os";import { createStudioServer, type StudioServer } from "./studioServer.js";+import {+ cleanupStudioServerRoot,+ makeStudioServerRoot,+ writeStudioIndexHtml,+} from "./studioServerTestFixture.js";/*** Cache policy for the studio bundle, decided by ROUTE. Vite emits only@@ -15,6 +19,7 @@ const hooks = vi.hoisted(() => ({ studioDir: "" }));// The bundle directory is resolved from __dirname at server construction, so// point that one `resolve(<...>/server, "studio")` call at a temp tree.+// fallow-ignore-next-line code-duplicationvi.mock("node:path", async (importOriginal) => {const actual = await importOriginal<typeof path>();return {@@ -38,26 +43,19 @@ let root: string;let server: StudioServer;beforeEach(() => {- root = fs.mkdtempSync(path.join(tmpdir(), "hf-studio-assets-"));- hooks.studioDir = path.join(root, "studio");- const projectDir = path.join(root, "project");- fs.mkdirSync(projectDir);- fs.mkdirSync(path.join(hooks.studioDir, "assets"), { recursive: true });+ const fixture = makeStudioServerRoot("hf-studio-assets-");+ root = fixture.root;+ hooks.studioDir = fixture.studioDir;fs.mkdirSync(path.join(hooks.studioDir, "icons"), { recursive: true });fs.writeFileSync(path.join(hooks.studioDir, "assets", HASHED_BUNDLE), BUNDLE_BYTES);fs.writeFileSync(path.join(hooks.studioDir, "icons", PUBLIC_ICON), "<svg/>");fs.writeFileSync(path.join(hooks.studioDir, "favicon.svg"), "<svg/>");- fs.writeFileSync(- path.join(hooks.studioDir, "index.html"),- "<html><head></head><body>Studio</body></html>",- );- server = createStudioServer({ projectDir });+ writeStudioIndexHtml(hooks.studioDir);+ server = createStudioServer({ projectDir: fixture.projectDir });});afterEach(() => {- server.watcher.close();- fs.rmSync(root, { recursive: true, force: true });- hooks.studioDir = "";+ cleanupStudioServerRoot(server, root, () => (hooks.studioDir = ""));});describe("studio bundle cache policy", () => {diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.tsindex 9c63828896..ecff85d778 100644--- a/packages/cli/src/server/studioServer.ts+++ b/packages/cli/src/server/studioServer.ts@@ -49,6 +49,7 @@ import { resolveAutoProxy } from "../utils/projectConfig.js";import { getElementScreenshotClip } from "@hyperframes/studio-server/screenshot-clip";import type { ScreenshotClip } from "@hyperframes/studio-server/screenshot-clip";import type { RenderJob } from "@hyperframes/producer";+import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";import { seekCompositionTimeline } from "../capture/captureCompositionFrame.js";import {assertWebGpuAdapterAvailable,@@ -893,6 +894,12 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {// Studio SPA static filesconst serveStudioStaticFile = (cacheControl: string) => (c: Context) => {const filePath = resolve(studioDir, c.req.path.slice(1));+ // Percent escapes can decode into separators and dot segments before this+ // resolve, so a hostile request can name files above the bundle+ // directory. Containment stays lexical on purpose: bundle assets may sit+ // behind symlinked directories (same tradeoff as the preview asset+ // route), but dot segments must never collapse outside the bundle root.+ if (!isWithinProjectRoot(studioDir, filePath)) return c.text("not found", 404);const content = readBundleFile(filePath);if (content === null) return c.text("not found", 404);return new Response(content, {diff --git a/packages/cli/src/server/studioServerTestFixture.ts b/packages/cli/src/server/studioServerTestFixture.tsnew file mode 100644index 0000000000..e66b5ea4fb--- /dev/null+++ b/packages/cli/src/server/studioServerTestFixture.ts@@ -0,0 +1,40 @@+import * as fs from "node:fs";+import * as path from "node:path";+import { tmpdir } from "node:os";++/**+ * Temp root plus empty `studio/assets` and `project` dirs, shared by every+ * studioServer static-file test; each caller writes its own fixture files+ * into the returned `studioDir` before constructing the server.+ */+export function makeStudioServerRoot(prefix: string): {+ root: string;+ studioDir: string;+ projectDir: string;+} {+ const root = fs.mkdtempSync(path.join(tmpdir(), prefix));+ const studioDir = path.join(root, "studio");+ const projectDir = path.join(root, "project");+ fs.mkdirSync(projectDir);+ fs.mkdirSync(path.join(studioDir, "assets"), { recursive: true });+ return { root, studioDir, projectDir };+}++/** The one SPA shell every studioServer static-file test needs, unchanged. */+export function writeStudioIndexHtml(studioDir: string): void {+ fs.writeFileSync(+ path.join(studioDir, "index.html"),+ "<html><head></head><body>Studio</body></html>",+ );+}++/** Pairs with makeStudioServerRoot; `onDone` resets caller-local state (e.g. the `hooks.studioDir` mock target). */+export function cleanupStudioServerRoot(+ server: { watcher: { close(): void } },+ root: string,+ onDone?: () => void,+): void {+ server.watcher.close();+ fs.rmSync(root, { recursive: true, force: true });+ onDone?.();+}diff --git a/packages/engine/src/services/fileServer.pathSafety.test.ts b/packages/engine/src/services/fileServer.pathSafety.test.tsnew file mode 100644index 0000000000..4df08092d3--- /dev/null+++ b/packages/engine/src/services/fileServer.pathSafety.test.ts@@ -0,0 +1,63 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import * as fs from "node:fs";+import * as path from "node:path";+import { tmpdir } from "node:os";+import { createFileServer, type FileServerHandle } from "./fileServer.js";++/**+ * The server derives each request path from the URL and joins it onto+ * compiledDir/projectDir. Hono decodes percent escapes when routing, so an+ * encoded separator or dot segment in the request must never walk out of the+ * served roots — Chrome never requests those shapes, but anything that can+ * reach the port (LAN bind, other local processes) can. On Windows an encoded+ * backslash (%5c) decodes to a real separator, so `..%5c..%5c` escapes even+ * though `..%2f` is normalized away by join(). These tests pin containment+ * at the handler.+ */+describe("fileServer path containment", () => {+ let root: string;+ let projectDir: string;+ let outsideFile: string;+ let server: FileServerHandle;++ beforeEach(async () => {+ root = fs.mkdtempSync(path.join(tmpdir(), "hf-fileserver-containment-"));+ projectDir = path.join(root, "project");+ fs.mkdirSync(projectDir);+ fs.writeFileSync(path.join(projectDir, "index.html"), "<html></html>");+ outsideFile = path.join(root, "outside-secret.txt");+ fs.writeFileSync(outsideFile, "OUTSIDE");+ server = await createFileServer({+ headScripts: [],+ bodyScripts: [],+ projectDir,+ });+ });++ afterEach(async () => {+ await server.close();+ fs.rmSync(root, { recursive: true, force: true });+ });++ const escapeAttempts = [+ // Encoded separators: %2f collapses with a leading dot-segment only via a+ // nested hop, %5c is a live separator on Windows.+ "/..%2foutside-secret.txt",+ "/%2e%2e%2foutside-secret.txt",+ "/nested%2f..%2f..%2foutside-secret.txt",+ "/..%5coutside-secret.txt",+ "/..%5c..%5coutside-secret.txt",+ ];++ it.each(escapeAttempts)("rejects encoded traversal %s", async (requestPath) => {+ const response = await fetch(`${server.url}${requestPath}`);+ expect(response.status).toBe(404);+ expect(await response.text()).not.toContain("OUTSIDE");+ });++ it("still serves files inside the project", async () => {+ const response = await fetch(`${server.url}/index.html`);+ expect(response.status).toBe(200);+ expect(await response.text()).toContain("<html>");+ });+});diff --git a/packages/engine/src/services/fileServer.ts b/packages/engine/src/services/fileServer.tsindex 04b4a62fe2..d0133ed305 100644--- a/packages/engine/src/services/fileServer.ts+++ b/packages/engine/src/services/fileServer.ts@@ -11,6 +11,7 @@ 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",@@ -84,6 +85,24 @@ function readRegularFile(filePath: string): Buffer<ArrayBuffer> | null {}}+/**+ * 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 } = options;@@ -98,10 +117,14 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer// Remove leading slashconst relativePath = requestPath.replace(/^\//, "");- const compiledPath = compiledDir ? join(compiledDir, relativePath) : null;+ // 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 =- (compiledPath ? readRegularFile(compiledPath) : null) ??- readRegularFile(join(projectDir, relativePath));+ (resolved.compiledPath ? readRegularFile(resolved.compiledPath) : null) ??+ readRegularFile(resolved.projectPath);if (content === null) return c.text("Not found", 404);const ext = extname(relativePath).toLowerCase();diff --git a/packages/parsers/src/assetResolution.test.ts b/packages/parsers/src/assetResolution.test.tsindex ead164ad07..bb9c83cf40 100644--- a/packages/parsers/src/assetResolution.test.ts+++ b/packages/parsers/src/assetResolution.test.ts@@ -1,10 +1,11 @@import { afterAll, beforeAll, describe, expect, it } from "vitest";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { join, posix, win32 } from "node:path";import {collectSubCompositionSrcs,isUnresolvedAssetPlaceholder,+ isWithinProjectRoot,maskNonScannableRanges,resolveProjectRelativeSrc,} from "./assetResolution.js";@@ -219,3 +220,48 @@ describe("resolveProjectRelativeSrc — the one src resolver for lint and render}});});++// A CI runner is one OS. Injecting path.win32/path.posix exercises both+// platforms' separator and drive-letter rules from here, so a regression in+// either fails this suite regardless of which OS actually runs it.+describe("isWithinProjectRoot", () => {+ it("rejects a backslash traversal under path.win32", () => {+ const root = "C:\\project";+ const candidate = win32.join(root, "..\\secret.txt");+ expect(isWithinProjectRoot(root, candidate, win32)).toBe(false);+ });++ it("rejects a mixed backslash/forward-slash traversal under path.win32", () => {+ const root = "C:\\project";+ const candidate = win32.join(root, "..\\../secret.txt");+ expect(isWithinProjectRoot(root, candidate, win32)).toBe(false);+ });++ it("rejects a drive-letter path outside the root under path.win32", () => {+ const root = "C:\\project";+ const candidate = "D:\\secret.txt";+ expect(isWithinProjectRoot(root, candidate, win32)).toBe(false);+ });++ it("allows a nested asset under path.win32", () => {+ const root = "C:\\project";+ const candidate = win32.join(root, "assets\\a.png");+ expect(isWithinProjectRoot(root, candidate, win32)).toBe(true);+ });++ it("rejects a forward-slash traversal under path.posix", () => {+ const root = "/project";+ const candidate = posix.join(root, "../secret.txt");+ expect(isWithinProjectRoot(root, candidate, posix)).toBe(false);+ });++ it("allows a nested asset under path.posix", () => {+ const root = "/project";+ const candidate = posix.join(root, "assets/a.png");+ expect(isWithinProjectRoot(root, candidate, posix)).toBe(true);+ });++ it("allows the root itself", () => {+ expect(isWithinProjectRoot("/project", "/project", posix)).toBe(true);+ });+});diff --git a/packages/parsers/src/assetResolution.ts b/packages/parsers/src/assetResolution.tsindex b14212aa52..0378a9d7ab 100644--- a/packages/parsers/src/assetResolution.ts+++ b/packages/parsers/src/assetResolution.ts@@ -2,6 +2,14 @@ import { existsSync } from "node:fs";import { isAbsolute, join, posix, relative, resolve, sep } from "node:path";import { decodeUrlPathVariants } from "./composition.js";+/** The subset of `node:path` that `isWithinProjectRoot` needs to run under+ * an injected platform (tests pass `path.win32` / `path.posix`). */+interface PathModuleLike {+ resolve: (...segments: string[]) => string;+ relative: (from: string, to: string) => string;+ isAbsolute: (path: string) => boolean;+}+/*** Shared local-asset resolution helpers for every package that maps* composition asset URLs to files on disk (lint project rules, the HEVC@@ -115,10 +123,22 @@ export function cleanAssetUrl(url: string): string {return url.trim().split(/[?#]/, 1)[0] ?? "";}-export function isWithinProjectRoot(projectDir: string, candidate: string): boolean {- const projectRoot = resolve(projectDir);- const relativePath = relative(projectRoot, candidate);- return relativePath === "" || (!relativePath.startsWith("..") && !isAbsolute(relativePath));+/**+ * `pathModule` defaults to the host's native `node:path`, so every existing+ * caller gets its actual OS's separator and drive-letter rules unchanged.+ * Tests inject `path.win32` / `path.posix` to exercise both platforms' rules+ * from a single OS (same pattern as producer/fileServer.ts's `isPathInside`).+ */+export function isWithinProjectRoot(+ projectDir: string,+ candidate: string,+ pathModule: PathModuleLike = { resolve, relative, isAbsolute },+): boolean {+ const projectRoot = pathModule.resolve(projectDir);+ const relativePath = pathModule.relative(projectRoot, candidate);+ return (+ relativePath === "" || (!relativePath.startsWith("..") && !pathModule.isAbsolute(relativePath))+ );}function addCandidate(candidates: string[], candidate: string): void {