Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions packages/cli/src/server/studioServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,53 @@ 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"), '<div data-composition-id="main"></div>');
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 = {
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();
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/src/server/studioServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import {
PREVIEW_BUNDLE_OPTIONS,
createPreviewDocumentStore,
thumbnailDeviceScaleFactor,
grantCaptureLoads,
type ResolvedProject,
type RenderJobState,
type BackgroundRemovalRender,
Expand Down Expand Up @@ -804,6 +805,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
opts.seekTime,
async (page) => {
await page.setViewport(viewport);
await grantCaptureLoads(await page.createCDPSession(), opts.previewUrl);
await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 });
await assertWebGpuAdapterAvailable(
page,
Expand Down Expand Up @@ -1117,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
Expand Down
28 changes: 28 additions & 0 deletions packages/shader-transitions/src/hyper-shader.preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,31 @@ describe("a runtime seek while the prewarm runs", () => {
expect(tl.totalTime()).toBe(1);
});
});

describe("a document without IndexedDB access", () => {
it("prepares its transitions without the snapshot cache", async () => {
stubGsap();
stubWebGl();
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const denied = new DOMException(
"access to the Indexed Database API is denied",
"SecurityError",
);
const open = vi.fn(() => {
throw denied;
});
vi.stubGlobal("indexedDB", { open });
// The cache's connection is module state, so a fresh module opens it under this stub.
vi.resetModules();
const { init: initFresh } = await import("./hyper-shader.js");
mountScenes(["s1", "s2"]);
initFresh({
bgColor: "#000",
scenes: ["s1", "s2"],
transitions: [{ time: 2, duration: 0.8, shader: "domain-warp" }],
});
await prewarmDone();
expect(open).toHaveBeenCalled();
expect(warn.mock.calls.flat()).not.toContain(denied);
});
});
7 changes: 6 additions & 1 deletion packages/shader-transitions/src/hyper-shader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,13 @@ function makeSnapshotKey(cacheKey: string, sampleIndex: number, side: "from" | "

function openSnapshotDb(): Promise<IDBDatabase | null> {
if (typeof indexedDB === "undefined") return Promise.resolve(null);
let request: IDBOpenDBRequest;
try {
request = indexedDB.open(SNAPSHOT_CACHE_DB, SNAPSHOT_CACHE_VERSION);
} catch {
return Promise.resolve(null);
}
return new Promise((resolve) => {
const request = indexedDB.open(SNAPSHOT_CACHE_DB, SNAPSHOT_CACHE_VERSION);
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(SNAPSHOT_CACHE_STORE)) {
Expand Down
27 changes: 18 additions & 9 deletions packages/studio-server/src/createStudioApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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();
Expand All @@ -43,11 +44,15 @@ const fromAnotherSite = (c: Context) => {
return site === "cross-site" || site === "same-site";
};

async function sandboxPreviewOpenedFromAnotherSite(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");
}
const isThumbnailCapture = (c: Context) => c.req.query(PREVIEW_CAPTURE_PARAM) !== undefined;

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))
Expand All @@ -71,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/*", sandboxPreviewOpenedFromAnotherSite);
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.
Expand Down Expand Up @@ -151,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);
Expand Down
186 changes: 186 additions & 0 deletions packages/studio-server/src/helpers/captureLoads.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { describe, expect, it, vi } from "vitest";
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("captureLoadGrant", () => {
it.each([
["Font", `${PREVIEW}/assets/brand.woff2`],
["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}/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 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: "OPTIONS", resourceType: "XHR" }, CAPTURE)).toBe(
"preflight",
);
});

it.each([
["XHR", `${PREVIEW}/.env`, "GET"],
["XHR", `${PREVIEW}/.git/config`, "GET"],
["XHR", `${PREVIEW}/assets/.npmrc`, "GET"],
["XHR", `${PREVIEW}/%2Eenv`, "GET"],
["XHR", `${PREVIEW}/%E0%A4%A.html`, "GET"],
["Script", `${PREVIEW}/.env`, "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}/.env?hf-proxy=h264`, "OPTIONS"],
["XHR", `${PREVIEW}/notes.txt?hf-proxy=h264`, "OPTIONS"],
["XHR", `${PREVIEW}/assets/clip.mov?hf-proxy=h264`, "PUT"],
])("refuses a %s load of %s (%s)", (resourceType, url, method) => {
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(captureLoadGrant(load, `${ORIGIN}/api/projects/demo/files/index.html`)).toBeNull();
expect(captureLoadGrant(load, "not a url")).toBeNull();
});
});

type Paused = Parameters<Parameters<CaptureCdpSession["on"]>[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> = {}): 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<Record<string, string>> };
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");
}
});

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" },
expect.objectContaining({ name: "Access-Control-Expose-Headers" }),
],
});
});

it("lets the frame read a missing file's status, as a same-origin page would", async () => {
const { session, send, pause } = fakeSession();
await grantCaptureLoads(session, CAPTURE);
pause(response(`${PREVIEW}/assets/fonts/Missing.ttf`, "XHR", { responseStatusCode: 404 }));
expect(send).toHaveBeenLastCalledWith(
"Fetch.continueResponse",
expect.objectContaining({ responseCode: 404 }),
);
});

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")],
[
"a request paused before its response",
response(`${PREVIEW}/assets/brand.woff2`, "Font", { responseStatusCode: undefined }),
],
[
"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();
});
});
Loading
Loading