fix: LAN-host previews and play pages refuse other sites without fetch metadata (#7836)

* fix(studio-server): previews with no fetch metadata on a LAN host count as another site

Browsers send no Sec-Fetch-Site header over plain HTTP to a non-loopback
name, such as a LAN address used with HYPERFRAMES_PREVIEW_HOST. The preview
guards now count such a request as the Studio's own page only when its
Referer names the same host. Otherwise the preview is marked and sandboxed,
its validators are dropped, and the thumbnail, waveform, peaks and
frame-token routes refuse it.

* fix(cli): play marks and sandboxes compositions another site loads

The play server's /composition/* route now applies the same another-site
decision as the Studio preview. A load from another site comes back with
the sandbox CSP and without validators, and its HTML carries the
hyperframes-preview-for-another-site mark, so the runtime offers that site
no editing port. The play page's own player is unchanged.

* fix(player): send a same-origin Referer from the composition frame

The player's composition iframe used no-referrer, so on a plain-HTTP LAN
host its own composition load carried neither Sec-Fetch-Site nor Referer
and the Studio and play servers sandboxed it as another site's load.
same-origin sends the host page's URL only to a composition on the same
origin, so another origin still learns nothing about the embedding page.
This commit is contained in:
Michael Wang
2026-11-15 12:34:43 +00:00
committed by GitHub
parent a7266e4c83
commit 2ceb682f92
8 changed files with 183 additions and 9 deletions
+56
View File
@@ -433,3 +433,59 @@ describe("registerCompositionRoute", () => {
expect(mocks.resolveProxy).not.toHaveBeenCalled();
});
});
describe("a composition document another site loads", () => {
const MARK = '<meta name="hyperframes-preview-for-another-site">';
const SANDBOX = "sandbox allow-scripts";
async function setup() {
const project = tmpProject();
writeFileSync(join(project.dir, "index.html"), "<html><head></head><body></body></html>");
return buildApp(project, false);
}
it("is marked and sandboxed when another site frames it", async () => {
const app = await setup();
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);
expect(res.headers.get("ETag")).toBeNull();
});
it("gets a marked 200, not a 304, for the unmarked copy's validators", async () => {
const app = await setup();
const own = await app.request("/composition/index.html", {
headers: { "Sec-Fetch-Site": "same-origin" },
});
const etag = own.headers.get("ETag") ?? "";
expect(etag).not.toBe("");
const res = await app.request("/composition/index.html", {
headers: { "Sec-Fetch-Site": "cross-site", "If-None-Match": etag },
});
expect(res.status).toBe(200);
expect(await res.text()).toContain(MARK);
});
it("stays unmarked for the play page's own player", async () => {
const app = await setup();
const res = await app.request("/composition/index.html", {
headers: { "Sec-Fetch-Site": "same-origin", "Sec-Fetch-Dest": "iframe" },
});
expect(await res.text()).not.toContain(MARK);
expect(res.headers.get("Content-Security-Policy")).toBeNull();
});
it("is marked on a LAN name with no fetch metadata unless the play page sent it", async () => {
const app = await setup();
const lan = "http://192.168.1.20:3003";
const foreign = await app.request(`${lan}/composition/index.html`);
expect(await foreign.text()).toContain(MARK);
const own = await app.request(`${lan}/composition/index.html`, {
headers: { Referer: `${lan}/` },
});
expect(await own.text()).not.toContain(MARK);
});
});
+2
View File
@@ -37,6 +37,7 @@ import {
resolvePlayerPath,
listenOnFreePort,
refuseUnknownHosts,
sandboxForAnotherSite,
injectRuntime,
injectMediaCodecMap,
buildRangeResponse,
@@ -223,6 +224,7 @@ export async function registerCompositionRoute(
): Promise<void> {
const { isSafePath } = await import("@hyperframes/core/studio-api");
sandboxForAnotherSite(app, "/composition/*");
// fallow-ignore-next-line complexity
app.get("/composition/*", async (ctx) => {
const reqPath = requestSubPath(ctx.req.url, "composition");
+40 -1
View File
@@ -9,12 +9,14 @@ import { fileURLToPath } from "node:url";
import { getMimeType, openRangeEnd } from "@hyperframes/studio-server";
import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags";
import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document";
import { PREVIEW_FOR_ANOTHER_SITE_META } from "@hyperframes/core/studio-preview-mark";
import {
PREVIEW_ALLOWED_HOSTS_ENV,
previewAllowedHostsFromEnv,
requestFromAnotherSite,
wildcardBindHostAllowed,
} from "@hyperframes/studio-server/request-identity";
import type { Hono } from "hono";
import type { Context, Hono } from "hono";
/**
* `window.__HF_MEDIA_CODEC_MAP__` injection + proxy pre-warm for HTML served
@@ -204,6 +206,43 @@ export function refuseUnknownHosts(app: Hono): void {
});
}
function withoutValidators(request: Request): Request {
const headers = new Headers(request.headers);
headers.delete("if-none-match");
headers.delete("if-modified-since");
return new Request(request, { headers });
}
async function markDocumentForAnotherSite(c: Context): Promise<void> {
if (c.res.status !== 200 || !c.res.headers.get("content-type")?.startsWith("text/html")) return;
const headers = new Headers(c.res.headers);
headers.delete("content-length");
headers.delete("etag");
const marked = injectTagsAtHeadStart(
await c.res.text(),
`<meta name="${PREVIEW_FOR_ANOTHER_SITE_META}">`,
);
c.res = undefined;
c.res = new Response(marked, { status: 200, headers });
}
/** Files under `path` that another site loads come back sandboxed, and documents marked so their runtime offers that site no editing port. */
export function sandboxForAnotherSite(app: Hono, path: string): void {
app.use(path, async function sandboxAnotherSiteLoad(c, next) {
const anotherSite = requestFromAnotherSite({
fetchSite: c.req.header("sec-fetch-site"),
host: c.req.header("host") ?? new URL(c.req.url).host,
referer: c.req.header("referer"),
});
if (anotherSite) c.req.raw = withoutValidators(c.req.raw);
await next();
c.header("Vary", "Sec-Fetch-Site", { append: true });
if (!anotherSite) return;
c.header("Content-Security-Policy", "sandbox allow-scripts");
await markDocumentForAnotherSite(c);
});
}
/**
* 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
@@ -3656,7 +3656,10 @@ describe("HyperframesPlayer retained runtime data", () => {
expect(player.iframeElement.sandbox.contains("allow-scripts")).toBe(true);
expect(player.iframeElement.sandbox.contains("allow-same-origin")).toBe(true);
expect(player.iframeElement.sandbox.contains("allow-top-navigation")).toBe(false);
expect(player.iframeElement.referrerPolicy).toBe("no-referrer");
});
it("sends its host page's URL only to a composition on the same origin", () => {
expect(player.iframeElement.referrerPolicy).toBe("same-origin");
});
it("supports an opaque-origin sandbox for hosts that do not need direct iframe DOM access", () => {
+1 -1
View File
@@ -49,7 +49,7 @@ export function createCompositionIframe(): {
iframe.className = "hfp-iframe";
iframe.sandbox.add("allow-scripts", "allow-same-origin");
iframe.allow = "autoplay; fullscreen";
iframe.referrerPolicy = "no-referrer";
iframe.referrerPolicy = "same-origin";
iframe.title = "HyperFrames Composition";
iframe.setAttribute(PLAYER_FRAME_ATTR, "");
+12 -6
View File
@@ -23,6 +23,7 @@ import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
import {
PREVIEW_ALLOWED_HOSTS_ENV,
requestFromAnotherSite,
requestHost,
sameOriginPost,
} from "./helpers/requestIdentity.js";
@@ -42,10 +43,12 @@ async function answerRefusedFrameWithPage(c: Context, next: Next) {
});
}
const fromAnotherSite = (c: Context) => {
const site = c.req.header("sec-fetch-site");
return site === "cross-site" || site === "same-site";
};
const fromAnotherSite = (c: Context) =>
requestFromAnotherSite({
fetchSite: c.req.header("sec-fetch-site"),
host: c.req.header("host") ?? urlHost(c.req.url),
referer: c.req.header("referer"),
});
const isThumbnailCapture = (c: Context) => c.req.query(PREVIEW_CAPTURE_PARAM) !== undefined;
@@ -63,8 +66,11 @@ async function markPreviewForAnotherSite(c: Context) {
}
const FRAMED_DESTS = new Set(["document", "iframe", "frame", "embed", "object", "fencedframe"]);
const framedByAnotherSite = (c: Context) =>
fromAnotherSite(c) && FRAMED_DESTS.has(c.req.header("sec-fetch-dest") ?? "");
const framedByAnotherSite = (c: Context) => {
if (!fromAnotherSite(c)) return false;
const dest = c.req.header("sec-fetch-dest");
return dest === undefined || FRAMED_DESTS.has(dest);
};
function withoutValidators(request: Request): Request {
const headers = new Headers(request.headers);
@@ -104,6 +104,27 @@ export function wildcardBindHostAllowed(
);
}
function refererNamesHost(referer: string | undefined, host: string): boolean {
if (!referer) return false;
try {
return new URL(referer).host.toLowerCase() === host.toLowerCase();
} catch {
return false;
}
}
export function requestFromAnotherSite(headers: {
fetchSite?: string;
host?: string;
referer?: string;
}): boolean {
const site = headers.fetchSite;
if (site !== undefined) return site === "cross-site" || site === "same-site";
const { host } = headers;
if (!host || isLoopbackHost(host)) return false;
return !refererNamesHost(headers.referer, host);
}
function firstForwarded(value: string | undefined): string | undefined {
const first = value?.split(",")[0]?.trim();
return first === "" ? undefined : first;
@@ -168,3 +168,50 @@ describe("a thumbnail capture document", () => {
expect(plain).not.toContain('crossorigin="anonymous"');
});
});
describe("a plain-HTTP request to a LAN name, which carries no fetch metadata", () => {
const MARK = '<meta name="hyperframes-preview-for-another-site">';
const LAN = "http://192.168.1.20:3002";
const documents = routes.filter(([, , type]) => type === "text/html");
const lanGet = (path: string, headers: Record<string, string> = {}) =>
api.request(`${LAN}${path}`, { headers });
it.each(documents)(
"%s is marked and sandboxed for a frame that sends no Referer",
async (_n, path) => {
const res = await lanGet(path);
expect(await res.text()).toContain(MARK);
expect(res.headers.get("content-security-policy")).toBe(SANDBOX);
},
);
it.each(documents)("%s is marked and sandboxed for another site's Referer", async (_n, path) => {
const res = await lanGet(path, { referer: "http://elsewhere.example/page" });
expect(await res.text()).toContain(MARK);
expect(res.headers.get("content-security-policy")).toBe(SANDBOX);
});
it.each(documents)("%s stays unmarked for the Studio's own player", async (_n, path) => {
const res = await lanGet(path, { referer: `${LAN}/?project=demo` });
expect(await res.text()).not.toContain(MARK);
expect(res.headers.get("content-security-policy")).toBeNull();
});
it("never answers the unmarked copy's validators with a 304", async () => {
const own = await lanGet("/projects/demo/preview", { referer: `${LAN}/` });
const etag = own.headers.get("etag");
expect(etag).toBeTruthy();
const res = await lanGet("/projects/demo/preview", { "if-none-match": etag! });
expect(res.status).toBe(200);
expect(await res.text()).toContain(MARK);
});
it.each(["frame-token", "thumbnail/index.html", "waveform/clip.mp4", "peaks/clip.mp4"])(
"refuses %s with no Referer and answers the Studio's own page",
async (route) => {
expect((await lanGet(`/projects/demo/${route}`)).status).toBe(403);
const own = await lanGet(`/projects/demo/${route}`, { referer: `${LAN}/` });
expect(own.status).not.toBe(403);
},
);
});