mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 07:50:13 +00:00
fix(studio-server): load fonts and modules only in the Studio's own preview frames (#7553)
* fix(studio-server): let opaque preview frames load project fonts and module scripts A preview framed with an opaque origin, such as the Compositions hover preview, makes its font and module-script loads in CORS mode with `Origin: null`. Without a CORS grant they failed: the frame fell back to a system font and module scripts never ran. The preview asset route now answers those two loads with `Access-Control-Allow-Origin: null`, `Vary: Origin` and `X-Content-Type-Options: nosniff`. The grant is chosen by `Sec-Fetch-Dest`, which the browser sets and page script cannot: `font` for a font file and `script` for a .js/.mjs file, served with the matching content type. A page's own `fetch()` is always `empty`, so it still gets no grant and composition script still cannot read project files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(studio-server): keep opaque-frame grant comments within the package share Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(studio-server): let opaque preview frames load project fonts Narrow the opaque-frame grant to fonts. Every sandboxed frame sends the same `Origin: null` and fetch metadata, so a CORS grant for module scripts could not be limited to frames the Studio itself serves. Module scripts stay unloaded in the hover preview for now; fonts keep their grant, and `Sec-Fetch-Dest: script` loads of .js/.mjs get none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(studio-server): load fonts and modules only in the Studio's own preview frames A CORS grant to `Origin: null` reaches every sandboxed frame, whichever page it sits in. The grant now lives on a per-project path instead: `/projects/:id/preview/~<token>/...` serves exactly what `/preview/...` serves, and only there do font loads (`Sec-Fetch-Dest: font`, a font file served as `font/*`) and module-script loads (`script`, a .js/.mjs file served as `text/javascript`) from an opaque frame get `Access-Control-Allow-Origin: null`. The plain path gets no grant. The token is an HMAC-SHA256 of the project id under a random per-server secret, compared in constant time. The Studio reads it from `/projects/:id/frame-token`, which refuses cross-site and same-site requests, and the Compositions hover preview frames its composition at the token path. Documents served there are re-based under the token and carry `Referrer-Policy: no-referrer`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(studio-server): raise the packed size budget for the preview frame tokens The per-project frame-token path adds server code to the package, and the packed tarball measured 166941 bytes in CI against a 164800 budget. Set the budget to the measured size plus about 1% headroom. — Rames Jusso Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a8fe3a5b68
commit
ffb13c3b62
@@ -26,6 +26,7 @@ import {
|
||||
} from "./helpers/requestIdentity.js";
|
||||
import { previewErrorPage } from "./helpers/previewErrorPage.js";
|
||||
import type { CaptureSandboxOption } from "./helpers/captureLoads.js";
|
||||
import { createFrameTokens, serveTokenPreviewPaths } from "./helpers/opaqueFrameLoads.js";
|
||||
|
||||
async function answerRefusedFrameWithPage(c: Context, next: Next) {
|
||||
await next();
|
||||
@@ -83,10 +84,25 @@ export interface StudioApiOptions extends CaptureSandboxOption {
|
||||
export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOptions = {}): Hono {
|
||||
const api = new Hono();
|
||||
const sandboxThumbnailCaptures = options.sandboxThumbnailCaptures ?? false;
|
||||
const frameTokens = createFrameTokens();
|
||||
const resolveProjectId = (id: string) =>
|
||||
Promise.resolve()
|
||||
.then(() => adapter.resolveProject(id))
|
||||
.then(
|
||||
(project) => project?.id,
|
||||
() => undefined,
|
||||
);
|
||||
api.use("/projects/:id/preview/*", serveTokenPreviewPaths(api, frameTokens, resolveProjectId));
|
||||
api.use(
|
||||
"/projects/:id/preview/*",
|
||||
sandboxPreviewForAnotherSiteOrCapture(sandboxThumbnailCaptures),
|
||||
);
|
||||
api.get("/projects/:id/frame-token", async (c) => {
|
||||
if (fromAnotherSite(c)) return c.json({ error: "forbidden: requested by another site" }, 403);
|
||||
const projectId = await resolveProjectId(c.req.param("id"));
|
||||
if (!projectId) return c.json({ error: "not found" }, 404);
|
||||
return c.json({ token: frameTokens.tokenFor(projectId) }, 200, { "Cache-Control": "no-store" });
|
||||
});
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import type { Context, Hono, Next } from "hono";
|
||||
|
||||
const GRANTED_LOADS = new Map([
|
||||
["font", { path: /\.(woff2?|ttf|otf)$/i, type: /^font\// }],
|
||||
["script", { path: /\.m?js$/i, type: /^text\/javascript\b/ }],
|
||||
]);
|
||||
const TOKEN_SEGMENT = /^~([\w-]{43})$/;
|
||||
|
||||
interface OpaqueFrameLoad {
|
||||
origin: string | undefined;
|
||||
dest: string | undefined;
|
||||
pathname: string;
|
||||
status: number;
|
||||
contentType: string | null;
|
||||
}
|
||||
|
||||
function opaqueFrameLoadGranted(load: OpaqueFrameLoad): boolean {
|
||||
const grant = load.origin === "null" ? GRANTED_LOADS.get(load.dest ?? "") : undefined;
|
||||
if (!grant?.path.test(load.pathname)) return false;
|
||||
const keepsStoredContentType = load.status === 304;
|
||||
return keepsStoredContentType || grant.type.test(load.contentType ?? "");
|
||||
}
|
||||
|
||||
export function createFrameTokens() {
|
||||
const secret = randomBytes(32);
|
||||
const tokenFor = (projectId: string) =>
|
||||
createHmac("sha256", secret).update(projectId).digest("base64url");
|
||||
const matches = (projectId: string, token: string) =>
|
||||
timingSafeEqual(Buffer.from(token), Buffer.from(tokenFor(projectId)));
|
||||
return { tokenFor, matches };
|
||||
}
|
||||
|
||||
type FrameTokens = ReturnType<typeof createFrameTokens>;
|
||||
|
||||
const previewBase = (projectId: string) =>
|
||||
`/api/projects/${encodeURIComponent(projectId)}/preview/`;
|
||||
|
||||
function tokenPathHeaders(c: Context, res: Response, pathname: string): Headers {
|
||||
const headers = new Headers(res.headers);
|
||||
headers.set("Referrer-Policy", "no-referrer");
|
||||
const granted = opaqueFrameLoadGranted({
|
||||
origin: c.req.header("origin"),
|
||||
dest: c.req.header("sec-fetch-dest"),
|
||||
pathname,
|
||||
status: res.status,
|
||||
contentType: headers.get("content-type"),
|
||||
});
|
||||
if (granted) {
|
||||
headers.set("Access-Control-Allow-Origin", "null");
|
||||
headers.set("X-Content-Type-Options", "nosniff");
|
||||
headers.append("Vary", "Origin");
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function underToken(res: Response, headers: Headers, projectId: string, token: string) {
|
||||
if (res.status !== 200 || !headers.get("content-type")?.startsWith("text/html"))
|
||||
return new Response(res.body, { status: res.status, headers });
|
||||
const base = previewBase(projectId);
|
||||
headers.delete("content-length");
|
||||
const html = (await res.text()).replaceAll(base, `${base}~${token}/`);
|
||||
return new Response(html, { status: res.status, headers });
|
||||
}
|
||||
|
||||
// Every opaque frame sends `Origin: null`, so the grant goes only to `preview/~<token>/` paths, which only the
|
||||
// Studio's own pages can learn. The token path serves the plain path's response, its document re-based under the token.
|
||||
export function serveTokenPreviewPaths(
|
||||
api: Hono,
|
||||
tokens: FrameTokens,
|
||||
resolveProjectId: (id: string) => Promise<string | undefined>,
|
||||
) {
|
||||
return async (c: Context, next: Next) => {
|
||||
const url = new URL(c.req.url);
|
||||
const segments = url.pathname.split("/");
|
||||
const token = TOKEN_SEGMENT.exec(segments[4] ?? "")?.[1];
|
||||
if (!token) return next();
|
||||
const projectId = await resolveProjectId(c.req.param("id") ?? "");
|
||||
if (!projectId || !tokens.matches(projectId, token)) return c.text("not found", 404);
|
||||
segments.splice(4, 1);
|
||||
url.pathname = segments.join("/");
|
||||
const req = new Request(url, { method: c.req.method, headers: c.req.raw.headers });
|
||||
const res = await api.fetch(req);
|
||||
return underToken(res, tokenPathHeaders(c, res, url.pathname), projectId, token);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// @vitest-environment node
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { mkdirSync, 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 root = mkdtempSync(join(tmpdir(), "hf-preview-opaque-loads-"));
|
||||
const projectDir = join(root, "demo");
|
||||
mkdirSync(join(projectDir, "fonts"), { recursive: true });
|
||||
mkdirSync(join(root, "other"));
|
||||
writeFileSync(join(projectDir, "index.html"), '<div data-composition-id="main"></div>');
|
||||
writeFileSync(
|
||||
join(projectDir, "scene.html"),
|
||||
'<div data-composition-id="scene"><img src="/logo.png"><script type="module" src="scene.js"></script></div>',
|
||||
);
|
||||
writeFileSync(join(projectDir, "fonts", "Brand.woff2"), Buffer.from("wOF2font"));
|
||||
writeFileSync(join(projectDir, "fonts", "Brand.ttf"), Buffer.from("ttf-font"));
|
||||
writeFileSync(join(projectDir, "scene.js"), "export const scene = 1;");
|
||||
writeFileSync(join(projectDir, "scene.mjs"), "export const scene = 2;");
|
||||
writeFileSync(join(projectDir, "data.json"), '{"secret":true}');
|
||||
writeFileSync(join(projectDir, "logo.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
|
||||
writeFileSync(join(root, "other", "index.html"), '<div data-composition-id="main"></div>');
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
const adapter: StudioApiAdapter = {
|
||||
listProjects: () => [],
|
||||
resolveProject: async (id: string) =>
|
||||
id === "demo" || id === "other" ? { id, dir: join(root, id) } : null,
|
||||
bundle: async () => null,
|
||||
lint: async () => ({ findings: [] }),
|
||||
runtimeUrl: "/api/runtime.js",
|
||||
rendersDir: () => join(root, "renders"),
|
||||
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }),
|
||||
};
|
||||
const api = createStudioApi(adapter);
|
||||
|
||||
async function frameToken(project: string, site = "same-origin") {
|
||||
return api.request(`http://localhost/projects/${project}/frame-token`, {
|
||||
headers: { "sec-fetch-site": site },
|
||||
});
|
||||
}
|
||||
|
||||
let token = "";
|
||||
let otherToken = "";
|
||||
beforeAll(async () => {
|
||||
token = (await (await frameToken("demo")).json()).token;
|
||||
otherToken = (await (await frameToken("other")).json()).token;
|
||||
});
|
||||
|
||||
function load(path: string, headers: Record<string, string>, prefix = `~${token}/`) {
|
||||
return api.request(`http://localhost/projects/demo/preview/${prefix}${path}`, {
|
||||
headers: { "sec-fetch-site": "cross-site", "sec-fetch-mode": "cors", ...headers },
|
||||
});
|
||||
}
|
||||
|
||||
function expectGranted(res: Response) {
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("null");
|
||||
expect(res.headers.get("x-content-type-options")).toBe("nosniff");
|
||||
expect(res.headers.get("vary")?.split(/,\s*/)).toContain("Origin");
|
||||
}
|
||||
|
||||
function expectNotGranted(res: Response) {
|
||||
expect(res.headers.get("access-control-allow-origin")).toBeNull();
|
||||
expect(res.headers.get("vary")?.split(/,\s*/) ?? []).not.toContain("Origin");
|
||||
}
|
||||
|
||||
describe("the frame token", () => {
|
||||
it("is a 256-bit base64url value per project", () => {
|
||||
expect(token).toMatch(/^[\w-]{43}$/);
|
||||
expect(otherToken).toMatch(/^[\w-]{43}$/);
|
||||
expect(otherToken).not.toBe(token);
|
||||
});
|
||||
|
||||
it.each(["cross-site", "same-site"])("is refused to a %s request", async (site) => {
|
||||
const res = await frameToken("demo", site);
|
||||
expect(res.status).toBe(403);
|
||||
expect(await res.text()).not.toContain(token);
|
||||
});
|
||||
|
||||
it("is not minted for an unknown project", async () => {
|
||||
expect((await frameToken("missing")).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("an opaque preview frame's loads under its token", () => {
|
||||
it.each([
|
||||
["font", "fonts/Brand.woff2", "font/woff2"],
|
||||
["font", "fonts/Brand.ttf", "font/ttf"],
|
||||
["script", "scene.js", "text/javascript"],
|
||||
["script", "scene.mjs", "text/javascript"],
|
||||
])("lets a %s load of %s through", async (dest, path, type) => {
|
||||
const res = await load(path, { origin: "null", "sec-fetch-dest": dest });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain(type);
|
||||
expectGranted(res);
|
||||
});
|
||||
|
||||
it("serves the same bytes as the plain path", async () => {
|
||||
const tokened = await load("fonts/Brand.woff2", { "sec-fetch-dest": "font" });
|
||||
const plain = await load("fonts/Brand.woff2", { "sec-fetch-dest": "font" }, "");
|
||||
expect(Buffer.from(await tokened.arrayBuffer())).toEqual(
|
||||
Buffer.from(await plain.arrayBuffer()),
|
||||
);
|
||||
});
|
||||
|
||||
it("lets a revalidated font through on a 304", async () => {
|
||||
// Past the server's settle window, so the just-written font gets an ETag.
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(Date.now() + 60_000);
|
||||
const etag = (await load("fonts/Brand.woff2", { "sec-fetch-dest": "font" })).headers.get(
|
||||
"etag",
|
||||
);
|
||||
expect(etag).toBeTruthy();
|
||||
const res = await load("fonts/Brand.woff2", {
|
||||
origin: "null",
|
||||
"sec-fetch-dest": "font",
|
||||
"if-none-match": etag!,
|
||||
});
|
||||
expect(res.status).toBe(304);
|
||||
expectGranted(res);
|
||||
});
|
||||
|
||||
it("refuses a revalidated file that is not a font, even for a font load", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(Date.now() + 60_000);
|
||||
const etag = (await load("logo.png", { "sec-fetch-dest": "image" })).headers.get("etag");
|
||||
expect(etag).toBeTruthy();
|
||||
const res = await load("logo.png", {
|
||||
origin: "null",
|
||||
"sec-fetch-dest": "font",
|
||||
"if-none-match": etag!,
|
||||
});
|
||||
expect(res.status).toBe(304);
|
||||
expectNotGranted(res);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["empty", "fonts/Brand.woff2"],
|
||||
["empty", "scene.js"],
|
||||
["empty", "data.json"],
|
||||
["empty", "scene.html"],
|
||||
["document", "scene.html"],
|
||||
["iframe", "scene.html"],
|
||||
["image", "logo.png"],
|
||||
["style", "fonts/Brand.woff2"],
|
||||
["font", "data.json"],
|
||||
["font", "scene.js"],
|
||||
["script", "data.json"],
|
||||
["script", "fonts/Brand.woff2"],
|
||||
["script", "scene.html"],
|
||||
["script", "comp/scene.html"],
|
||||
// The sub-composition route answers any project file with an HTML page.
|
||||
["script", "comp/scene.js"],
|
||||
["font", "comp/fonts/Brand.woff2"],
|
||||
["toString", "scene.js"],
|
||||
["constructor", "fonts/Brand.woff2"],
|
||||
])("refuses a %s load of %s", async (dest, path) => {
|
||||
const res = await load(path, { origin: "null", "sec-fetch-dest": dest });
|
||||
expect(res.status).toBe(200);
|
||||
expectNotGranted(res);
|
||||
});
|
||||
|
||||
it("refuses a page's own fetch, which carries no Sec-Fetch-Dest it can choose", async () => {
|
||||
expectNotGranted(await load("fonts/Brand.woff2", { origin: "null" }));
|
||||
});
|
||||
|
||||
it.each([["https://evil.example"], ["http://localhost"], [undefined]])(
|
||||
"refuses a font load from origin %s",
|
||||
async (origin) => {
|
||||
const res = await load("fonts/Brand.woff2", {
|
||||
"sec-fetch-dest": "font",
|
||||
...(origin === undefined ? {} : { origin }),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expectNotGranted(res);
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses a missing font", async () => {
|
||||
const res = await load("fonts/Missing.woff2", { origin: "null", "sec-fetch-dest": "font" });
|
||||
expect(res.status).toBe(404);
|
||||
expectNotGranted(res);
|
||||
});
|
||||
|
||||
it("re-bases the composition document under the token and sends no referrer", async () => {
|
||||
const res = await load("comp/scene.html", { "sec-fetch-dest": "iframe" });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("referrer-policy")).toBe("no-referrer");
|
||||
const html = await res.text();
|
||||
const tokened = `/api/projects/demo/preview/~${token}/`;
|
||||
expect(html).toContain(`<base href="${tokened}">`);
|
||||
expect(html.replaceAll(tokened, "")).not.toContain("/api/projects/demo/preview/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("a frame without the project's token", () => {
|
||||
const guessed = "A".repeat(43);
|
||||
it.each([
|
||||
["the plain path", ""],
|
||||
["a guessed token", `~${guessed}/`],
|
||||
["another project's token", () => `~${otherToken}/`],
|
||||
["a token of the wrong length", `~${"A".repeat(42)}/`],
|
||||
])("gets no grant for a font or module script on %s", async (_name, prefix) => {
|
||||
const at = typeof prefix === "function" ? prefix() : prefix;
|
||||
for (const [dest, path] of [
|
||||
["font", "fonts/Brand.woff2"],
|
||||
["script", "scene.js"],
|
||||
]) {
|
||||
const res = await load(path!, { origin: "null", "sec-fetch-dest": dest! }, at);
|
||||
expectNotGranted(res);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a guessed token", `~${"A".repeat(43)}/`],
|
||||
["another project's token", () => `~${otherToken}/`],
|
||||
["a token of the wrong length", `~${"A".repeat(42)}/`],
|
||||
])("is not served at all with %s", async (_name, prefix) => {
|
||||
const at = typeof prefix === "function" ? prefix() : prefix;
|
||||
expect((await load("fonts/Brand.woff2", { "sec-fetch-dest": "font" }, at)).status).toBe(404);
|
||||
});
|
||||
|
||||
it("is not served under an unknown project", async () => {
|
||||
const res = await api.request(
|
||||
`http://localhost/projects/missing/preview/~${token}/fonts/Brand.woff2`,
|
||||
{ headers: { origin: "null", "sec-fetch-dest": "font" } },
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
expectNotGranted(res);
|
||||
});
|
||||
|
||||
it("refuses a font outside the preview path", async () => {
|
||||
const res = await api.request("http://localhost/projects/demo/files/fonts/Brand.woff2", {
|
||||
headers: { origin: "null", "sec-fetch-dest": "font", "sec-fetch-site": "cross-site" },
|
||||
});
|
||||
expectNotGranted(res);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,11 @@
|
||||
import { act } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { TIMELINE_COMPOSITION_MIME } from "../../utils/timelineCompositionDrop";
|
||||
import { mountCompositionsTab } from "./compositionsTabTestUtils";
|
||||
import {
|
||||
mountCompositionsTab,
|
||||
settleFrameToken,
|
||||
stubFrameTokenFetch,
|
||||
} from "./compositionsTabTestUtils";
|
||||
|
||||
function mount(onSelect = vi.fn(), onAddToTimeline = vi.fn()) {
|
||||
const host = mountCompositionsTab({ onSelect, onAddToTimeline });
|
||||
@@ -13,15 +17,17 @@ function mount(onSelect = vi.fn(), onAddToTimeline = vi.fn()) {
|
||||
}
|
||||
|
||||
describe("composition card drag", () => {
|
||||
it("mounts one live preview only after sustained hover and removes it on leave", () => {
|
||||
it("mounts one live preview only after sustained hover and removes it on leave", async () => {
|
||||
vi.useFakeTimers();
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const tokenFetch = stubFrameTokenFetch();
|
||||
try {
|
||||
const { host, card } = mount();
|
||||
act(() => {
|
||||
card.dispatchEvent(new Event("pointerover", { bubbles: true }));
|
||||
vi.advanceTimersByTime(300);
|
||||
});
|
||||
await settleFrameToken();
|
||||
expect(host.querySelectorAll("iframe")).toHaveLength(1);
|
||||
|
||||
act(() => {
|
||||
@@ -30,6 +36,7 @@ describe("composition card drag", () => {
|
||||
expect(host.querySelector("iframe")).toBeNull();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
tokenFetch.mockRestore();
|
||||
consoleError.mockRestore();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
|
||||
import { act } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { mountCompositionsTab } from "./compositionsTabTestUtils";
|
||||
import {
|
||||
FRAME_TOKEN,
|
||||
mountCompositionsTab,
|
||||
settleFrameToken,
|
||||
stubFrameTokenFetch,
|
||||
} from "./compositionsTabTestUtils";
|
||||
|
||||
type PostedControl = { source: string; type: string; action: string; muted?: boolean };
|
||||
|
||||
function hoverPreview() {
|
||||
async function hoverPreview() {
|
||||
const host = mountCompositionsTab();
|
||||
const card = host.querySelector<HTMLElement>('[draggable="true"]');
|
||||
if (!card) throw new Error("composition card did not render");
|
||||
@@ -14,6 +19,7 @@ function hoverPreview() {
|
||||
card.dispatchEvent(new Event("pointerover", { bubbles: true }));
|
||||
vi.advanceTimersByTime(300);
|
||||
});
|
||||
await settleFrameToken();
|
||||
const iframe = host.querySelector("iframe");
|
||||
if (!iframe) throw new Error("hover preview did not mount");
|
||||
// Stand-in for the frame's window. The document getter throws, as reading into
|
||||
@@ -48,23 +54,37 @@ let consoleError: ReturnType<typeof vi.spyOn>;
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
stubFrameTokenFetch();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
consoleError.mockRestore();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("composition card hover preview", () => {
|
||||
it("frames the composition in an opaque origin", () => {
|
||||
const { iframe } = hoverPreview();
|
||||
it("frames the composition in an opaque origin, at the project's token path", async () => {
|
||||
const { iframe } = await hoverPreview();
|
||||
expect(iframe.getAttribute("src")).toBe(
|
||||
`/api/projects/demo/preview/~${FRAME_TOKEN}/comp/compositions/headline.html`,
|
||||
);
|
||||
expect(iframe.getAttribute("sandbox")).toBe("allow-scripts");
|
||||
expect(iframe.sandbox.contains("allow-scripts")).toBe(true);
|
||||
expect(iframe.sandbox.contains("allow-same-origin")).toBe(false);
|
||||
});
|
||||
|
||||
it("plays muted over the runtime bridge once the runtime is listening", () => {
|
||||
const { frameWindow } = hoverPreview();
|
||||
it("falls back to the plain path when the token is unavailable", async () => {
|
||||
vi.restoreAllMocks();
|
||||
stubFrameTokenFetch(null);
|
||||
const { iframe } = await hoverPreview();
|
||||
expect(iframe.getAttribute("src")).toBe(
|
||||
"/api/projects/demo/preview/comp/compositions/headline.html",
|
||||
);
|
||||
});
|
||||
|
||||
it("plays muted over the runtime bridge once the runtime is listening", async () => {
|
||||
const { frameWindow } = await hoverPreview();
|
||||
expect(frameWindow.postMessage).not.toHaveBeenCalled();
|
||||
|
||||
fromFrame(frameWindow, { type: "ready" });
|
||||
@@ -79,8 +99,8 @@ describe("composition card hover preview", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("sizes the stage from the runtime's timeline message", () => {
|
||||
const { iframe, frameWindow } = hoverPreview();
|
||||
it("sizes the stage from the runtime's timeline message", async () => {
|
||||
const { iframe, frameWindow } = await hoverPreview();
|
||||
expect([iframe.style.width, iframe.style.height]).toEqual(["1920px", "1080px"]);
|
||||
|
||||
fromFrame(frameWindow, { type: "timeline", compositionWidth: 1080, compositionHeight: 1920 });
|
||||
@@ -88,8 +108,8 @@ describe("composition card hover preview", () => {
|
||||
expect([iframe.style.width, iframe.style.height]).toEqual(["1080px", "1920px"]);
|
||||
});
|
||||
|
||||
it("ignores runtime messages that come from another window", () => {
|
||||
const { iframe, frameWindow } = hoverPreview();
|
||||
it("ignores runtime messages that come from another window", async () => {
|
||||
const { iframe, frameWindow } = await hoverPreview();
|
||||
|
||||
fromFrame({ postMessage: vi.fn() }, { type: "ready" });
|
||||
fromFrame(window, { type: "timeline", compositionWidth: 640, compositionHeight: 640 });
|
||||
|
||||
@@ -8,7 +8,7 @@ import { TIMELINE_VIEWPORT_BUDGETS } from "../../player/lib/timelineViewportBudg
|
||||
import { CompositionThumbnail } from "../../player/components/CompositionThumbnail";
|
||||
import { usePlayerStore } from "../../player/store/playerStore";
|
||||
import { renderPosterForNextOpen } from "../nle/PreviewPoster";
|
||||
import { mountCompositionsTab } from "./compositionsTabTestUtils";
|
||||
import { mountCompositionsTab, settleFrameToken } from "./compositionsTabTestUtils";
|
||||
|
||||
class DecodingImage {
|
||||
onload: (() => void) | null = null;
|
||||
@@ -247,7 +247,7 @@ describe("composition card thumbnails", () => {
|
||||
expect(URL.revokeObjectURL).not.toHaveBeenCalledWith("blob:frame-2");
|
||||
});
|
||||
|
||||
it("tell a hover preview how large it shows, so its videos are not copied at source size", () => {
|
||||
it("tell a hover preview how large it shows, so its videos are not copied at source size", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const host = mount();
|
||||
@@ -258,6 +258,8 @@ describe("composition card thumbnails", () => {
|
||||
);
|
||||
});
|
||||
act(() => vi.advanceTimersByTime(300));
|
||||
renders.at(-1)!.answer(404); // the hover preview's frame-token request
|
||||
await settleFrameToken();
|
||||
const frame = host.querySelector("iframe")!;
|
||||
const postMessage = vi.fn();
|
||||
Object.defineProperty(frame, "contentWindow", { value: { postMessage } });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { buildProjectApiPath } from "../../utils/projectRouting";
|
||||
import { studioApiFetch } from "../../utils/studioApiFetch";
|
||||
import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useThumbnailLease } from "../../hooks/useThumbnailLease";
|
||||
import {
|
||||
@@ -61,6 +62,30 @@ function compositionPreviewUrl(projectId: string, comp: string): string {
|
||||
return buildProjectApiPath(projectId, `/preview/comp/${encodePreviewPath(comp)}`);
|
||||
}
|
||||
|
||||
function framePreviewUrl(projectId: string, comp: string, frameToken: string | null): string {
|
||||
const tokenPrefix = frameToken ? `/~${frameToken}` : "";
|
||||
return buildProjectApiPath(projectId, `/preview${tokenPrefix}/comp/${encodePreviewPath(comp)}`);
|
||||
}
|
||||
|
||||
function useFreshFrameToken(projectId: string, wanted: boolean): string | null | undefined {
|
||||
const [known, setKnown] = useState<{ token: string | null } | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
if (!wanted) return setKnown(undefined);
|
||||
let live = true;
|
||||
void studioApiFetch(buildProjectApiPath(projectId, "/frame-token"))
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((body: { token?: unknown } | null) =>
|
||||
typeof body?.token === "string" ? body.token : null,
|
||||
)
|
||||
.catch(() => null)
|
||||
.then((token) => live && setKnown({ token }));
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [projectId, wanted]);
|
||||
return known?.token;
|
||||
}
|
||||
|
||||
export function compositionCardThumbnailUrl(
|
||||
projectId: string,
|
||||
comp: string,
|
||||
@@ -173,7 +198,7 @@ function CompCard({
|
||||
setLivePreviewLoaded(false);
|
||||
};
|
||||
const name = comp.replace(/^compositions\//, "").replace(/\.html$/, "");
|
||||
const previewUrl = compositionPreviewUrl(projectId, comp);
|
||||
const frameToken = useFreshFrameToken(projectId, hovered);
|
||||
const thumbnailUrl = compositionCardThumbnailUrl(projectId, comp, contentRevision);
|
||||
const [thumbnailBox, nearViewport] = useNearViewport<HTMLDivElement>();
|
||||
const timelineSessionEpoch = usePlayerStore((state) => state.timelineSessionEpoch);
|
||||
@@ -287,10 +312,10 @@ function CompCard({
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
{hovered && (
|
||||
{hovered && frameToken !== undefined && (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={previewUrl}
|
||||
src={framePreviewUrl(projectId, comp, frameToken)}
|
||||
sandbox={OPAQUE_ORIGIN_SCRIPTS_ONLY_SANDBOX}
|
||||
className="absolute border-none pointer-events-none"
|
||||
style={{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { act, type ComponentProps } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, vi } from "vitest";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
import { thumbnailScheduler } from "../../player/lib/thumbnailScheduler";
|
||||
import { usePlayerStore } from "../../player/store/playerStore";
|
||||
import { CompositionsTab } from "./CompositionsTab";
|
||||
@@ -37,3 +37,18 @@ export function mountCompositionsTab(props: Partial<ComponentProps<typeof Compos
|
||||
});
|
||||
return host;
|
||||
}
|
||||
|
||||
export const FRAME_TOKEN = "T".repeat(43);
|
||||
|
||||
export function stubFrameTokenFetch(token: string | null = FRAME_TOKEN) {
|
||||
return vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
||||
expect(String(input)).toBe("/api/projects/demo/frame-token");
|
||||
return { ok: token !== null, json: async () => ({ token }) } as Response;
|
||||
});
|
||||
}
|
||||
|
||||
export async function settleFrameToken() {
|
||||
await act(async () => {
|
||||
for (let i = 0; i < 10; i += 1) await Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
"unpacked": 26703858
|
||||
},
|
||||
"@hyperframes/studio-server": {
|
||||
"packed": 164800,
|
||||
"packed": 168500,
|
||||
"unpacked": 646000
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user