fix: present refuses other sites' framing; Studio preview reads only its own frame's messages (#7877)

* fix(studio): the preview reads hf-preview messages only from its own frame

The preview message router acted on a message with no sender window, and on
any message that arrived before the preview frame existed. It now takes an
hf-preview message only when the preview frame exists, the message comes from
that frame's window, and its origin is one the frame can have: the page's own
origin, or "null" for a sealed frame. The element picker checks the same.

* fix(cli): present sandboxes deck pages another site loads and refuses framing by other sites

present now applies the same another-site decision as play to its
/composition/* route: a load by another site gets a sandbox CSP, its
validators are dropped, and the document is marked so its runtime offers
that site no editing port. Every present response also sends
frame-ancestors 'self' and X-Frame-Options SAMEORIGIN, so only the
presenter page itself can frame the deck. The route setup moves into
buildPresentApp so tests exercise the server as run() builds it.
This commit is contained in:
Michael Wang
2026-11-16 00:30:46 +00:00
committed by GitHub
parent ace8a78dcc
commit 4067efc454
9 changed files with 224 additions and 42 deletions
+73
View File
@@ -0,0 +1,73 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildPresentApp } from "./present.js";
const MARK = '<meta name="hyperframes-preview-for-another-site">';
const SANDBOX = "sandbox allow-scripts";
const FRAME_ANCESTORS = "frame-ancestors 'self'";
let dir: string | undefined;
afterEach(() => {
vi.unstubAllEnvs();
if (dir) rmSync(dir, { recursive: true, force: true });
dir = undefined;
});
async function presentApp() {
dir = mkdtempSync(join(tmpdir(), "hf-present-test-"));
writeFileSync(join(dir, "index.html"), "<html><head></head><body></body></html>");
return buildPresentApp({ dir, name: "deck", indexPath: join(dir, "index.html") }, "{}", {
playerPath: join(dir, "player.js"),
slideshowPath: join(dir, "slideshow.js"),
});
}
describe("a deck document another site loads", () => {
it("is marked and sandboxed when another site frames it", async () => {
const app = await presentApp();
const res = await app.request("/composition/index.html", {
headers: { "Sec-Fetch-Site": "cross-site", "Sec-Fetch-Dest": "iframe" },
});
expect(res.status).toBe(200);
expect(await res.text()).toContain(MARK);
expect(res.headers.get("Content-Security-Policy")).toBe(`${SANDBOX}, ${FRAME_ANCESTORS}`);
});
it("stays unmarked for the presenter page's own player", async () => {
const app = await presentApp();
const res = await app.request("/composition/index.html", {
headers: { "Sec-Fetch-Site": "same-origin", "Sec-Fetch-Dest": "iframe" },
});
expect(res.status).toBe(200);
expect(await res.text()).not.toContain(MARK);
expect(res.headers.get("Content-Security-Policy")).toBe(FRAME_ANCESTORS);
});
it("is marked on a named host with no fetch metadata unless the presenter page sent it", async () => {
vi.stubEnv("HYPERFRAMES_PREVIEW_ALLOWED_HOSTS", "deck.example");
const app = await presentApp();
const origin = "http://deck.example:3004";
const foreign = await app.request(`${origin}/composition/index.html`);
expect(await foreign.text()).toContain(MARK);
const own = await app.request(`${origin}/composition/index.html`, {
headers: { Referer: `${origin}/` },
});
expect(await own.text()).not.toContain(MARK);
});
});
describe("pages the present server answers", () => {
it.each(["/", "/composition/index.html"])(
"may be framed only by its own pages: %s",
async (path) => {
const app = await presentApp();
const res = await app.request(path, { headers: { "Sec-Fetch-Site": "same-origin" } });
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy")).toBe(FRAME_ANCESTORS);
expect(res.headers.get("X-Frame-Options")).toBe("SAMEORIGIN");
},
);
});
+38 -26
View File
@@ -28,6 +28,8 @@ import {
resolveSlideshowPath,
listenOnFreePort,
refuseUnknownHosts,
refuseFramingByOtherSites,
sandboxForAnotherSite,
assetContentType,
} from "../utils/compositionServer.js";
import { isPrivateCompositionFile } from "../utils/privateProjectFile.js";
@@ -120,33 +122,8 @@ export default defineCommand({
return;
}
const { Hono } = await import("hono");
const { createAdaptorServer } = await import("@hono/node-server");
const app = new Hono();
refuseUnknownHosts(app);
app.get("/player.js", (ctx) =>
ctx.body(readFileSync(playerPath, "utf-8"), 200, {
"Content-Type": "application/javascript",
"Cache-Control": "no-cache",
}),
);
app.get("/slideshow.js", (ctx) =>
ctx.body(readFileSync(slideshowPath, "utf-8"), 200, {
"Content-Type": "application/javascript",
"Cache-Control": "no-cache",
}),
);
// Serve composition files raw. Slideshow compositions self-drive their own
// timelines (no engine runtime injected) — the same model demo.html / the
// standalone harness use; injecting a runtime would leave the composition
// engine-paused and blank.
await registerPresentCompositionRoute(app, project);
// Both the presenter window and the audience window (opened by present() with
// ?mode=audience) load this same page; the component reads the mode from the URL.
app.get("/", (ctx) => ctx.html(buildPresentPage(project.name, islandJson)));
const app = await buildPresentApp(project, islandJson, { playerPath, slideshowPath });
clack.intro(c.bold("hyperframes present"));
const s = clack.spinner();
@@ -188,6 +165,40 @@ export default defineCommand({
},
});
export async function buildPresentApp(
project: ProjectDir,
islandJson: string,
bundles: { playerPath: string; slideshowPath: string },
): Promise<Hono> {
const { Hono } = await import("hono");
const app = new Hono();
refuseUnknownHosts(app);
refuseFramingByOtherSites(app);
app.get("/player.js", (ctx) =>
ctx.body(readFileSync(bundles.playerPath, "utf-8"), 200, {
"Content-Type": "application/javascript",
"Cache-Control": "no-cache",
}),
);
app.get("/slideshow.js", (ctx) =>
ctx.body(readFileSync(bundles.slideshowPath, "utf-8"), 200, {
"Content-Type": "application/javascript",
"Cache-Control": "no-cache",
}),
);
// Serve composition files raw. Slideshow compositions self-drive their own
// timelines (no engine runtime injected) — the same model demo.html / the
// standalone harness use; injecting a runtime would leave the composition
// engine-paused and blank.
await registerPresentCompositionRoute(app, project);
// Both the presenter window and the audience window (opened by present() with
// ?mode=audience) load this same page; the component reads the mode from the URL.
app.get("/", (ctx) => ctx.html(buildPresentPage(project.name, islandJson)));
return app;
}
function buildPresentPage(projectName: string, islandJson: string): string {
return `<!doctype html>
<html lang="en">
@@ -315,6 +326,7 @@ export async function registerPresentCompositionRoute(
project: ProjectDir,
): Promise<void> {
const { isSafePath } = await import("@hyperframes/core/studio-api");
sandboxForAnotherSite(app, "/composition/*");
app.get("/composition/*", (ctx) => {
const reqPath = requestSubPath(ctx.req.url, "composition");
const filePath = resolve(project.dir, reqPath);
@@ -16,6 +16,7 @@ import {
requestFromAnotherSite,
wildcardBindHostAllowed,
} from "@hyperframes/studio-server/request-identity";
import { SAME_ORIGIN_FRAMING_HEADERS } from "@hyperframes/engine";
import type { Context, Hono } from "hono";
/**
@@ -243,6 +244,16 @@ export function sandboxForAnotherSite(app: Hono, path: string): void {
});
}
/** The runtime hands an editing port to its parent frame, so only this server's own pages may frame what it serves. */
export function refuseFramingByOtherSites(app: Hono): void {
app.use(async function sameOriginFramingOnly(c, next) {
await next();
for (const [name, value] of Object.entries(SAME_ORIGIN_FRAMING_HEADERS)) {
c.res.headers.append(name, value);
}
});
}
/**
* Bind `server` to the first free port at or after `startPort` (scanning up to
* 10 ports). Returns the bound port. Rejects if all candidates are in use or on
@@ -41,6 +41,7 @@ function routeStateTicks(opaque: boolean) {
handle(
new MessageEvent("message", {
source: frame as unknown as Window,
origin: window.location.origin,
data: { source: "hf-preview", type: "state", isPlaying: false },
}),
);
@@ -1,18 +1,34 @@
// @vitest-environment happy-dom
import { describe, expect, it, vi } from "vitest";
import { usePlayerStore } from "../store/playerStore";
import { createPreviewMessageHandler } from "./previewMessageRouter";
import { detachedFakeIframe } from "./timelinePlayerTestHarness";
/** A preview frame and a post from its window, from the origin it loads at. */
function previewFrame(frame: Record<string, unknown> = {}) {
const iframe = detachedFakeIframe(frame);
const post = (data: unknown) =>
new MessageEvent("message", {
source: frame as unknown as Window,
origin: window.location.origin,
data,
});
return { iframe, post };
}
function route(isPlaying: boolean) {
const enrich = vi.fn();
const { iframe, post } = previewFrame();
const handle = createPreviewMessageHandler({
iframeRef: { current: null },
iframeRef: { current: iframe },
processTimelineMessageRef: { current: vi.fn() },
enrichMissingCompositionsRef: { current: enrich },
lastTimelineMessageRef: { current: 0 },
getAdapter: () => null,
syncTimelineElements: vi.fn(),
});
handle(new MessageEvent("message", { data: { source: "hf-preview", type: "state", isPlaying } }));
handle(post({ source: "hf-preview", type: "state", isPlaying }));
return enrich;
}
@@ -29,20 +45,16 @@ describe("preview state messages while a scrub posts them", () => {
try {
vi.setSystemTime(10_000);
const enrich = vi.fn();
const { iframe, post } = previewFrame();
const handle = createPreviewMessageHandler({
iframeRef: { current: null },
iframeRef: { current: iframe },
processTimelineMessageRef: { current: vi.fn() },
enrichMissingCompositionsRef: { current: enrich },
lastTimelineMessageRef: { current: 0 },
getAdapter: () => null,
syncTimelineElements: vi.fn(),
});
const state = () =>
handle(
new MessageEvent("message", {
data: { source: "hf-preview", type: "state", isPlaying: false },
}),
);
const state = () => handle(post({ source: "hf-preview", type: "state", isPlaying: false }));
state();
vi.advanceTimersByTime(100);
state();
@@ -58,8 +70,8 @@ describe("preview state messages while a scrub posts them", () => {
});
describe("preview quality messages", () => {
function routeMessage(data: unknown, frame?: { postMessage: (message: unknown) => void }) {
const iframe = frame ? ({ contentWindow: frame } as unknown as HTMLIFrameElement) : null;
function routeMessage(data: unknown, frame: Record<string, unknown> = {}) {
const { iframe, post } = previewFrame(frame);
createPreviewMessageHandler({
iframeRef: { current: iframe },
processTimelineMessageRef: { current: vi.fn() },
@@ -67,7 +79,7 @@ describe("preview quality messages", () => {
lastTimelineMessageRef: { current: 0 },
getAdapter: () => null,
syncTimelineElements: vi.fn(),
})(new MessageEvent("message", { data }));
})(post(data));
}
it("keeps what the preview says about its lighter copies, and clears it when it says none", () => {
@@ -182,3 +194,69 @@ describe("preview quality messages", () => {
usePlayerStore.getState().setPreviewQuality(1);
});
});
describe("messages that do not come from the preview frame", () => {
const facts = {
sceneCount: 1,
mountedElementCount: 1,
durationSeconds: 1,
videos: [],
lighterAt: [],
copiesReady: true,
};
const report = { source: "hf-preview", type: "preview-facts", facts };
function deliver(iframe: HTMLIFrameElement | null, event: MessageEvent) {
usePlayerStore.getState().setPreviewFacts(null);
createPreviewMessageHandler({
iframeRef: { current: iframe },
processTimelineMessageRef: { current: vi.fn() },
enrichMissingCompositionsRef: { current: vi.fn() },
lastTimelineMessageRef: { current: 0 },
getAdapter: () => null,
syncTimelineElements: vi.fn(),
})(event);
return usePlayerStore.getState().previewFacts;
}
const from = (source: unknown, origin: string) =>
new MessageEvent("message", {
source: source as Window,
origin,
data: report,
});
it("ignores a report with no sender window", () => {
const { iframe } = previewFrame();
expect(deliver(iframe, from(null, window.location.origin))).toBeNull();
});
it("ignores a report that arrives before the preview frame exists", () => {
expect(deliver(null, from({}, window.location.origin))).toBeNull();
});
it("ignores a report from a window that is not the preview frame", () => {
const { iframe } = previewFrame();
expect(deliver(iframe, from({}, window.location.origin))).toBeNull();
});
it("ignores a report from the preview frame's window at an origin that frame cannot have", () => {
const frame = {};
const { iframe } = previewFrame(frame);
expect(deliver(iframe, from(frame, "https://another.example"))).toBeNull();
});
it("accepts a sealed preview frame's report only from its opaque origin", () => {
const frame = {};
const { iframe } = previewFrame(frame);
iframe.setAttribute("sandbox", "allow-scripts");
expect(deliver(iframe, from(frame, window.location.origin))).toBeNull();
expect(deliver(iframe, from(frame, "null"))).toEqual(facts);
});
it("accepts the preview frame's report from the origin it loads at", () => {
const frame = {};
const { iframe } = previewFrame(frame);
expect(deliver(iframe, from(frame, window.location.origin))).toEqual(facts);
});
});
@@ -24,6 +24,7 @@ import {
} from "../store/previewQualitySlice";
import { parseTimelineFromDOM } from "../lib/timelineDOM";
import { previewClipManifest, previewFrameOpaque } from "../lib/previewChannel";
import { frameOrigins } from "../lib/bridgePlayback";
/** What `processTimelineMessage` accepts — the clip-manifest postMessage. */
export interface ClipManifestMessage {
@@ -57,9 +58,10 @@ export interface PreviewMessageRouterDeps {
syncTimelineElements: (elements: TimelineElement[]) => void;
}
/** True when the message did not come from OUR preview iframe. */
function isForeignSource(e: MessageEvent, iframe: HTMLIFrameElement | null): boolean {
return Boolean(e.source && iframe && e.source !== iframe.contentWindow);
/** True only for a post by our preview iframe's window, from an origin that frame can have. */
function fromOurPreview(e: MessageEvent, iframe: HTMLIFrameElement | null): boolean {
if (!iframe || !e.source || e.source !== iframe.contentWindow) return false;
return frameOrigins(iframe).includes(e.origin);
}
/** A preview message worth acting on, or null: the fixture lease, the sender
@@ -70,7 +72,7 @@ function acceptedPreviewMessage(
iframe: HTMLIFrameElement | null,
): PreviewMessage | null {
if (hasTimelinePerformanceFixtureLease()) return null;
if (isForeignSource(e, iframe)) return null;
if (!fromOurPreview(e, iframe)) return null;
const data = e.data as PreviewMessage | null;
if (data?.source !== "hf-preview") return null;
return acceptStudioRuntimeMessage(data) ? data : null;
@@ -91,6 +91,7 @@ it("publishes resolved metadata only for clips that still need it", async () =>
window.dispatchEvent(
new MessageEvent("message", {
source: frame,
origin: window.location.origin,
data: { source: "hf-preview", type: "timeline", clips, durationInFrames: 18000, fps: 30 },
}),
);
@@ -64,6 +64,7 @@ function postFromRuntime(win: object, data: Record<string, unknown>) {
window.dispatchEvent(
new MessageEvent("message", {
source: win as unknown as Window,
origin: window.location.origin,
data: { source: "hf-preview", ...data },
}),
);
@@ -87,6 +87,7 @@ describe("useTimelinePlayer seek hydration", () => {
window.dispatchEvent(
new MessageEvent("message", {
source: iframeWindow,
origin: window.location.origin,
data: {
source: "hf-preview",
type: "timeline",
@@ -164,6 +165,7 @@ describe("useTimelinePlayer seek hydration", () => {
window.dispatchEvent(
new MessageEvent("message", {
source: iframeWindow as unknown as Window,
origin: window.location.origin,
data: { source: "hf-preview", type: "state", protocolVersion: 999 },
}),
);
@@ -174,6 +176,7 @@ describe("useTimelinePlayer seek hydration", () => {
window.dispatchEvent(
new MessageEvent("message", {
source: iframeWindow as unknown as Window,
origin: window.location.origin,
data: { source: "hf-preview", type: "state" },
}),
);