Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions packages/cli/src/commands/play.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 changes: 2 additions & 0 deletions packages/cli/src/commands/play.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
resolvePlayerPath,
listenOnFreePort,
refuseUnknownHosts,
sandboxForAnotherSite,
injectRuntime,
injectMediaCodecMap,
buildRangeResponse,
Expand Down Expand Up @@ -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");
Expand Down
41 changes: 40 additions & 1 deletion packages/cli/src/utils/compositionServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion packages/player/src/hyperframes-player.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/player/src/iframe-dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, "");

Expand Down
18 changes: 12 additions & 6 deletions packages/studio-server/src/createStudioApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;

Expand All @@ -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);
Expand Down
21 changes: 21 additions & 0 deletions packages/studio-server/src/helpers/requestIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
47 changes: 47 additions & 0 deletions packages/studio-server/src/routes/preview.sandbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
},
);
});
Loading