From 983e865ad7ac8e6e6737eff229949d181934ed39 Mon Sep 17 00:00:00 2001 From: James Russo Date: Tue, 10 Nov 2026 14:30:10 +0000 Subject: [PATCH] fix(studio-server): thumbnail origin from the server, sandbox previews from other sites (#7492) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(studio-server): thumbnail origin from the server, sandbox previews from other sites The thumbnail route builds the headless browser's URL from the server's own listening origin (a new optional `serverOrigin` on the adapter, wired in the CLI preview server and the Vite dev host) instead of the request's Host header. Hosts that report no origin fall back to a loopback Host only. Preview responses (bundled, sub-composition and project files) opened from another site carry `Content-Security-Policy: sandbox allow-scripts` and `Vary: Sec-Fetch-Site`. Studio's same-origin iframe, browser automation and non-browser clients are unchanged. Co-Authored-By: Claude Opus 5.5 * fix(studio): build the thumbnail origin from a hostname bind name With HYPERFRAMES_PREVIEW_HOST set to a hostname, the listening address is the IP it resolved to, and the Host check accepts the bind name, not that IP. The thumbnail browser then loaded a 403 page. Use the bind name when it is a hostname; IP and wildcard binds keep the listening address. — Rames Jusso Co-Authored-By: Claude Opus 5.5 * style(studio): drop the serverOrigin comment that put it over the package's comment share The hostname-bind rule is stated by its test name in serverOrigin.test.ts. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../src/commands/preview.startFailure.test.ts | 1 + packages/cli/src/commands/preview.ts | 15 +++- packages/cli/src/server/studioServer.test.ts | 8 ++ packages/cli/src/server/studioServer.ts | 3 + packages/studio-server/src/createStudioApi.ts | 10 +++ .../src/helpers/serverOrigin.test.ts | 33 +++++++ .../studio-server/src/helpers/serverOrigin.ts | 29 ++++++ packages/studio-server/src/index.ts | 1 + .../src/routes/preview.sandbox.test.ts | 78 ++++++++++++++++ .../src/routes/thumbnail.origin.test.ts | 88 +++++++++++++++++++ .../studio-server/src/routes/thumbnail.ts | 5 +- packages/studio-server/src/types.ts | 2 + packages/studio/vite.adapter.ts | 6 ++ 13 files changed, 275 insertions(+), 4 deletions(-) create mode 100644 packages/studio-server/src/helpers/serverOrigin.test.ts create mode 100644 packages/studio-server/src/helpers/serverOrigin.ts create mode 100644 packages/studio-server/src/routes/preview.sandbox.test.ts create mode 100644 packages/studio-server/src/routes/thumbnail.origin.test.ts diff --git a/packages/cli/src/commands/preview.startFailure.test.ts b/packages/cli/src/commands/preview.startFailure.test.ts index 4a302805fd..4ea9fe95a0 100644 --- a/packages/cli/src/commands/preview.startFailure.test.ts +++ b/packages/cli/src/commands/preview.startFailure.test.ts @@ -22,6 +22,7 @@ vi.mock("@clack/prompts", async (importOriginal) => { vi.mock("../server/studioServer.js", () => ({ resolveStudioBundle: () => ({ available: true, checkedPaths: [] }), loadPreviewServerBuildSignature: async () => "test", + originForListeningAddress: () => undefined, createStudioServer: () => ({ app: { fetch: () => new Response() }, watcher: { close: vi.fn() }, diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index 4b909468a8..e2ce0c36c8 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -1589,8 +1589,12 @@ export async function runEmbeddedMode( startPort: number, options?: EmbeddedStudioOptions, ): Promise { - const { createStudioServer, loadPreviewServerBuildSignature, resolveStudioBundle } = - await import("../server/studioServer.js"); + const { + createStudioServer, + loadPreviewServerBuildSignature, + originForListeningAddress, + resolveStudioBundle, + } = await import("../server/studioServer.js"); const pName = options?.projectName ?? basename(dir); const studioBundle = resolveStudioBundle(); @@ -1687,7 +1691,12 @@ export async function runEmbeddedMode( } const url = `http://localhost:${result.port}`; - listening = `http://127.0.0.1:${result.port}`; + listening = + originForListeningAddress( + result.server.address(), + "http", + process.env.HYPERFRAMES_PREVIEW_HOST, + ) ?? `http://127.0.0.1:${result.port}`; if (options?.json) { writeLifecycleJson(foregroundPreviewReadyPayload(pName, url, dir, process.pid)); } else { diff --git a/packages/cli/src/server/studioServer.test.ts b/packages/cli/src/server/studioServer.test.ts index 1c1b400a64..091843813f 100644 --- a/packages/cli/src/server/studioServer.test.ts +++ b/packages/cli/src/server/studioServer.test.ts @@ -795,6 +795,14 @@ describe("host guarding on identity-bearing responses", () => { expect(await res.text()).not.toContain('distinctId":"'); }); + it("gives the thumbnail browser the origin it listens on, not the request's", async () => { + let listening: string | undefined; + server = createStudioServer({ projectDir: tmpProject(), origin: () => listening }); + expect(server.adapter.serverOrigin?.()).toBeUndefined(); + listening = "http://127.0.0.1:3002"; + expect(server.adapter.serverOrigin?.()).toBe("http://127.0.0.1:3002"); + }); + it("serves the identity endpoint on a loopback Host", async () => { server = createStudioServer({ projectDir: tmpProject() }); const res = await server.app.request("/api/telemetry-identity", { diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index 691f48298f..b55446d66b 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -94,6 +94,8 @@ import { } from "../browser/gpuPolicy.js"; import { loadSharpInBackground } from "../utils/optionalPackages.js"; +export { originForListeningAddress } from "@hyperframes/studio-server"; + const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json"; // Under preview.ts's 3s process-exit watchdog, so shutdown() always returns @@ -605,6 +607,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { runtimeUrl: "/api/runtime.js", gsapLocalRoot: gsapVendorDir ? GSAP_LOCAL_ROOT : undefined, + serverOrigin: () => options.origin?.(), rendersDir: () => join(projectDir, "renders"), diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts index 4c473bc759..06cec729b7 100644 --- a/packages/studio-server/src/createStudioApi.ts +++ b/packages/studio-server/src/createStudioApi.ts @@ -38,6 +38,15 @@ async function answerRefusedFrameWithPage(c: Context, next: Next) { }); } +async function sandboxPreviewOpenedFromAnotherSite(c: Context, next: Next) { + await next(); + c.header("Vary", "Sec-Fetch-Site", { append: true }); + const site = c.req.header("sec-fetch-site"); + if (site === "cross-site" || site === "same-site") { + c.header("Content-Security-Policy", "sandbox allow-scripts"); + } +} + function urlHost(url: string): string | undefined { try { return new URL(url).host || undefined; @@ -60,6 +69,7 @@ export interface StudioApiOptions { export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOptions = {}): Hono { const api = new Hono(); + api.use("/projects/:id/preview/*", sandboxPreviewOpenedFromAnotherSite); // This API is unauthenticated and simple cross-origin POSTs need no // preflight, so the guard rejects writes the shared predicate refuses. api.use(async function rejectCrossOriginWrites(c, next) { diff --git a/packages/studio-server/src/helpers/serverOrigin.test.ts b/packages/studio-server/src/helpers/serverOrigin.test.ts new file mode 100644 index 0000000000..1e4db335cd --- /dev/null +++ b/packages/studio-server/src/helpers/serverOrigin.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import { originForListeningAddress } from "./serverOrigin"; + +describe("originForListeningAddress", () => { + it.each([ + [{ address: "127.0.0.1", family: "IPv4", port: 3002 }, "http://127.0.0.1:3002"], + [{ address: "0.0.0.0", family: "IPv4", port: 3002 }, "http://127.0.0.1:3002"], + [{ address: "::", family: "IPv6", port: 3002 }, "http://127.0.0.1:3002"], + [{ address: "::1", family: "IPv6", port: 3002 }, "http://[::1]:3002"], + [{ address: "192.168.1.20", family: "IPv4", port: 5190 }, "http://192.168.1.20:5190"], + ])("reaches %o at %s", (address, origin) => { + expect(originForListeningAddress(address)).toBe(origin); + }); + + it("reaches a hostname bind by that name, which the Host check accepts", () => { + const address = { address: "192.168.1.20", family: "IPv4", port: 5190 }; + expect(originForListeningAddress(address, "http", "mybox.lan")).toBe("http://mybox.lan:5190"); + expect(originForListeningAddress(address, "http", " mybox.lan ")).toBe("http://mybox.lan:5190"); + }); + + it.each(["192.168.1.20", "0.0.0.0", "::", "*", "", undefined])( + "keeps the listening address for bind %s", + (bindHost) => { + const address = { address: "192.168.1.20", family: "IPv4", port: 5190 }; + expect(originForListeningAddress(address, "http", bindHost)).toBe("http://192.168.1.20:5190"); + }, + ); + + it("has no origin for a pipe or a server that is not listening", () => { + expect(originForListeningAddress("/tmp/studio.sock")).toBeUndefined(); + expect(originForListeningAddress(null)).toBeUndefined(); + }); +}); diff --git a/packages/studio-server/src/helpers/serverOrigin.ts b/packages/studio-server/src/helpers/serverOrigin.ts new file mode 100644 index 0000000000..6762e47da9 --- /dev/null +++ b/packages/studio-server/src/helpers/serverOrigin.ts @@ -0,0 +1,29 @@ +import { isIP, type AddressInfo } from "node:net"; + +export function originForListeningAddress( + address: AddressInfo | string | null | undefined, + protocol: "http" | "https" = "http", + bindHost?: string, +): string | undefined { + if (!address || typeof address === "string") return undefined; + const bindName = bindHost?.trim() ?? ""; + if (bindName !== "" && bindName !== "*" && isIP(bindName) === 0) { + return `${protocol}://${bindName}:${address.port}`; + } + const unspecified = address.address === "0.0.0.0" || address.address === "::"; + const host = unspecified ? "127.0.0.1" : address.address; + return `${protocol}://${host.includes(":") ? `[${host}]` : host}:${address.port}`; +} + +// Anchored at both ends: a `user@host` or path after the port would move the URL built from it. +const LOOPBACK_HOST_HEADER = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d{1,5})?$/i; +const IN_PROCESS_ORIGIN = "http://localhost"; + +export function thumbnailPreviewOrigin( + serverOrigin: string | undefined, + hostHeader: string | undefined, +): string | null { + if (serverOrigin) return serverOrigin; + if (hostHeader === undefined) return IN_PROCESS_ORIGIN; + return LOOPBACK_HOST_HEADER.test(hostHeader) ? `http://${hostHeader}` : null; +} diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts index 1c8b218509..2ad1e7afa3 100644 --- a/packages/studio-server/src/index.ts +++ b/packages/studio-server/src/index.ts @@ -48,6 +48,7 @@ export { PREVIEW_BUNDLE_OPTIONS } from "./routes/preview.js"; export { createPreviewDocumentStore } from "./helpers/previewDocumentStore.js"; export { getMimeType, MIME_TYPES } from "./helpers/mime.js"; export { decodeWellFormedEscapes, requestSubPath } from "./helpers/requestSubPath.js"; +export { originForListeningAddress } from "./helpers/serverOrigin.js"; export { MAX_OPEN_MEDIA_RANGE_BYTES, openRangeEnd } from "./helpers/mediaRange.js"; export { consumeFileWriteReceipt, diff --git a/packages/studio-server/src/routes/preview.sandbox.test.ts b/packages/studio-server/src/routes/preview.sandbox.test.ts new file mode 100644 index 0000000000..5741855660 --- /dev/null +++ b/packages/studio-server/src/routes/preview.sandbox.test.ts @@ -0,0 +1,78 @@ +// @vitest-environment node +import { afterAll, describe, expect, it } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createStudioApi } from "../createStudioApi"; +import type { StudioApiAdapter } from "../types"; + +const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-sandbox-")); +writeFileSync( + join(projectDir, "index.html"), + '
', +); +writeFileSync(join(projectDir, "page.html"), ""); +writeFileSync( + join(projectDir, "icon.svg"), + '', +); +afterAll(() => rmSync(projectDir, { recursive: true, force: true })); + +const adapter: StudioApiAdapter = { + listProjects: () => [], + resolveProject: async (id: string) => ({ id, dir: projectDir }), + bundle: async () => null, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => join(projectDir, "renders"), + startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }), +}; +const api = createStudioApi(adapter); + +const SANDBOX = "sandbox allow-scripts"; +const routes = [ + ["a project HTML file", "/projects/demo/preview/page.html", "text/html"], + ["a project SVG file", "/projects/demo/preview/icon.svg", "image/svg+xml"], + ["the bundled preview", "/projects/demo/preview", "text/html"], + ["a sub-composition preview", "/projects/demo/preview/comp/page.html", "text/html"], +] as const; + +async function get(path: string, site?: string) { + return api.request(`http://localhost${path}`, { + headers: site === undefined ? {} : { "sec-fetch-site": site }, + }); +} + +describe.each(routes)("%s", (_name, path, type) => { + it.each(["cross-site", "same-site"])("is sandboxed when the request is %s", async (site) => { + const res = await get(path, site); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain(type); + expect(res.headers.get("content-security-policy")).toBe(SANDBOX); + expect(res.headers.get("vary")).toBe("Sec-Fetch-Site"); + }); + + it.each([["same-origin"], ["none"], [undefined]])( + "keeps its origin when Sec-Fetch-Site is %s", + async (site) => { + const res = await get(path, site); + expect(res.status).toBe(200); + expect(res.headers.get("content-security-policy")).toBeNull(); + expect(res.headers.get("vary")).toBe("Sec-Fetch-Site"); + }, + ); +}); + +describe("a revalidated preview", () => { + it("still names Sec-Fetch-Site in Vary and carries the sandbox on a 304", async () => { + const first = await get("/projects/demo/preview", "same-origin"); + const etag = first.headers.get("etag"); + expect(etag).toBeTruthy(); + const res = await api.request("http://localhost/projects/demo/preview", { + headers: { "sec-fetch-site": "cross-site", "if-none-match": etag! }, + }); + expect(res.status).toBe(304); + expect(res.headers.get("vary")).toBe("Sec-Fetch-Site"); + expect(res.headers.get("content-security-policy")).toBe(SANDBOX); + }); +}); diff --git a/packages/studio-server/src/routes/thumbnail.origin.test.ts b/packages/studio-server/src/routes/thumbnail.origin.test.ts new file mode 100644 index 0000000000..75f0e49153 --- /dev/null +++ b/packages/studio-server/src/routes/thumbnail.origin.test.ts @@ -0,0 +1,88 @@ +// @vitest-environment node +import { afterEach, describe, expect, it, vi } from "vitest"; +import { Hono } from "hono"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { registerThumbnailRoutes } from "./thumbnail"; +import type { StudioApiAdapter } from "../types"; + +vi.mock("../helpers/proxyTranscoder.js", async (importOriginal) => ({ + ...(await importOriginal()), + proxyActivityMark: vi.fn(() => "0"), +})); + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function setup(serverOrigin?: string) { + const projectDir = mkdtempSync(join(tmpdir(), "hf-thumbnail-origin-")); + dirs.push(projectDir); + writeFileSync(join(projectDir, "index.html"), '
'); + const visited: string[] = []; + const adapter: StudioApiAdapter = { + listProjects: () => [], + resolveProject: async (id: string) => ({ id, dir: projectDir }), + bundle: async () => null, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => join(projectDir, "renders"), + startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/o.mp4" }), + ...(serverOrigin !== undefined && { serverOrigin: () => serverOrigin }), + generateThumbnail: async ({ previewUrl }) => { + visited.push(previewUrl); + return Buffer.from("thumb"); + }, + }; + const app = new Hono(); + registerThumbnailRoutes(app, adapter); + // Each request a fresh `t`, so none is answered from the previous one's cache. + let seek = 0; + const request = (host: string) => + app.request(`http://localhost/projects/demo/thumbnail/index.html?t=${(seek += 0.25)}`, { + headers: { host }, + }); + return { request, visited }; +} + +describe("the thumbnail browser's destination", () => { + it("is the server's own origin, whatever Host the request names", async () => { + const { request, visited } = setup("http://127.0.0.1:3002"); + + const res = await request("other.example:3002"); + + expect(res.status).toBe(200); + expect(visited).toHaveLength(1); + expect(new URL(visited[0]!).origin).toBe("http://127.0.0.1:3002"); + expect(visited[0]).toMatch(/^http:\/\/127\.0\.0\.1:3002\/api\/projects\/demo\/preview\?/); + }); + + it("never comes from a non-loopback Host when the host reports no origin", async () => { + const { request, visited } = setup(); + + for (const host of [ + "other.example:3002", + "127.0.0.1:3002@other.example", + "localhost.other.example", + "127.0.0.1.other.example:3002", + ]) { + expect((await request(host)).status).toBe(400); + } + expect(visited).toEqual([]); + }); + + it("is a loopback Host as given when the host reports no origin", async () => { + const { request, visited } = setup(); + + for (const host of ["localhost:3002", "127.0.0.1:4100", "[::1]:3002"]) { + expect((await request(host)).status).toBe(200); + } + expect(visited.map((url) => new URL(url).host)).toEqual([ + "localhost:3002", + "127.0.0.1:4100", + "[::1]:3002", + ]); + }); +}); diff --git a/packages/studio-server/src/routes/thumbnail.ts b/packages/studio-server/src/routes/thumbnail.ts index 7d355a0c17..61e1faf3b3 100644 --- a/packages/studio-server/src/routes/thumbnail.ts +++ b/packages/studio-server/src/routes/thumbnail.ts @@ -31,6 +31,7 @@ import { } from "../helpers/safePath.js"; import { proxyActivityMark } from "../helpers/proxyTranscoder.js"; import { PREVIEW_CAPTURE_PARAM } from "./preview.js"; +import { thumbnailPreviewOrigin } from "../helpers/serverOrigin.js"; const THUMBNAIL_CACHE_VERSION = "v5"; const THUMBNAIL_MAX_OUTPUT_WIDTH = 240; @@ -186,7 +187,9 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v const motion = manifestKey(join(project.dir, STUDIO_MOTION_PATH)); sourceMtime = Math.max(sourceMtime, manualEdits.mtimeMs, motion.mtimeMs); - const projectUrl = `http://${c.req.header("host")}/api/projects/${encodeURIComponent(project.id)}`; + const origin = thumbnailPreviewOrigin(adapter.serverOrigin?.(), c.req.header("host")); + if (!origin) return c.json({ error: "thumbnail needs a loopback Host" }, 400); + const projectUrl = `${origin}/api/projects/${encodeURIComponent(project.id)}`; const previewPath = compPath === "index.html" ? `${projectUrl}/preview` diff --git a/packages/studio-server/src/types.ts b/packages/studio-server/src/types.ts index 8a455a133d..56d966e935 100644 --- a/packages/studio-server/src/types.ts +++ b/packages/studio-server/src/types.ts @@ -229,6 +229,8 @@ export interface StudioApiAdapter { jobId: string; }) => MediaProcessingJobState; + serverOrigin?: () => string | undefined; + /** Optional: generate a thumbnail at the route's explicit output dimensions. */ generateThumbnail?: (opts: { project: ResolvedProject; diff --git a/packages/studio/vite.adapter.ts b/packages/studio/vite.adapter.ts index c54a8839f7..df7fd97995 100644 --- a/packages/studio/vite.adapter.ts +++ b/packages/studio/vite.adapter.ts @@ -23,6 +23,7 @@ import { DEFAULT_HISTORY_ROOT, openProjectHistory, historyCache, + originForListeningAddress, } from "@hyperframes/studio-server"; import { encoderJobOptions } from "@hyperframes/studio-server/encoder-options"; import type { RegistryItem } from "@hyperframes/core/registry"; @@ -306,6 +307,11 @@ export function createViteAdapter( }, runtimeUrl: "/api/runtime.js", + serverOrigin: () => + originForListeningAddress( + server.httpServer?.address(), + server.config.server.https ? "https" : "http", + ), rendersDir: () => resolve(dataDir, "../renders"),