From 3cff050e8069529ca82f251f028d851278209295 Mon Sep 17 00:00:00 2001 From: James Date: Wed, 11 Nov 2026 00:19:59 +0000 Subject: [PATCH 1/6] fix(studio-server): run thumbnail captures in an opaque origin The thumbnail renderer loads each composition as a top-level page, so its scripts ran on the Studio's origin. The capture document (`?hf-capture`) now carries `Content-Security-Policy: sandbox allow-scripts`, so those scripts get an opaque origin. An opaque page's CORS-mode loads fail without a CORS header. The renderer that opened the page is trusted, so it adds `Access-Control-Allow-Origin: null` itself, over that page's own DevTools session, to the loads a frame needs: - fonts, module scripts and images; - the `.html` scenes, `.json` and `.cube` files the runtime fetches. Only GETs of the project's preview files qualify, matched by file type. Both thumbnail renderers do this: the CLI's and the Vite dev server's. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/server/studioServer.test.ts | 35 +++++ packages/cli/src/server/studioServer.ts | 3 + packages/studio-server/src/createStudioApi.ts | 14 +- .../src/helpers/captureLoads.test.ts | 120 ++++++++++++++++++ .../studio-server/src/helpers/captureLoads.ts | 102 +++++++++++++++ packages/studio-server/src/index.ts | 1 + .../src/routes/preview.sandbox.test.ts | 29 +++++ packages/studio/vite.browser.test.ts | 20 ++- packages/studio/vite.browser.ts | 3 + 9 files changed, 322 insertions(+), 5 deletions(-) create mode 100644 packages/studio-server/src/helpers/captureLoads.test.ts create mode 100644 packages/studio-server/src/helpers/captureLoads.ts diff --git a/packages/cli/src/server/studioServer.test.ts b/packages/cli/src/server/studioServer.test.ts index 6d08dad7a71..4f7cf8a08c9 100644 --- a/packages/cli/src/server/studioServer.test.ts +++ b/packages/cli/src/server/studioServer.test.ts @@ -761,6 +761,41 @@ describe("Studio thumbnail capture", () => { expect(clears[0]).toBeGreaterThan(screenshot.mock.invocationCallOrder[0]!); }); + it("grants the capture page's loads on its own session before it navigates", async () => { + const calls: string[] = []; + const session = { + send: vi.fn(async (method: string) => void calls.push(method)), + on: vi.fn(), + }; + const page = new Proxy( + { + createCDPSession: async () => session, + goto: async () => void calls.push("goto"), + screenshot: async () => Buffer.from("jpeg"), + }, + { + get: (target, key) => + key === "then" + ? undefined + : key in target + ? target[key as keyof typeof target] + : async () => {}, + }, + ); + engineState.acquireBrowser = async () => ({ + browser: { connected: true, newPage: async () => page, on: () => {} }, + release: async () => {}, + }); + const dir = tmpProject(); + server = createStudioServer({ projectDir: dir }); + const previewUrl = "http://127.0.0.1:3002/api/projects/demo/preview?hf-capture=1"; + await expect( + server.adapter.generateThumbnail?.({ ...opts(dir), previewUrl }), + ).resolves.toBeInstanceOf(Buffer); + expect(calls.slice(0, 2)).toEqual(["Fetch.enable", "goto"]); + expect(session.on).toHaveBeenCalledWith("Fetch.requestPaused", expect.any(Function)); + }); + it("reuses the cached project signature instead of walking the project per thumbnail", async () => { fakePageBrowser(); const dir = tmpProject(); diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index 9389fe4accf..8bb09d58d64 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -63,6 +63,7 @@ import { PREVIEW_BUNDLE_OPTIONS, createPreviewDocumentStore, thumbnailDeviceScaleFactor, + grantCaptureLoads, type ResolvedProject, type RenderJobState, type BackgroundRemovalRender, @@ -804,6 +805,8 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { opts.seekTime, async (page) => { await page.setViewport(viewport); + // The capture document runs in an opaque origin; this page's session grants its fonts and scenes. + await grantCaptureLoads(await page.createCDPSession(), opts.previewUrl); await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 }); await assertWebGpuAdapterAvailable( page, diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts index b8ae0b71ac8..7b129412199 100644 --- a/packages/studio-server/src/createStudioApi.ts +++ b/packages/studio-server/src/createStudioApi.ts @@ -2,7 +2,7 @@ import { Hono, type Context, type Next } from "hono"; import type { StudioApiAdapter } from "./types.js"; import { registerProjectRoutes } from "./routes/projects.js"; import { registerFileRoutes } from "./routes/files.js"; -import { registerPreviewRoutes } from "./routes/preview.js"; +import { PREVIEW_CAPTURE_PARAM, registerPreviewRoutes } from "./routes/preview.js"; import { registerLintRoutes } from "./routes/lint.js"; import { registerRenderRoutes } from "./routes/render.js"; import { registerImageThumbnailRoutes } from "./routes/imageThumbnail.js"; @@ -43,10 +43,16 @@ const fromAnotherSite = (c: Context) => { return site === "cross-site" || site === "same-site"; }; -async function sandboxPreviewOpenedFromAnotherSite(c: Context, next: Next) { +// A thumbnail capture runs every composition with no user action, so its document gets an opaque +// origin too: its scripts reach nothing of this API. The renderer grants the loads it still needs +// (grantCaptureLoads). +const forCapture = (c: Context) => c.req.query(PREVIEW_CAPTURE_PARAM) !== undefined; + +async function sandboxPreviewForAnotherSiteOrCapture(c: Context, next: Next) { await next(); c.header("Vary", "Sec-Fetch-Site", { append: true }); - if (fromAnotherSite(c)) c.header("Content-Security-Policy", "sandbox allow-scripts"); + if (fromAnotherSite(c) || forCapture(c)) + c.header("Content-Security-Policy", "sandbox allow-scripts"); } async function refuseThumbnailForAnotherSite(c: Context, next: Next) { @@ -77,7 +83,7 @@ export interface StudioApiOptions { export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOptions = {}): Hono { const api = new Hono(); - api.use("/projects/:id/preview/*", sandboxPreviewOpenedFromAnotherSite); + api.use("/projects/:id/preview/*", sandboxPreviewForAnotherSiteOrCapture); api.use("/projects/:id/thumbnail/*", refuseThumbnailForAnotherSite); // This API is unauthenticated and simple cross-origin POSTs need no // preflight, so the guard rejects writes the shared predicate refuses. diff --git a/packages/studio-server/src/helpers/captureLoads.test.ts b/packages/studio-server/src/helpers/captureLoads.test.ts new file mode 100644 index 00000000000..fb8b37d12f5 --- /dev/null +++ b/packages/studio-server/src/helpers/captureLoads.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it, vi } from "vitest"; +import { captureLoadGetsCors, grantCaptureLoads, type CaptureCdpSession } from "./captureLoads"; + +const ORIGIN = "http://127.0.0.1:3002"; +const PREVIEW = `${ORIGIN}/api/projects/demo/preview`; +const CAPTURE = `${PREVIEW}/comp/compositions/intro.html?hf-capture=1`; + +describe("captureLoadGetsCors", () => { + it.each([ + ["Font", `${PREVIEW}/assets/brand.woff2`], + ["Font", `${PREVIEW}/fonts/Display.ttf?v=2`], + ["Script", `${PREVIEW}/assets/scene.mjs`], + ["Image", `${PREVIEW}/assets/logo.png`], + ["XHR", `${PREVIEW}/compositions/scene.html`], + ["Fetch", `${PREVIEW}/caption-overrides.json`], + ["XHR", `${PREVIEW}/luts/warm.cube`], + ])("grants a %s load of %s", (resourceType, url) => { + expect(captureLoadGetsCors({ url, method: "GET", resourceType }, CAPTURE)).toBe(true); + }); + + it.each([ + ["XHR", `${PREVIEW}/.env`, "GET"], + ["XHR", `${PREVIEW}/.git/config`, "GET"], + ["Fetch", `${PREVIEW}/notes.txt`, "GET"], + ["Script", `${PREVIEW}/.env`, "GET"], + ["Font", `${PREVIEW}/secrets.txt`, "GET"], + ["Stylesheet", `${PREVIEW}/style.css`, "GET"], + ["XHR", `${ORIGIN}/api/projects/demo/files/index.html`, "GET"], + ["XHR", `${ORIGIN}/api/projects/other/preview/index.html`, "GET"], + ["XHR", `http://127.0.0.1:9999/api/projects/demo/preview/index.html`, "GET"], + ["XHR", `${PREVIEW}/compositions/scene.html`, "PUT"], + ["XHR", `${PREVIEW}/compositions/scene.html`, "POST"], + ])("refuses a %s load of %s (%s)", (resourceType, url, method) => { + expect(captureLoadGetsCors({ url, method, resourceType }, CAPTURE)).toBe(false); + }); + + it("grants nothing for a URL that is not a preview document", () => { + const load = { url: `${PREVIEW}/assets/brand.woff2`, method: "GET", resourceType: "Font" }; + expect(captureLoadGetsCors(load, `${ORIGIN}/api/projects/demo/files/index.html`)).toBe(false); + expect(captureLoadGetsCors(load, "not a url")).toBe(false); + }); +}); + +type Paused = Parameters[1]>[0]; + +function fakeSession() { + let paused: ((event: Paused) => void) | undefined; + const send = vi.fn(async (_method: string, _params?: object) => undefined); + const session: CaptureCdpSession = { + send, + on: (_event, handler) => { + paused = handler; + }, + }; + return { session, send, pause: (event: Paused) => paused?.(event) }; +} + +const response = (url: string, resourceType: string, extra: Partial = {}): Paused => ({ + requestId: "r1", + request: { url, method: "GET" }, + resourceType, + responseStatusCode: 200, + responseHeaders: [{ name: "Content-Type", value: "font/woff2" }], + ...extra, +}); + +describe("grantCaptureLoads", () => { + it("intercepts responses under the project's preview path only", async () => { + const { session, send } = fakeSession(); + await grantCaptureLoads(session, CAPTURE); + const enable = send.mock.calls.find(([method]) => method === "Fetch.enable"); + expect(enable).toBeDefined(); + const { patterns } = enable![1] as { patterns: Array> }; + expect(patterns.length).toBeGreaterThan(0); + for (const pattern of patterns) { + expect(pattern.urlPattern).toBe(`${PREVIEW}/*`); + expect(pattern.requestStage).toBe("Response"); + } + }); + + it("adds the CORS header to a granted load and keeps its own headers", async () => { + const { session, send, pause } = fakeSession(); + await grantCaptureLoads(session, CAPTURE); + pause(response(`${PREVIEW}/assets/brand.woff2`, "Font")); + expect(send).toHaveBeenLastCalledWith("Fetch.continueResponse", { + requestId: "r1", + responseCode: 200, + responseHeaders: [ + { name: "Content-Type", value: "font/woff2" }, + { name: "Access-Control-Allow-Origin", value: "null" }, + { name: "X-Content-Type-Options", value: "nosniff" }, + ], + }); + }); + + it.each([ + ["a file fetch() may not read", response(`${PREVIEW}/.env`, "XHR")], + [ + "a failed load", + response(`${PREVIEW}/assets/brand.woff2`, "Font", { responseStatusCode: 404 }), + ], + [ + "a load that already answers CORS", + response(`${PREVIEW}/assets/brand.woff2`, "Font", { + responseHeaders: [{ name: "access-control-allow-origin", value: "*" }], + }), + ], + ])("passes %s through unchanged", async (_name, event) => { + const { session, send, pause } = fakeSession(); + await grantCaptureLoads(session, CAPTURE); + pause(event); + expect(send).toHaveBeenLastCalledWith("Fetch.continueRequest", { requestId: "r1" }); + }); + + it("does nothing for a URL that is not a preview document", async () => { + const { session, send } = fakeSession(); + await grantCaptureLoads(session, `${ORIGIN}/api/projects/demo/files/index.html`); + expect(send).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/studio-server/src/helpers/captureLoads.ts b/packages/studio-server/src/helpers/captureLoads.ts new file mode 100644 index 00000000000..a3e0d7b6d9c --- /dev/null +++ b/packages/studio-server/src/helpers/captureLoads.ts @@ -0,0 +1,102 @@ +/** + * A thumbnail capture document is served with `Content-Security-Policy: sandbox allow-scripts` + * (createStudioApi), so its scripts run in an opaque origin and cannot use the Studio API. Loads that + * the browser makes in CORS mode then fail too: fonts, module scripts, images drawn for color grading, + * and the runtime's fetch of a nested composition. The renderer that opened the capture page is trusted, + * so it adds the CORS header to those responses itself, for that page only, by the kind of each load. + * Only GETs of the project's own preview files are granted, and `fetch()` reads only the files the + * runtime fetches to draw a frame: `.html` scenes, `.json` and `.cube` LUTs. + */ + +const RUNTIME_READS = /\.(html?|json|cube)$/i; + +/** File kinds an opaque capture page may load with CORS, by Chrome's resource type. Chrome reports + * a page's `fetch()` as `XHR` to the Fetch domain. */ +const CAPTURE_LOADS = new Map([ + ["Font", /\.(woff2?|ttf|otf)$/i], + ["Script", /\.m?js$/i], + ["Image", /\.(png|jpe?g|gif|webp|avif|svg)$/i], + ["Fetch", RUNTIME_READS], + ["XHR", RUNTIME_READS], +]); + +/** `/api/projects//preview/` for a capture URL, or null for any other URL. */ +function previewPrefix(captureUrl: string): string | null { + let url: URL; + try { + url = new URL(captureUrl); + } catch { + return null; + } + const path = /^\/api\/projects\/[^/]+\/preview(?=\/|$)/.exec(url.pathname)?.[0]; + return path ? `${url.origin}${path}/` : null; +} + +export interface CaptureLoad { + url: string; + method: string; + resourceType: string; +} + +/** Whether the capture page at `captureUrl` may read `load` across its opaque origin. */ +export function captureLoadGetsCors(load: CaptureLoad, captureUrl: string): boolean { + const prefix = previewPrefix(captureUrl); + if (!prefix || load.method !== "GET" || !load.url.startsWith(prefix)) return false; + return CAPTURE_LOADS.get(load.resourceType)?.test(new URL(load.url).pathname) ?? false; +} + +type Header = { name: string; value: string }; + +/** The part of a CDP session this needs; puppeteer's `CDPSession` fits it. */ +export interface CaptureCdpSession { + send(method: string, params?: object): Promise; + on( + event: "Fetch.requestPaused", + handler: (event: { + requestId: string; + request: { url: string; method: string }; + resourceType: string; + responseStatusCode?: number; + responseHeaders?: Header[]; + }) => void, + ): unknown; +} + +/** Adds `Access-Control-Allow-Origin: null` to the capture page's loads that `captureLoadGetsCors` + * allows. Call it on the page's own session before navigating, and keep the session for the page's life. */ +export async function grantCaptureLoads(cdp: CaptureCdpSession, captureUrl: string): Promise { + const prefix = previewPrefix(captureUrl); + if (!prefix) return; + cdp.on("Fetch.requestPaused", (event) => { + const headers = event.responseHeaders ?? []; + const status = event.responseStatusCode ?? 0; + const grant = + status >= 200 && + status < 300 && + !headers.some((header) => header.name.toLowerCase() === "access-control-allow-origin") && + captureLoadGetsCors( + { url: event.request.url, method: event.request.method, resourceType: event.resourceType }, + captureUrl, + ); + void ( + grant + ? cdp.send("Fetch.continueResponse", { + requestId: event.requestId, + responseCode: status, + responseHeaders: [ + ...headers, + { name: "Access-Control-Allow-Origin", value: "null" }, + { name: "X-Content-Type-Options", value: "nosniff" }, + ], + }) + : cdp.send("Fetch.continueRequest", { requestId: event.requestId }) + ).catch(() => undefined); + }); + await cdp.send("Fetch.enable", { + patterns: [...CAPTURE_LOADS.keys()].map((resourceType) => ({ + urlPattern: `${prefix}*`, + resourceType, + requestStage: "Response", + })), + }); +} diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts index 2ad1e7afa35..c276c321034 100644 --- a/packages/studio-server/src/index.ts +++ b/packages/studio-server/src/index.ts @@ -59,6 +59,7 @@ export { type FileWriteReceipt, } from "./helpers/fileVersion.js"; export { buildSubCompositionHtml } from "./helpers/subComposition.js"; +export { captureLoadGetsCors, grantCaptureLoads } from "./helpers/captureLoads.js"; export { clearElementScreenshotIsolation, getElementScreenshotClip, diff --git a/packages/studio-server/src/routes/preview.sandbox.test.ts b/packages/studio-server/src/routes/preview.sandbox.test.ts index 5741855660e..c77af212a5f 100644 --- a/packages/studio-server/src/routes/preview.sandbox.test.ts +++ b/packages/studio-server/src/routes/preview.sandbox.test.ts @@ -76,3 +76,32 @@ describe("a revalidated preview", () => { expect(res.headers.get("content-security-policy")).toBe(SANDBOX); }); }); + +describe("a thumbnail capture document", () => { + const captures = [ + ["the bundled preview", "/projects/demo/preview?hf-capture=1"], + ["a sub-composition preview", "/projects/demo/preview/comp/page.html?hf-capture=1"], + ] as const; + + describe.each(captures)("%s", (_name, path) => { + it.each([["same-origin"], ["none"], [undefined]])( + "is sandboxed even 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")).toBe(SANDBOX); + }, + ); + }); + + it("carries the sandbox on a 304", async () => { + const path = "/projects/demo/preview?hf-capture=1"; + const etag = (await get(path, "none")).headers.get("etag"); + expect(etag).toBeTruthy(); + const res = await api.request(`http://localhost${path}`, { + headers: { "sec-fetch-site": "none", "if-none-match": etag! }, + }); + expect(res.status).toBe(304); + expect(res.headers.get("content-security-policy")).toBe(SANDBOX); + }); +}); diff --git a/packages/studio/vite.browser.test.ts b/packages/studio/vite.browser.test.ts index e3a5e205df4..ada156227fd 100644 --- a/packages/studio/vite.browser.test.ts +++ b/packages/studio/vite.browser.test.ts @@ -2,7 +2,9 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } import { join } from "node:path"; const browserMocks = vi.hoisted(() => { + const cdp = { send: vi.fn(async (_method: string) => undefined), on: vi.fn() }; const page = { + createCDPSession: vi.fn(async () => cdp), setViewport: vi.fn(async () => {}), goto: vi.fn(async () => {}), evaluate: vi.fn(async () => undefined), @@ -15,7 +17,7 @@ const browserMocks = vi.hoisted(() => { const sharedBrowser = { connected: true as boolean, newPage }; const launch = vi.fn(async () => sharedBrowser); const versionProbe = vi.fn(() => "150.0.0.0"); - return { launch, newPage, page, sharedBrowser, versionProbe }; + return { cdp, launch, newPage, page, sharedBrowser, versionProbe }; }); vi.mock("puppeteer-core", () => ({ default: { launch: browserMocks.launch } })); @@ -63,6 +65,7 @@ describe("generateThumbnail", () => { browserMocks.newPage.mockClear(); browserMocks.versionProbe.mockClear(); for (const mock of Object.values(browserMocks.page)) mock.mockClear(); + browserMocks.cdp.send.mockClear(); }); afterEach(() => { @@ -105,6 +108,21 @@ describe("generateThumbnail", () => { warn.mockRestore(); }); + it("grants the capture page's loads on its own session before it navigates", async () => { + const previewUrl = "http://127.0.0.1:5190/api/projects/demo/preview?hf-capture=1"; + await expect(generateThumbnail({ ...options(), previewUrl })).resolves.toEqual( + Buffer.from("thumbnail"), + ); + const enable = browserMocks.cdp.send.mock.calls.findIndex( + ([method]) => method === "Fetch.enable", + ); + expect(enable).toBeGreaterThanOrEqual(0); + expect(browserMocks.cdp.send.mock.invocationCallOrder[enable]).toBeLessThan( + browserMocks.page.goto.mock.invocationCallOrder[0]!, + ); + expect(browserMocks.page.goto).toHaveBeenCalledWith(previewUrl, expect.anything()); + }); + it("captures at the route-provided physical output size", async () => { await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail")); diff --git a/packages/studio/vite.browser.ts b/packages/studio/vite.browser.ts index 8584e79f1ad..38dbf43be55 100644 --- a/packages/studio/vite.browser.ts +++ b/packages/studio/vite.browser.ts @@ -6,6 +6,7 @@ import { homedir } from "node:os"; import { join, win32 as pathWin32 } from "node:path"; import { getElementScreenshotClip, + grantCaptureLoads, thumbnailDeviceScaleFactor, type ScreenshotClip, } from "@hyperframes/studio-server"; @@ -227,6 +228,8 @@ async function prepareThumbnailPage( height: opts.height, deviceScaleFactor: thumbnailDeviceScaleFactor(opts), }); + // The capture document runs in an opaque origin; this page's session grants its fonts and scenes. + await grantCaptureLoads(await page.createCDPSession(), opts.previewUrl); await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 }); await page.evaluate(() => { document.documentElement.style.background = "#1c2028"; From 1bcc2be98a057047e17ae54502ea00465179cf26 Mon Sep 17 00:00:00 2001 From: James Date: Wed, 11 Nov 2026 00:28:08 +0000 Subject: [PATCH 2/6] fix(studio-server): let an opaque capture wait for a video's preview copy A video the browser cannot decode is drawn from its `?hf-proxy=` copy. The runtime waits for that copy with a ranged fetch, preflighted when it carries the priority header. In the opaque capture page both failed, so each such thumbnail fell back to a still after about five seconds of retries. The renderer now answers that preflight itself. It also exposes the copy's status headers to the wait, for video files under the preview path only. Co-Authored-By: Claude Opus 5.5 --- .../src/helpers/captureLoads.test.ts | 64 +++++++++-- .../studio-server/src/helpers/captureLoads.ts | 105 +++++++++++++----- packages/studio-server/src/index.ts | 2 +- 3 files changed, 134 insertions(+), 37 deletions(-) diff --git a/packages/studio-server/src/helpers/captureLoads.test.ts b/packages/studio-server/src/helpers/captureLoads.test.ts index fb8b37d12f5..c4f32481770 100644 --- a/packages/studio-server/src/helpers/captureLoads.test.ts +++ b/packages/studio-server/src/helpers/captureLoads.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it, vi } from "vitest"; -import { captureLoadGetsCors, grantCaptureLoads, type CaptureCdpSession } from "./captureLoads"; +import { captureLoadGrant, grantCaptureLoads, type CaptureCdpSession } from "./captureLoads"; const ORIGIN = "http://127.0.0.1:3002"; const PREVIEW = `${ORIGIN}/api/projects/demo/preview`; const CAPTURE = `${PREVIEW}/comp/compositions/intro.html?hf-capture=1`; -describe("captureLoadGetsCors", () => { +describe("captureLoadGrant", () => { it.each([ ["Font", `${PREVIEW}/assets/brand.woff2`], ["Font", `${PREVIEW}/fonts/Display.ttf?v=2`], @@ -14,8 +14,16 @@ describe("captureLoadGetsCors", () => { ["XHR", `${PREVIEW}/compositions/scene.html`], ["Fetch", `${PREVIEW}/caption-overrides.json`], ["XHR", `${PREVIEW}/luts/warm.cube`], - ])("grants a %s load of %s", (resourceType, url) => { - expect(captureLoadGetsCors({ url, method: "GET", resourceType }, CAPTURE)).toBe(true); + ])("lets the frame read a %s load of %s", (resourceType, url) => { + expect(captureLoadGrant({ url, method: "GET", resourceType }, CAPTURE)).toBe("read"); + }); + + it("answers the runtime's wait for a video's preview copy and its preflight", () => { + const url = `${PREVIEW}/assets/clip.mov?hf-proxy=h264&hf-proxy-box=1448x724`; + expect(captureLoadGrant({ url, method: "GET", resourceType: "XHR" }, CAPTURE)).toBe("proxy"); + expect(captureLoadGrant({ url, method: "OPTIONS", resourceType: "XHR" }, CAPTURE)).toBe( + "preflight", + ); }); it.each([ @@ -30,14 +38,20 @@ describe("captureLoadGetsCors", () => { ["XHR", `http://127.0.0.1:9999/api/projects/demo/preview/index.html`, "GET"], ["XHR", `${PREVIEW}/compositions/scene.html`, "PUT"], ["XHR", `${PREVIEW}/compositions/scene.html`, "POST"], + ["XHR", `${PREVIEW}/compositions/scene.html`, "OPTIONS"], + ["XHR", `${PREVIEW}/assets/clip.mov`, "GET"], + ["XHR", `${PREVIEW}/.env?hf-proxy=h264`, "GET"], + ["XHR", `${PREVIEW}/.env?hf-proxy=h264`, "OPTIONS"], + ["XHR", `${PREVIEW}/assets/clip.mov?hf-proxy=h264`, "PUT"], + ["Media", `${PREVIEW}/assets/clip.mov?hf-proxy=h264`, "GET"], ])("refuses a %s load of %s (%s)", (resourceType, url, method) => { - expect(captureLoadGetsCors({ url, method, resourceType }, CAPTURE)).toBe(false); + expect(captureLoadGrant({ url, method, resourceType }, CAPTURE)).toBeNull(); }); it("grants nothing for a URL that is not a preview document", () => { const load = { url: `${PREVIEW}/assets/brand.woff2`, method: "GET", resourceType: "Font" }; - expect(captureLoadGetsCors(load, `${ORIGIN}/api/projects/demo/files/index.html`)).toBe(false); - expect(captureLoadGetsCors(load, "not a url")).toBe(false); + expect(captureLoadGrant(load, `${ORIGIN}/api/projects/demo/files/index.html`)).toBeNull(); + expect(captureLoadGrant(load, "not a url")).toBeNull(); }); }); @@ -93,6 +107,42 @@ describe("grantCaptureLoads", () => { }); }); + it("exposes the preview copy's progress headers to the runtime's wait", async () => { + const { session, send, pause } = fakeSession(); + await grantCaptureLoads(session, CAPTURE); + pause( + response(`${PREVIEW}/assets/clip.mov?hf-proxy=h264`, "XHR", { + responseStatusCode: 202, + responseHeaders: [{ name: "Retry-After", value: "2" }], + }), + ); + expect(send).toHaveBeenLastCalledWith("Fetch.continueResponse", { + requestId: "r1", + responseCode: 202, + responseHeaders: expect.arrayContaining([ + { name: "Access-Control-Allow-Origin", value: "null" }, + { name: "Access-Control-Expose-Headers", value: expect.stringContaining("Retry-After") }, + ]), + }); + }); + + it("answers the wait's preflight itself, whatever the server said", async () => { + const { session, send, pause } = fakeSession(); + await grantCaptureLoads(session, CAPTURE); + pause({ + ...response(`${PREVIEW}/assets/clip.mov?hf-proxy=h264`, "XHR", { responseStatusCode: 404 }), + request: { url: `${PREVIEW}/assets/clip.mov?hf-proxy=h264`, method: "OPTIONS" }, + }); + expect(send).toHaveBeenLastCalledWith("Fetch.fulfillRequest", { + requestId: "r1", + responseCode: 204, + responseHeaders: expect.arrayContaining([ + { name: "Access-Control-Allow-Origin", value: "null" }, + { name: "Access-Control-Allow-Methods", value: "GET" }, + ]), + }); + }); + it.each([ ["a file fetch() may not read", response(`${PREVIEW}/.env`, "XHR")], [ diff --git a/packages/studio-server/src/helpers/captureLoads.ts b/packages/studio-server/src/helpers/captureLoads.ts index a3e0d7b6d9c..797306b8d0b 100644 --- a/packages/studio-server/src/helpers/captureLoads.ts +++ b/packages/studio-server/src/helpers/captureLoads.ts @@ -1,17 +1,20 @@ +import { PREVIEW_PROXY_PRIORITY_HEADER, PREVIEW_PROXY_PROGRESS_HEADER } from "@hyperframes/core"; + /** * A thumbnail capture document is served with `Content-Security-Policy: sandbox allow-scripts` * (createStudioApi), so its scripts run in an opaque origin and cannot use the Studio API. Loads that * the browser makes in CORS mode then fail too: fonts, module scripts, images drawn for color grading, - * and the runtime's fetch of a nested composition. The renderer that opened the capture page is trusted, - * so it adds the CORS header to those responses itself, for that page only, by the kind of each load. - * Only GETs of the project's own preview files are granted, and `fetch()` reads only the files the - * runtime fetches to draw a frame: `.html` scenes, `.json` and `.cube` LUTs. + * the runtime's fetch of a nested composition, and its wait for a video's preview copy. The renderer + * that opened the capture page is trusted, so it adds the CORS headers to those responses itself, for + * that page only, by the kind of each load. Only the project's own preview files qualify, and + * `fetch()` reads only what the runtime fetches to draw a frame: `.html` scenes, `.json`, `.cube` + * LUTs and a video's `?hf-proxy=` copy. */ const RUNTIME_READS = /\.(html?|json|cube)$/i; /** File kinds an opaque capture page may load with CORS, by Chrome's resource type. Chrome reports - * a page's `fetch()` as `XHR` to the Fetch domain. */ + * a page's `fetch()`, and its preflight, as `XHR` to the Fetch domain. */ const CAPTURE_LOADS = new Map([ ["Font", /\.(woff2?|ttf|otf)$/i], ["Script", /\.m?js$/i], @@ -20,6 +23,10 @@ const CAPTURE_LOADS = new Map([ ["XHR", RUNTIME_READS], ]); +// The server makes a `?hf-proxy=` copy of a video file only, and answers anything else with a 404. +const PROXY_PARAM = "hf-proxy"; +const VIDEO_FILE = /\.(mp4|webm|mov|mkv|avi|m4v|mxf|mts|m2ts)$/i; + /** `/api/projects//preview/` for a capture URL, or null for any other URL. */ function previewPrefix(captureUrl: string): string | null { let url: URL; @@ -38,11 +45,28 @@ export interface CaptureLoad { resourceType: string; } -/** Whether the capture page at `captureUrl` may read `load` across its opaque origin. */ -export function captureLoadGetsCors(load: CaptureLoad, captureUrl: string): boolean { +/** + * What the capture page at `captureUrl` may do with `load` across its opaque origin: + * - `read`: a file the frame draws from; + * - `proxy`: the runtime's wait for a video's preview copy (`proxyWait.ts`), which reads its status + * and progress headers; + * - `preflight`: that wait's preflight, sent when it carries the priority header. + */ +export function captureLoadGrant( + load: CaptureLoad, + captureUrl: string, +): "read" | "proxy" | "preflight" | null { const prefix = previewPrefix(captureUrl); - if (!prefix || load.method !== "GET" || !load.url.startsWith(prefix)) return false; - return CAPTURE_LOADS.get(load.resourceType)?.test(new URL(load.url).pathname) ?? false; + if (!prefix || !load.url.startsWith(prefix)) return null; + const url = new URL(load.url); + const fetched = load.resourceType === "XHR" || load.resourceType === "Fetch"; + if (fetched && url.searchParams.has(PROXY_PARAM) && VIDEO_FILE.test(url.pathname)) { + if (load.method === "OPTIONS") return "preflight"; + if (load.method === "GET") return "proxy"; + return null; + } + if (load.method !== "GET") return null; + return CAPTURE_LOADS.get(load.resourceType)?.test(url.pathname) ? "read" : null; } type Header = { name: string; value: string }; @@ -62,35 +86,58 @@ export interface CaptureCdpSession { ): unknown; } -/** Adds `Access-Control-Allow-Origin: null` to the capture page's loads that `captureLoadGetsCors` - * allows. Call it on the page's own session before navigating, and keep the session for the page's life. */ +const OPAQUE_CALLER: Header[] = [ + { name: "Access-Control-Allow-Origin", value: "null" }, + { name: "X-Content-Type-Options", value: "nosniff" }, +]; +const PROXY_HEADERS: Header[] = [ + { + name: "Access-Control-Expose-Headers", + value: `Retry-After, ${PREVIEW_PROXY_PROGRESS_HEADER}, Content-Range`, + }, +]; +const PREFLIGHT_ANSWER: Header[] = [ + { name: "Access-Control-Allow-Origin", value: "null" }, + { name: "Access-Control-Allow-Methods", value: "GET" }, + { name: "Access-Control-Allow-Headers", value: `Range, ${PREVIEW_PROXY_PRIORITY_HEADER}` }, +]; + +/** Grants the capture page's loads that `captureLoadGrant` allows. Call it on the page's own session + * before navigating, and keep the session for the page's life. */ export async function grantCaptureLoads(cdp: CaptureCdpSession, captureUrl: string): Promise { const prefix = previewPrefix(captureUrl); if (!prefix) return; cdp.on("Fetch.requestPaused", (event) => { + const { requestId } = event; const headers = event.responseHeaders ?? []; const status = event.responseStatusCode ?? 0; - const grant = + const grant = captureLoadGrant( + { url: event.request.url, method: event.request.method, resourceType: event.resourceType }, + captureUrl, + ); + const answered = status >= 200 && status < 300 && - !headers.some((header) => header.name.toLowerCase() === "access-control-allow-origin") && - captureLoadGetsCors( - { url: event.request.url, method: event.request.method, resourceType: event.resourceType }, - captureUrl, - ); - void ( - grant - ? cdp.send("Fetch.continueResponse", { - requestId: event.requestId, - responseCode: status, - responseHeaders: [ - ...headers, - { name: "Access-Control-Allow-Origin", value: "null" }, - { name: "X-Content-Type-Options", value: "nosniff" }, - ], + !headers.some((header) => header.name.toLowerCase() === "access-control-allow-origin"); + const sent = + grant === "preflight" + ? cdp.send("Fetch.fulfillRequest", { + requestId, + responseCode: 204, + responseHeaders: PREFLIGHT_ANSWER, }) - : cdp.send("Fetch.continueRequest", { requestId: event.requestId }) - ).catch(() => undefined); + : grant && answered + ? cdp.send("Fetch.continueResponse", { + requestId, + responseCode: status, + responseHeaders: [ + ...headers, + ...OPAQUE_CALLER, + ...(grant === "proxy" ? PROXY_HEADERS : []), + ], + }) + : cdp.send("Fetch.continueRequest", { requestId }); + void sent.catch(() => undefined); }); await cdp.send("Fetch.enable", { patterns: [...CAPTURE_LOADS.keys()].map((resourceType) => ({ diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts index c276c321034..f69ea3c5bb2 100644 --- a/packages/studio-server/src/index.ts +++ b/packages/studio-server/src/index.ts @@ -59,7 +59,7 @@ export { type FileWriteReceipt, } from "./helpers/fileVersion.js"; export { buildSubCompositionHtml } from "./helpers/subComposition.js"; -export { captureLoadGetsCors, grantCaptureLoads } from "./helpers/captureLoads.js"; +export { captureLoadGrant, grantCaptureLoads } from "./helpers/captureLoads.js"; export { clearElementScreenshotIsolation, getElementScreenshotClip, From a177852d72849e31fbcf6cdfaec20f95a4389975 Mon Sep 17 00:00:00 2001 From: James Date: Wed, 11 Nov 2026 00:33:48 +0000 Subject: [PATCH 3/6] refactor(studio-server): keep capture-load comments within the package share Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/server/studioServer.ts | 1 - packages/studio-server/src/createStudioApi.ts | 7 ++-- .../studio-server/src/helpers/captureLoads.ts | 34 +++++-------------- packages/studio/vite.browser.ts | 1 - 4 files changed, 10 insertions(+), 33 deletions(-) diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index 8bb09d58d64..0f687659b31 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -805,7 +805,6 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { opts.seekTime, async (page) => { await page.setViewport(viewport); - // The capture document runs in an opaque origin; this page's session grants its fonts and scenes. await grantCaptureLoads(await page.createCDPSession(), opts.previewUrl); await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 }); await assertWebGpuAdapterAvailable( diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts index 7b129412199..0c4ec9fe52e 100644 --- a/packages/studio-server/src/createStudioApi.ts +++ b/packages/studio-server/src/createStudioApi.ts @@ -43,15 +43,12 @@ const fromAnotherSite = (c: Context) => { return site === "cross-site" || site === "same-site"; }; -// A thumbnail capture runs every composition with no user action, so its document gets an opaque -// origin too: its scripts reach nothing of this API. The renderer grants the loads it still needs -// (grantCaptureLoads). -const forCapture = (c: Context) => c.req.query(PREVIEW_CAPTURE_PARAM) !== undefined; +const isThumbnailCapture = (c: Context) => c.req.query(PREVIEW_CAPTURE_PARAM) !== undefined; async function sandboxPreviewForAnotherSiteOrCapture(c: Context, next: Next) { await next(); c.header("Vary", "Sec-Fetch-Site", { append: true }); - if (fromAnotherSite(c) || forCapture(c)) + if (fromAnotherSite(c) || isThumbnailCapture(c)) c.header("Content-Security-Policy", "sandbox allow-scripts"); } diff --git a/packages/studio-server/src/helpers/captureLoads.ts b/packages/studio-server/src/helpers/captureLoads.ts index 797306b8d0b..d284f1601e0 100644 --- a/packages/studio-server/src/helpers/captureLoads.ts +++ b/packages/studio-server/src/helpers/captureLoads.ts @@ -1,20 +1,13 @@ import { PREVIEW_PROXY_PRIORITY_HEADER, PREVIEW_PROXY_PROGRESS_HEADER } from "@hyperframes/core"; /** - * A thumbnail capture document is served with `Content-Security-Policy: sandbox allow-scripts` - * (createStudioApi), so its scripts run in an opaque origin and cannot use the Studio API. Loads that - * the browser makes in CORS mode then fail too: fonts, module scripts, images drawn for color grading, - * the runtime's fetch of a nested composition, and its wait for a video's preview copy. The renderer - * that opened the capture page is trusted, so it adds the CORS headers to those responses itself, for - * that page only, by the kind of each load. Only the project's own preview files qualify, and - * `fetch()` reads only what the runtime fetches to draw a frame: `.html` scenes, `.json`, `.cube` - * LUTs and a video's `?hf-proxy=` copy. + * A capture document is sandboxed (createStudioApi), so its CORS-mode loads fail. The trusted renderer + * adds the CORS headers for its own page, by each load's kind: what a frame draws, and what the runtime + * fetches (`.html` scenes, `.json`, `.cube` LUTs, a video's `?hf-proxy=` copy and its preflight). */ - const RUNTIME_READS = /\.(html?|json|cube)$/i; -/** File kinds an opaque capture page may load with CORS, by Chrome's resource type. Chrome reports - * a page's `fetch()`, and its preflight, as `XHR` to the Fetch domain. */ +// Chrome reports a page's `fetch()`, and its preflight, as `XHR`. const CAPTURE_LOADS = new Map([ ["Font", /\.(woff2?|ttf|otf)$/i], ["Script", /\.m?js$/i], @@ -23,12 +16,10 @@ const CAPTURE_LOADS = new Map([ ["XHR", RUNTIME_READS], ]); -// The server makes a `?hf-proxy=` copy of a video file only, and answers anything else with a 404. const PROXY_PARAM = "hf-proxy"; const VIDEO_FILE = /\.(mp4|webm|mov|mkv|avi|m4v|mxf|mts|m2ts)$/i; -/** `/api/projects//preview/` for a capture URL, or null for any other URL. */ -function previewPrefix(captureUrl: string): string | null { +function capturePreviewPrefix(captureUrl: string): string | null { let url: URL; try { url = new URL(captureUrl); @@ -45,18 +36,11 @@ export interface CaptureLoad { resourceType: string; } -/** - * What the capture page at `captureUrl` may do with `load` across its opaque origin: - * - `read`: a file the frame draws from; - * - `proxy`: the runtime's wait for a video's preview copy (`proxyWait.ts`), which reads its status - * and progress headers; - * - `preflight`: that wait's preflight, sent when it carries the priority header. - */ export function captureLoadGrant( load: CaptureLoad, captureUrl: string, ): "read" | "proxy" | "preflight" | null { - const prefix = previewPrefix(captureUrl); + const prefix = capturePreviewPrefix(captureUrl); if (!prefix || !load.url.startsWith(prefix)) return null; const url = new URL(load.url); const fetched = load.resourceType === "XHR" || load.resourceType === "Fetch"; @@ -71,7 +55,6 @@ export function captureLoadGrant( type Header = { name: string; value: string }; -/** The part of a CDP session this needs; puppeteer's `CDPSession` fits it. */ export interface CaptureCdpSession { send(method: string, params?: object): Promise; on( @@ -102,10 +85,9 @@ const PREFLIGHT_ANSWER: Header[] = [ { name: "Access-Control-Allow-Headers", value: `Range, ${PREVIEW_PROXY_PRIORITY_HEADER}` }, ]; -/** Grants the capture page's loads that `captureLoadGrant` allows. Call it on the page's own session - * before navigating, and keep the session for the page's life. */ +/** Call on the capture page's own session before it navigates; keep the session for the page's life. */ export async function grantCaptureLoads(cdp: CaptureCdpSession, captureUrl: string): Promise { - const prefix = previewPrefix(captureUrl); + const prefix = capturePreviewPrefix(captureUrl); if (!prefix) return; cdp.on("Fetch.requestPaused", (event) => { const { requestId } = event; diff --git a/packages/studio/vite.browser.ts b/packages/studio/vite.browser.ts index 38dbf43be55..6a4ecde9ed1 100644 --- a/packages/studio/vite.browser.ts +++ b/packages/studio/vite.browser.ts @@ -228,7 +228,6 @@ async function prepareThumbnailPage( height: opts.height, deviceScaleFactor: thumbnailDeviceScaleFactor(opts), }); - // The capture document runs in an opaque origin; this page's session grants its fonts and scenes. await grantCaptureLoads(await page.createCDPSession(), opts.previewUrl); await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 }); await page.evaluate(() => { From 563bde8a72662543e902882e4bfed10895781fa9 Mon Sep 17 00:00:00 2001 From: James Date: Wed, 11 Nov 2026 05:09:18 +0000 Subject: [PATCH 4/6] fix(studio-server): keep video pixels and project fetches in opaque thumbnail captures - Media loads: the renderer now grants them, and a capture document loads the project's own videos with `crossorigin="anonymous"`. Color grading and shader textures can then read their pixels. - Fetches: every GET of the project's preview files is granted, except a dotfile or dot-folder path such as `.env` or `.git/`. This covers the models and fonts that registry blocks fetch at runtime. - Opt-in: the capture sandbox is now a `createStudioApi` option, `sandboxThumbnailCaptures`, off by default. The CLI Studio server and the Vite dev server turn it on, because their thumbnail renderers install the grant. Another app keeps its current capture documents until its renderer does the same. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/server/studioServer.test.ts | 12 ++++ packages/cli/src/server/studioServer.ts | 2 +- packages/studio-server/src/createStudioApi.ts | 24 ++++--- .../src/helpers/captureLoads.test.ts | 30 +++++---- .../studio-server/src/helpers/captureLoads.ts | 66 +++++++++++-------- .../src/helpers/captureVideos.test.ts | 28 ++++++++ .../src/helpers/captureVideos.ts | 25 +++++++ .../src/routes/preview.sandbox.test.ts | 32 +++++++-- packages/studio-server/src/routes/preview.ts | 16 +++-- packages/studio/vite.config.ts | 1 + 10 files changed, 174 insertions(+), 62 deletions(-) create mode 100644 packages/studio-server/src/helpers/captureVideos.test.ts create mode 100644 packages/studio-server/src/helpers/captureVideos.ts diff --git a/packages/cli/src/server/studioServer.test.ts b/packages/cli/src/server/studioServer.test.ts index 4f7cf8a08c9..6e8046b7cc7 100644 --- a/packages/cli/src/server/studioServer.test.ts +++ b/packages/cli/src/server/studioServer.test.ts @@ -761,6 +761,18 @@ describe("Studio thumbnail capture", () => { expect(clears[0]).toBeGreaterThan(screenshot.mock.invocationCallOrder[0]!); }); + it("serves thumbnail capture documents in an opaque origin", async () => { + const dir = tmpProject(); + writeFileSync(join(dir, "index.html"), '
'); + server = createStudioServer({ projectDir: dir, projectName: "demo" }); + const capture = await server.app.request( + "http://localhost/api/projects/demo/preview?hf-capture=1", + ); + expect(capture.headers.get("content-security-policy")).toBe("sandbox allow-scripts"); + const preview = await server.app.request("http://localhost/api/projects/demo/preview"); + expect(preview.headers.get("content-security-policy")).toBeNull(); + }); + it("grants the capture page's loads on its own session before it navigates", async () => { const calls: string[] = []; const session = { diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index 0f687659b31..8358c883497 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -1119,7 +1119,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { // Mount the shared studio API at /api. // Use fetch() forwarding (not .route()) so the sub-app sees paths without // the /api prefix — the shared module's path extraction uses c.req.path. - const api = createStudioApi(adapter, { allowedHosts }); + const api = createStudioApi(adapter, { allowedHosts, sandboxThumbnailCaptures: true }); app.all("/api/*", async (c) => { const url = new URL(c.req.url); url.pathname = url.pathname.slice(4); // Strip "/api" prefix diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts index 0c4ec9fe52e..05b8a7520d6 100644 --- a/packages/studio-server/src/createStudioApi.ts +++ b/packages/studio-server/src/createStudioApi.ts @@ -25,6 +25,7 @@ import { sameOriginPost, } from "./helpers/requestIdentity.js"; import { previewErrorPage } from "./helpers/previewErrorPage.js"; +import type { CaptureSandboxOption } from "./helpers/captureLoads.js"; async function answerRefusedFrameWithPage(c: Context, next: Next) { await next(); @@ -45,12 +46,13 @@ const fromAnotherSite = (c: Context) => { const isThumbnailCapture = (c: Context) => c.req.query(PREVIEW_CAPTURE_PARAM) !== undefined; -async function sandboxPreviewForAnotherSiteOrCapture(c: Context, next: Next) { - await next(); - c.header("Vary", "Sec-Fetch-Site", { append: true }); - if (fromAnotherSite(c) || isThumbnailCapture(c)) - c.header("Content-Security-Policy", "sandbox allow-scripts"); -} +const sandboxPreviewForAnotherSiteOrCapture = + (sandboxCaptures: boolean) => async (c: Context, next: Next) => { + await next(); + c.header("Vary", "Sec-Fetch-Site", { append: true }); + if (fromAnotherSite(c) || (sandboxCaptures && isThumbnailCapture(c))) + c.header("Content-Security-Policy", "sandbox allow-scripts"); + }; async function refuseThumbnailForAnotherSite(c: Context, next: Next) { if (fromAnotherSite(c)) @@ -74,13 +76,17 @@ function urlScheme(url: string): string | undefined { } } -export interface StudioApiOptions { +export interface StudioApiOptions extends CaptureSandboxOption { allowedHosts?: readonly string[]; } export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOptions = {}): Hono { const api = new Hono(); - api.use("/projects/:id/preview/*", sandboxPreviewForAnotherSiteOrCapture); + const sandboxThumbnailCaptures = options.sandboxThumbnailCaptures ?? false; + api.use( + "/projects/:id/preview/*", + sandboxPreviewForAnotherSiteOrCapture(sandboxThumbnailCaptures), + ); api.use("/projects/:id/thumbnail/*", refuseThumbnailForAnotherSite); // This API is unauthenticated and simple cross-origin POSTs need no // preflight, so the guard rejects writes the shared predicate refuses. @@ -154,7 +160,7 @@ export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOpt registerProjectRoutes(api, adapter); registerFileRoutes(api, adapter); - registerPreviewRoutes(api, adapter); + registerPreviewRoutes(api, adapter, { sandboxThumbnailCaptures }); registerLintRoutes(api, adapter); registerRenderRoutes(api, adapter); registerThumbnailRoutes(api, adapter); diff --git a/packages/studio-server/src/helpers/captureLoads.test.ts b/packages/studio-server/src/helpers/captureLoads.test.ts index c4f32481770..43680c115cd 100644 --- a/packages/studio-server/src/helpers/captureLoads.test.ts +++ b/packages/studio-server/src/helpers/captureLoads.test.ts @@ -8,19 +8,22 @@ const CAPTURE = `${PREVIEW}/comp/compositions/intro.html?hf-capture=1`; describe("captureLoadGrant", () => { it.each([ ["Font", `${PREVIEW}/assets/brand.woff2`], - ["Font", `${PREVIEW}/fonts/Display.ttf?v=2`], ["Script", `${PREVIEW}/assets/scene.mjs`], + ["Stylesheet", `${PREVIEW}/style.css`], ["Image", `${PREVIEW}/assets/logo.png`], + ["Media", `${PREVIEW}/assets/clip.mp4`], + ["Media", `${PREVIEW}/assets/clip.mov?hf-proxy=h264`], ["XHR", `${PREVIEW}/compositions/scene.html`], - ["Fetch", `${PREVIEW}/caption-overrides.json`], - ["XHR", `${PREVIEW}/luts/warm.cube`], + ["Fetch", `${PREVIEW}/models/device.glb`], + ["XHR", `${PREVIEW}/assets/fonts/Geist-Bold.ttf`], + ["XHR", `${PREVIEW}/notes.txt`], + ["XHR", `${PREVIEW}/assets/clip.mov?hf-proxy=h264&hf-proxy-box=1448x724`], ])("lets the frame read a %s load of %s", (resourceType, url) => { expect(captureLoadGrant({ url, method: "GET", resourceType }, CAPTURE)).toBe("read"); }); - it("answers the runtime's wait for a video's preview copy and its preflight", () => { + it("answers the preflight of the runtime's wait for a video's preview copy", () => { const url = `${PREVIEW}/assets/clip.mov?hf-proxy=h264&hf-proxy-box=1448x724`; - expect(captureLoadGrant({ url, method: "GET", resourceType: "XHR" }, CAPTURE)).toBe("proxy"); expect(captureLoadGrant({ url, method: "OPTIONS", resourceType: "XHR" }, CAPTURE)).toBe( "preflight", ); @@ -29,21 +32,21 @@ describe("captureLoadGrant", () => { it.each([ ["XHR", `${PREVIEW}/.env`, "GET"], ["XHR", `${PREVIEW}/.git/config`, "GET"], - ["Fetch", `${PREVIEW}/notes.txt`, "GET"], + ["XHR", `${PREVIEW}/assets/.npmrc`, "GET"], + ["XHR", `${PREVIEW}/%2Eenv`, "GET"], + ["XHR", `${PREVIEW}/%E0%A4%A.html`, "GET"], ["Script", `${PREVIEW}/.env`, "GET"], - ["Font", `${PREVIEW}/secrets.txt`, "GET"], - ["Stylesheet", `${PREVIEW}/style.css`, "GET"], + ["Image", `${PREVIEW}/.git/logo.png`, "GET"], + ["Document", `${PREVIEW}/compositions/scene.html`, "GET"], ["XHR", `${ORIGIN}/api/projects/demo/files/index.html`, "GET"], ["XHR", `${ORIGIN}/api/projects/other/preview/index.html`, "GET"], ["XHR", `http://127.0.0.1:9999/api/projects/demo/preview/index.html`, "GET"], ["XHR", `${PREVIEW}/compositions/scene.html`, "PUT"], ["XHR", `${PREVIEW}/compositions/scene.html`, "POST"], ["XHR", `${PREVIEW}/compositions/scene.html`, "OPTIONS"], - ["XHR", `${PREVIEW}/assets/clip.mov`, "GET"], - ["XHR", `${PREVIEW}/.env?hf-proxy=h264`, "GET"], ["XHR", `${PREVIEW}/.env?hf-proxy=h264`, "OPTIONS"], + ["XHR", `${PREVIEW}/notes.txt?hf-proxy=h264`, "OPTIONS"], ["XHR", `${PREVIEW}/assets/clip.mov?hf-proxy=h264`, "PUT"], - ["Media", `${PREVIEW}/assets/clip.mov?hf-proxy=h264`, "GET"], ])("refuses a %s load of %s (%s)", (resourceType, url, method) => { expect(captureLoadGrant({ url, method, resourceType }, CAPTURE)).toBeNull(); }); @@ -85,7 +88,9 @@ describe("grantCaptureLoads", () => { const enable = send.mock.calls.find(([method]) => method === "Fetch.enable"); expect(enable).toBeDefined(); const { patterns } = enable![1] as { patterns: Array> }; - expect(patterns.length).toBeGreaterThan(0); + expect(patterns.map((pattern) => pattern.resourceType)).toEqual( + expect.arrayContaining(["Font", "Image", "Media", "XHR"]), + ); for (const pattern of patterns) { expect(pattern.urlPattern).toBe(`${PREVIEW}/*`); expect(pattern.requestStage).toBe("Response"); @@ -103,6 +108,7 @@ describe("grantCaptureLoads", () => { { name: "Content-Type", value: "font/woff2" }, { name: "Access-Control-Allow-Origin", value: "null" }, { name: "X-Content-Type-Options", value: "nosniff" }, + expect.objectContaining({ name: "Access-Control-Expose-Headers" }), ], }); }); diff --git a/packages/studio-server/src/helpers/captureLoads.ts b/packages/studio-server/src/helpers/captureLoads.ts index d284f1601e0..90759f7e8e6 100644 --- a/packages/studio-server/src/helpers/captureLoads.ts +++ b/packages/studio-server/src/helpers/captureLoads.ts @@ -1,20 +1,12 @@ import { PREVIEW_PROXY_PRIORITY_HEADER, PREVIEW_PROXY_PROGRESS_HEADER } from "@hyperframes/core"; /** - * A capture document is sandboxed (createStudioApi), so its CORS-mode loads fail. The trusted renderer - * adds the CORS headers for its own page, by each load's kind: what a frame draws, and what the runtime - * fetches (`.html` scenes, `.json`, `.cube` LUTs, a video's `?hf-proxy=` copy and its preflight). + * A sandboxed capture document's CORS-mode loads fail, so the trusted renderer adds CORS headers for + * its own page: every GET of the project's preview files except a dotfile or dot-folder (`.env`, + * `.git/`), and the preflight of the runtime's wait for a video's `?hf-proxy=` copy. */ -const RUNTIME_READS = /\.(html?|json|cube)$/i; - // Chrome reports a page's `fetch()`, and its preflight, as `XHR`. -const CAPTURE_LOADS = new Map([ - ["Font", /\.(woff2?|ttf|otf)$/i], - ["Script", /\.m?js$/i], - ["Image", /\.(png|jpe?g|gif|webp|avif|svg)$/i], - ["Fetch", RUNTIME_READS], - ["XHR", RUNTIME_READS], -]); +const GRANTED_TYPES = new Set(["Font", "Script", "Stylesheet", "Image", "Media", "Fetch", "XHR"]); const PROXY_PARAM = "hf-proxy"; const VIDEO_FILE = /\.(mp4|webm|mov|mkv|avi|m4v|mxf|mts|m2ts)$/i; @@ -30,27 +22,49 @@ function capturePreviewPrefix(captureUrl: string): string | null { return path ? `${url.origin}${path}/` : null; } +export interface CaptureSandboxOption { + /** + * Serve thumbnail capture documents (`?hf-capture`) in an opaque origin. Default off. Turn it on + * only with a thumbnail renderer that calls `grantCaptureLoads` on each capture page before loading + * it; without that grant its captures lose fonts, module scripts, nested scenes and video pixels. + */ + sandboxThumbnailCaptures?: boolean; +} + export interface CaptureLoad { url: string; method: string; resourceType: string; } +const decodedSegment = (segment: string) => { + try { + return decodeURIComponent(segment); + } catch { + return "."; + } +}; + +const isDotPath = (url: URL, prefix: string) => + url.pathname + .slice(new URL(prefix).pathname.length) + .split("/") + .some((segment) => decodedSegment(segment).startsWith(".")); + export function captureLoadGrant( load: CaptureLoad, captureUrl: string, -): "read" | "proxy" | "preflight" | null { +): "read" | "preflight" | null { const prefix = capturePreviewPrefix(captureUrl); if (!prefix || !load.url.startsWith(prefix)) return null; const url = new URL(load.url); - const fetched = load.resourceType === "XHR" || load.resourceType === "Fetch"; - if (fetched && url.searchParams.has(PROXY_PARAM) && VIDEO_FILE.test(url.pathname)) { - if (load.method === "OPTIONS") return "preflight"; - if (load.method === "GET") return "proxy"; - return null; - } - if (load.method !== "GET") return null; - return CAPTURE_LOADS.get(load.resourceType)?.test(url.pathname) ? "read" : null; + if (isDotPath(url, prefix) || !GRANTED_TYPES.has(load.resourceType)) return null; + const proxyWait = + (load.resourceType === "XHR" || load.resourceType === "Fetch") && + url.searchParams.has(PROXY_PARAM) && + VIDEO_FILE.test(url.pathname); + if (load.method === "OPTIONS") return proxyWait ? "preflight" : null; + return load.method === "GET" ? "read" : null; } type Header = { name: string; value: string }; @@ -72,8 +86,6 @@ export interface CaptureCdpSession { const OPAQUE_CALLER: Header[] = [ { name: "Access-Control-Allow-Origin", value: "null" }, { name: "X-Content-Type-Options", value: "nosniff" }, -]; -const PROXY_HEADERS: Header[] = [ { name: "Access-Control-Expose-Headers", value: `Retry-After, ${PREVIEW_PROXY_PROGRESS_HEADER}, Content-Range`, @@ -112,17 +124,13 @@ export async function grantCaptureLoads(cdp: CaptureCdpSession, captureUrl: stri ? cdp.send("Fetch.continueResponse", { requestId, responseCode: status, - responseHeaders: [ - ...headers, - ...OPAQUE_CALLER, - ...(grant === "proxy" ? PROXY_HEADERS : []), - ], + responseHeaders: [...headers, ...OPAQUE_CALLER], }) : cdp.send("Fetch.continueRequest", { requestId }); void sent.catch(() => undefined); }); await cdp.send("Fetch.enable", { - patterns: [...CAPTURE_LOADS.keys()].map((resourceType) => ({ + patterns: [...GRANTED_TYPES].map((resourceType) => ({ urlPattern: `${prefix}*`, resourceType, requestStage: "Response", diff --git a/packages/studio-server/src/helpers/captureVideos.test.ts b/packages/studio-server/src/helpers/captureVideos.test.ts new file mode 100644 index 00000000000..de4f05d8e70 --- /dev/null +++ b/packages/studio-server/src/helpers/captureVideos.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { corsProjectVideos } from "./captureVideos.js"; + +const doc = (body: string) => `${body}`; + +describe("corsProjectVideos", () => { + it("loads the project's own videos with CORS and leaves the rest alone", () => { + const html = corsProjectVideos( + doc( + '' + + '' + + '' + + '' + + '' + + '' + + '', + ), + ); + const marked = [...html.matchAll(/