// @vitest-environment node import { afterAll, afterEach, 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 { parseHTML } from "linkedom"; import { PREVIEW_DOCUMENT_HANDOFF } from "@hyperframes/core/studio-preview-mark"; import { createStudioApi } from "../createStudioApi"; import { createPreviewDocumentTickets, withDocumentSecret, } from "../helpers/previewDocumentTickets"; import type { StudioApiAdapter } from "../types"; const root = mkdtempSync(join(tmpdir(), "hf-preview-document-ticket-")); afterAll(() => rmSync(root, { recursive: true, force: true })); afterEach(() => vi.useRealTimers()); const STAGE = '
'; const RUNTIME = ''; let made = 0; function studio( html = `${STAGE}`, transformPreviewHtml?: StudioApiAdapter["transformPreviewHtml"], ) { const dir = join(root, `p${++made}`); mkdirSync(dir); writeFileSync(join(dir, "index.html"), html); writeFileSync(join(dir, "scene.html"), html); const api = createStudioApi({ listProjects: () => [], resolveProject: async (id) => ({ id, dir }), bundle: async () => null, transformPreviewHtml, lint: async () => ({ findings: [] }), runtimeUrl: "/api/runtime.js", rendersDir: () => join(dir, "renders"), startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "out.mp4" }), }); const at = ( path: string, headers: Record = { "sec-fetch-site": "same-origin" }, ) => api.request(`http://localhost/projects/demo/${path}`, { headers }); /** `path` as the frame's own document. */ const page = (path: string, headers = {}) => at(path, { "sec-fetch-site": "same-origin", "sec-fetch-dest": "iframe", ...headers }); const ticket = async (): Promise<{ ticket: string; secret: string }> => (await at("preview-ticket")).json(); return { at, page, ticket }; } const runtimeTags = (page: string) => [ ...parseHTML(page).document.querySelectorAll('script[src="/api/runtime.js"]'), ]; function expectBracketedRuntime(page: string, secret: string) { const tags = runtimeTags(page); expect(tags).toHaveLength(1); const runtime = tags[0]!; expect(runtime.hasAttribute("data-hf-doc")).toBe(false); const before = runtime.previousElementSibling; const after = runtime.nextElementSibling; expect(before?.tagName.toLowerCase()).toBe("script"); expect(before?.textContent).toContain(secret); expect(before?.textContent).toContain("c.remove()"); expect(after?.tagName.toLowerCase()).toBe("script"); expect(after?.textContent).toContain(PREVIEW_DOCUMENT_HANDOFF); expect(after?.textContent).toContain("c.remove()"); expect(after?.textContent).not.toContain(secret); } describe("a sealed preview's document ticket", () => { // fails without the fix: the page under a ticket carried nothing Studio could tell it by. it.each(["preview", "preview/comp/scene.html"])( "brackets the runtime tag of %s with a self-removing handoff and wipe, for the first request only", async (path) => { const { at, page: load, ticket } = studio(); const { ticket: spent, secret } = await ticket(); const first = await load(`${path}?hf-doc=${spent}`); expect(first.headers.get("cache-control")).toBe("no-store"); expect(first.headers.get("etag")).toBeNull(); const page = await first.text(); expectBracketedRuntime(page, secret); expect(page.split(secret)).toHaveLength(2); const again = await load(`${path}?hf-doc=${spent}`); expect(again.headers.get("cache-control")).toBe("no-store"); expect(await again.text()).not.toContain(secret); expect(await (await at(path)).text()).not.toContain(PREVIEW_DOCUMENT_HANDOFF); }, ); it("gives its secret to a page the browser holds a copy of, never a 304", async () => { const { at, page: load, ticket } = studio(); const etag = (await at("preview")).headers.get("etag")!; const { ticket: open, secret } = await ticket(); const res = await load(`preview?hf-doc=${open}`, { "if-none-match": etag }); expect(res.status).toBe(200); expectBracketedRuntime(await res.text(), secret); }); it("reaches the page loaded under the project's frame token", async () => { const { at, page: load, ticket } = studio(); const { token } = await (await at("frame-token")).json(); const { ticket: open, secret } = await ticket(); const res = await load(`preview/~${token}?hf-doc=${open}`); expect(res.headers.get("cache-control")).toBe("no-store"); expectBracketedRuntime(await res.text(), secret); }); // fails without the fix: the player's own read of a reloaded page spent the ticket, so the page edited nothing. it.each([ { "sec-fetch-dest": "empty" }, { "sec-fetch-dest": "empty", accept: "text/html" }, { accept: "*/*" }, ])("is neither spent by a read of the page nor answered to one: %o", async (headers) => { const { at, page: load, ticket } = studio(); const { ticket: open, secret } = await ticket(); const read = await at(`preview?hf-doc=${open}`, { "sec-fetch-site": "same-origin", ...headers, }); expect(await read.text()).not.toContain(secret); expect(await (await load(`preview?hf-doc=${open}`)).text()).toContain(secret); }); it("goes to the frame's page where the browser sends no Sec-Fetch headers", async () => { const { at, ticket } = studio(); const { ticket: open, secret } = await ticket(); const res = await at(`preview?hf-doc=${open}`, { accept: "text/html,application/xhtml+xml" }); expect(await res.text()).toContain(secret); }); it.each(["cross-site", "same-site"])("is refused to a %s request", async (site) => { const res = await studio().at("preview-ticket", { "sec-fetch-site": site }); expect(res.status).toBe(403); }); it("is never stored, and is new each time", async () => { const { at, ticket } = studio(); expect((await at("preview-ticket")).headers.get("cache-control")).toBe("no-store"); const given = [await ticket(), await ticket()].flatMap((t) => [t.ticket, t.secret]); expect(new Set(given).size).toBe(4); for (const value of given) expect(value).toMatch(/^[\w-]{43}$/); }); it("expires", () => { let now = 0; const tickets = createPreviewDocumentTickets(() => now); const early = tickets.mint(); now = 60_000; expect(tickets.spend(early.ticket)).toBe(early.secret); const late = tickets.mint(); now = 120_001; expect(tickets.spend(late.ticket)).toBeNull(); }); }); // The outer tag keeps the inner one from being taken for a baked runtime and stripped. const DECOY = ''; const rewrites: Array<[string, StudioApiAdapter["transformPreviewHtml"]]> = [ ["no host step", undefined], ["a host step that re-writes the page", ({ html }) => parseHTML(html).document.toString()], ]; const decoys: Array<[string, string]> = [ [ "an attribute", `${STAGE}`, ], [ "a comment before the document", `${STAGE}`, ], [ "a title", `${DECOY}${STAGE}`, ], ["its own tag", `${DECOY}${STAGE}`], ]; describe("the secret of a page that spells the runtime's tag itself", () => { // fails without the fix: the secret went on the first text that read like the runtime's tag. it.each( decoys.flatMap(([where, html]) => rewrites.map(([step, fn]) => [where, step, html, fn] as const), ), )("is only around the runtime's own tag: %s, %s", async (_where, _step, html, fn) => { const { page: load, ticket } = studio(html, fn); const { ticket: open, secret } = await ticket(); const page = await (await load(`preview?hf-doc=${open}`)).text(); expect(page.split(secret)).toHaveLength(2); expectBracketedRuntime(page, secret); }); }); it("brackets the tag after a comment a browser ends early, never text in an attribute", () => { const html = `${RUNTIME}`; const page = withDocumentSecret(html, "s1"); expect(page.split("s1")).toHaveLength(2); expect(page).toContain(``, ``, ``, ``, ])("is not on the page: %s", (html) => { expect(withDocumentSecret(html, "s1")).toBe(html); }); it("is on a page whose handlers only its body has", () => { const html = `${RUNTIME}`; expectBracketedRuntime(withDocumentSecret(html, "s1"), "s1"); }); it("allows a runtime src path containing words like type or defer", () => { const html = ``; const page = withDocumentSecret(html, "s1"); expect(page).toContain('"s1"'); expect(page).toContain(PREVIEW_DOCUMENT_HANDOFF); }); });