diff --git a/packages/cli/src/commands/play.test.ts b/packages/cli/src/commands/play.test.ts index 0829bbc85b..747b6551e1 100644 --- a/packages/cli/src/commands/play.test.ts +++ b/packages/cli/src/commands/play.test.ts @@ -433,3 +433,59 @@ describe("registerCompositionRoute", () => { expect(mocks.resolveProxy).not.toHaveBeenCalled(); }); }); + +describe("a composition document another site loads", () => { + const MARK = ''; + const SANDBOX = "sandbox allow-scripts"; + + async function setup() { + const project = tmpProject(); + writeFileSync(join(project.dir, "index.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); + }); +}); diff --git a/packages/cli/src/commands/play.ts b/packages/cli/src/commands/play.ts index ebaf1c09aa..3c481422a3 100644 --- a/packages/cli/src/commands/play.ts +++ b/packages/cli/src/commands/play.ts @@ -37,6 +37,7 @@ import { resolvePlayerPath, listenOnFreePort, refuseUnknownHosts, + sandboxForAnotherSite, injectRuntime, injectMediaCodecMap, buildRangeResponse, @@ -223,6 +224,7 @@ export async function registerCompositionRoute( ): Promise { 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"); diff --git a/packages/cli/src/utils/compositionServer.ts b/packages/cli/src/utils/compositionServer.ts index 1be0b61fcc..3609dd7c81 100644 --- a/packages/cli/src/utils/compositionServer.ts +++ b/packages/cli/src/utils/compositionServer.ts @@ -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 { + 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(), + ``, + ); + 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 diff --git a/packages/player/src/hyperframes-player.test.ts b/packages/player/src/hyperframes-player.test.ts index 56f84e3a48..77dfe3eed9 100644 --- a/packages/player/src/hyperframes-player.test.ts +++ b/packages/player/src/hyperframes-player.test.ts @@ -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", () => { diff --git a/packages/player/src/iframe-dom.ts b/packages/player/src/iframe-dom.ts index f9665eebc8..5709c53660 100644 --- a/packages/player/src/iframe-dom.ts +++ b/packages/player/src/iframe-dom.ts @@ -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, ""); diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts index 0335c6513d..c6ba77dc02 100644 --- a/packages/studio-server/src/createStudioApi.ts +++ b/packages/studio-server/src/createStudioApi.ts @@ -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); diff --git a/packages/studio-server/src/helpers/requestIdentity.ts b/packages/studio-server/src/helpers/requestIdentity.ts index 4853879383..d59693c00e 100644 --- a/packages/studio-server/src/helpers/requestIdentity.ts +++ b/packages/studio-server/src/helpers/requestIdentity.ts @@ -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; diff --git a/packages/studio-server/src/routes/preview.sandbox.test.ts b/packages/studio-server/src/routes/preview.sandbox.test.ts index cad9493387..d3be701412 100644 --- a/packages/studio-server/src/routes/preview.sandbox.test.ts +++ b/packages/studio-server/src/routes/preview.sandbox.test.ts @@ -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 = ''; + const LAN = "http://192.168.1.20:3002"; + const documents = routes.filter(([, , type]) => type === "text/html"); + const lanGet = (path: string, headers: Record = {}) => + 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); + }, + ); +});