fix(studio-server): a loopback page with no fetch metadata is marked unless the app framed it (#8017)

* test(studio-server): a loopback page with no fetch metadata is marked unless it is the app's own

* fix(studio-server): a loopback page with no fetch metadata is marked unless the app framed it

* test(studio-server): a page marked by its Referer names Referer in Vary

* fix(studio-server): a page marked by its Referer tells caches it varies by Referer
This commit is contained in:
Miguel Ángel
2026-11-17 05:05:41 +00:00
committed by GitHub
parent 19743ea094
commit b6e1e8dda9
10 changed files with 116 additions and 31 deletions
+25 -3
View File
@@ -179,17 +179,21 @@ describe("registerCompositionRoute", () => {
const etags: Record<string, string> = {};
for (const path of ["/composition/index.html", "/composition/clip.mp4"]) {
const first = await app.request(path);
const own = { "Sec-Fetch-Site": "same-origin" };
const first = await app.request(path, { headers: own });
etags[path] = first.headers.get("ETag") ?? "";
expect(etags[path]).not.toBe("");
expect(first.headers.get("Cache-Control")).toBe("no-cache");
const again = await app.request(path, { headers: { "If-None-Match": etags[path] } });
const again = await app.request(path, { headers: { ...own, "If-None-Match": etags[path] } });
expect(again.status).toBe(304);
}
writeFileSync(join(project.dir, "clip.mp4"), Buffer.from("0123456789abc", "utf-8"));
const edited = await app.request("/composition/clip.mp4", {
headers: { "If-None-Match": etags["/composition/clip.mp4"] ?? "" },
headers: {
"Sec-Fetch-Site": "same-origin",
"If-None-Match": etags["/composition/clip.mp4"] ?? "",
},
});
expect(edited.status).toBe(200);
});
@@ -488,4 +492,22 @@ describe("a composition document another site loads", () => {
});
expect(await own.text()).not.toContain(MARK);
});
// fails without the fix: a loopback load with no fetch metadata counted as the play page's own.
it("is marked on loopback with no fetch metadata unless the play page sent it", async () => {
const app = await setup();
const local = "http://localhost:3003";
const bare = await app.request(`${local}/composition/index.html`);
expect(await bare.text()).toContain(MARK);
expect(bare.headers.get("Content-Security-Policy")).toBe(SANDBOX);
const foreign = await app.request(`${local}/composition/index.html`, {
headers: { Referer: "http://elsewhere.example/page" },
});
expect(await foreign.text()).toContain(MARK);
const own = await app.request(`${local}/composition/index.html`, {
headers: { Referer: `${local}/` },
});
expect(await own.text()).not.toContain(MARK);
for (const res of [bare, own]) expect(res.headers.get("Vary")).toBe("Sec-Fetch-Site, Referer");
});
});
@@ -37,7 +37,7 @@ it.runIf(process.platform === "linux")(
expect(compositionsAffectedBy(projectDir, "index.html")).toEqual(["index.html"]);
const app = server.app;
const endpoint = "/api/projects/film/preview/comp/scenes/intro.html";
const before = await app.request(endpoint);
const before = await app.request(endpoint, { headers: { "Sec-Fetch-Site": "same-origin" } });
expect(before.status).toBe(200);
expect(await before.text()).toContain("Original");
const beforeTag = before.headers.get("etag");
@@ -75,14 +75,16 @@ it.runIf(process.platform === "linux")(
affectedCompositions: null,
});
});
const after = await app.request(endpoint, { headers: { "If-None-Match": beforeTag! } });
const after = await app.request(endpoint, {
headers: { "Sec-Fetch-Site": "same-origin", "If-None-Match": beforeTag! },
});
expect(after.status).toBe(200);
expect(after.headers.get("etag")).not.toBe(beforeTag);
expect(await after.text()).toContain("Replacement");
writeFileSync(join(projectDir, "scenes/intro.html"), scene("Later edit"));
await vi.waitFor(async () => {
const later = await app.request(endpoint);
const later = await app.request(endpoint, { headers: { "Sec-Fetch-Site": "same-origin" } });
expect(later.status).toBe(200);
expect(await later.text()).toContain("Later edit");
});
@@ -110,7 +112,9 @@ it.runIf(process.platform === "linux").each([
writeFileSync(join(projectDir, ".hyperframes/studio-motion.json"), "{}");
server = createStudioServer({ projectDir, projectName: "film" });
const endpoint = "/api/projects/film/preview/comp/index.html";
const before = await server.app.request(endpoint);
const before = await server.app.request(endpoint, {
headers: { "Sec-Fetch-Site": "same-origin" },
});
expect(before.status).toBe(200);
const beforeTag = before.headers.get("etag");
expect(beforeTag).toBeTruthy();
@@ -123,7 +127,7 @@ it.runIf(process.platform === "linux").each([
await vi.waitFor(async () => {
const after = await server!.app.request(endpoint, {
headers: { "If-None-Match": beforeTag! },
headers: { "Sec-Fetch-Site": "same-origin", "If-None-Match": beforeTag! },
});
expect(after.status).toBe(200);
expect(after.headers.get("etag")).not.toBe(beforeTag);
+3 -1
View File
@@ -805,7 +805,9 @@ describe("Studio thumbnail capture", () => {
"http://localhost/api/projects/demo/preview?hf-capture=1",
);
expect(capture.headers.get("content-security-policy")).toBe("sandbox allow-scripts");
const preview = await server.app.request("http://localhost/api/projects/demo/preview");
const preview = await server.app.request("http://localhost/api/projects/demo/preview", {
headers: { "Sec-Fetch-Site": "same-origin" },
});
expect(preview.headers.get("content-security-policy")).toBeNull();
});
+3 -3
View File
@@ -13,7 +13,7 @@ import { PREVIEW_FOR_ANOTHER_SITE_META } from "@hyperframes/core/studio-preview-
import {
PREVIEW_ALLOWED_HOSTS_ENV,
previewAllowedHostsFromEnv,
requestFromAnotherSite,
documentFromAnotherSite,
wildcardBindHostAllowed,
} from "@hyperframes/studio-server/request-identity";
import { SAME_ORIGIN_FRAMING_HEADERS } from "@hyperframes/engine";
@@ -230,14 +230,14 @@ async function markDocumentForAnotherSite(c: Context): Promise<void> {
/** 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({
const anotherSite = documentFromAnotherSite({
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 });
c.header("Vary", "Sec-Fetch-Site, Referer", { append: true });
if (!anotherSite) return;
c.header("Content-Security-Policy", "sandbox allow-scripts");
await markDocumentForAnotherSite(c);
@@ -13,7 +13,8 @@ interface Answer {
function getWithHost(port: number, path: string, host: string): Promise<Answer> {
return new Promise((resolveAnswer, rejectAnswer) => {
const req = request({ hostname: "127.0.0.1", port, path, headers: { host } }, (res) => {
const headers = { host, "sec-fetch-site": "same-origin" };
const req = request({ hostname: "127.0.0.1", port, path, headers }, (res) => {
let body = "";
res.setEncoding("utf8");
res.on("data", (chunk: string) => (body += chunk));
@@ -789,6 +789,17 @@ describe("serveStaticProjectHtml page another site loads", () => {
}
},
);
// fails without the fix: a loopback load with no fetch metadata counted as the capture's own.
it("marks a page loaded with no fetch metadata unless its Referer is this server", async () => {
const url = await serveProject();
const bare = await fetch(`${url}scene.html`);
expect(await bare.text()).toContain(MARK);
expect(bare.headers.get("content-security-policy")).toContain(SANDBOX);
const own = await fetch(`${url}scene.html`, { headers: { Referer: url } });
expect(await own.text()).not.toContain(MARK);
for (const res of [bare, own]) expect(res.headers.get("vary")).toBe("Sec-Fetch-Site, Referer");
});
});
function writeToolRecords(projectDir: string): void {
@@ -19,7 +19,7 @@ import {
} from "@hyperframes/core";
import { getMimeType } from "@hyperframes/core/studio-api";
import { decodeWellFormedEscapes, openRangeEnd } from "@hyperframes/studio-server";
import { requestFromAnotherSite } from "@hyperframes/studio-server/request-identity";
import { documentFromAnotherSite } from "@hyperframes/studio-server/request-identity";
import { findStageProxyBox } from "./compositionViewport.js";
import { resolveAutoProxy } from "./projectConfig.js";
import { injectMediaCodecMap } from "./compositionServer.js";
@@ -296,11 +296,12 @@ function markForAnotherSite(html: string): string {
/** A load by another site is sandboxed, and the documents it gets are marked so their runtime offers it no editing port. */
function loadedByAnotherSite(req: IncomingMessage, res: ServerResponse): boolean {
const anotherSite = requestFromAnotherSite({
const anotherSite = documentFromAnotherSite({
fetchSite: req.headers["sec-fetch-site"] as string | undefined,
host: req.headers.host,
referer: req.headers.referer,
});
res.setHeader("Vary", "Sec-Fetch-Site, Referer");
if (anotherSite) {
const policies = [res.getHeader("Content-Security-Policy"), "sandbox allow-scripts"];
res.setHeader("Content-Security-Policy", policies.filter((p) => p !== undefined).map(String));
+11 -9
View File
@@ -28,6 +28,7 @@ import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
import {
PREVIEW_ALLOWED_HOSTS_ENV,
documentFromAnotherSite,
requestFromAnotherSite,
requestHost,
sameOriginPost,
@@ -52,12 +53,13 @@ async function answerRefusedFrameWithPage(c: Context, next: Next) {
});
}
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 siteHeaders = (c: Context) => ({
fetchSite: c.req.header("sec-fetch-site"),
host: c.req.header("host") ?? urlHost(c.req.url),
referer: c.req.header("referer"),
});
const fromAnotherSite = (c: Context) => requestFromAnotherSite(siteHeaders(c));
const documentForAnotherSite = (c: Context) => documentFromAnotherSite(siteHeaders(c));
const isThumbnailCapture = (c: Context) => c.req.query(PREVIEW_CAPTURE_PARAM) !== undefined;
@@ -76,7 +78,7 @@ async function markPreviewForAnotherSite(c: Context) {
const FRAMED_DESTS = new Set(["document", "iframe", "frame", "embed", "object", "fencedframe"]);
const framedByAnotherSite = (c: Context) => {
if (!fromAnotherSite(c)) return false;
if (!documentForAnotherSite(c)) return false;
const dest = c.req.header("sec-fetch-dest");
return dest === undefined || FRAMED_DESTS.has(dest);
};
@@ -92,8 +94,8 @@ const sandboxPreviewForAnotherSiteOrCapture =
(sandboxCaptures: boolean) => async (c: Context, next: Next) => {
if (framedByAnotherSite(c)) c.req.raw = withoutValidators(c.req.raw);
await next();
c.header("Vary", "Sec-Fetch-Site", { append: true });
const anotherSite = fromAnotherSite(c);
c.header("Vary", "Sec-Fetch-Site, Referer", { append: true });
const anotherSite = documentForAnotherSite(c);
if (anotherSite || (sandboxCaptures && isThumbnailCapture(c)))
c.header("Content-Security-Policy", "sandbox allow-scripts");
if (anotherSite) await markPreviewForAnotherSite(c);
@@ -125,6 +125,15 @@ export function requestFromAnotherSite(headers: {
return !refererNamesHost(headers.referer, host);
}
export function documentFromAnotherSite(headers: {
fetchSite?: string;
host?: string;
referer?: string;
}): boolean {
if (headers.fetchSite !== undefined || !headers.host) return requestFromAnotherSite(headers);
return !refererNamesHost(headers.referer, headers.host);
}
function firstForwarded(value: string | undefined): string | undefined {
const first = value?.split(",")[0]?.trim();
return first === "" ? undefined : first;
@@ -53,16 +53,16 @@ describe.each(routes)("%s", (_name, path, type) => {
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain(type);
expect(res.headers.get("content-security-policy")).toBe(SANDBOX);
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site");
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site, Referer");
});
it.each([["same-origin"], ["none"], [undefined]])(
it.each([["same-origin"], ["none"]])(
"keeps its origin when Sec-Fetch-Site is %s",
async (site) => {
const res = await get(path, site);
expect(res.status).toBe(200);
expect(res.headers.get("content-security-policy")).toBeNull();
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site");
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site, Referer");
},
);
});
@@ -99,7 +99,7 @@ describe("a revalidated preview", () => {
headers: { "sec-fetch-site": "same-origin", "if-none-match": etag! },
});
expect(res.status).toBe(304);
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site");
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site, Referer");
});
it.each(["cross-site", "same-site"])(
@@ -118,7 +118,7 @@ describe("a revalidated preview", () => {
});
expect(res.status).toBe(200);
expect(await res.text()).toContain('<meta name="hyperframes-preview-for-another-site">');
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site");
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site, Referer");
expect(res.headers.get("content-security-policy")).toBe(SANDBOX);
},
);
@@ -152,9 +152,10 @@ describe("a thumbnail capture document", () => {
it("carries the sandbox on a 304", async () => {
const path = "/projects/demo/preview?hf-capture=1";
const etag = (await request(sandboxing, path)).headers.get("etag");
const navigation = { "sec-fetch-site": "none" };
const etag = (await request(sandboxing, path, navigation)).headers.get("etag");
expect(etag).toBeTruthy();
const res = await request(sandboxing, path, { "if-none-match": etag! });
const res = await request(sandboxing, path, { ...navigation, "if-none-match": etag! });
expect(res.status).toBe(304);
expect(res.headers.get("content-security-policy")).toBe(SANDBOX);
});
@@ -215,3 +216,35 @@ describe("a plain-HTTP request to a LAN name, which carries no fetch metadata",
},
);
});
// fails without the fix: with no fetch metadata a loopback load counted as Studio's own, so another site's frame got
// an unmarked page whose runtime offered it the editing port.
describe("a loopback request from a browser that sends no fetch metadata", () => {
const MARK = '<meta name="hyperframes-preview-for-another-site">';
const LOCAL = "http://localhost:3002";
const documents = routes.filter(([, , type]) => type === "text/html");
const localGet = (path: string, headers: Record<string, string> = {}) =>
api.request(`${LOCAL}${path}`, { headers });
it.each(documents)("%s is marked and sandboxed with no Referer", async (_n, path) => {
const res = await localGet(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 localGet(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 localGet(path, { referer: `${LOCAL}/?project=demo` });
expect(await res.text()).not.toContain(MARK);
expect(res.headers.get("content-security-policy")).toBeNull();
});
it("still answers a local tool's request to a route that refuses other sites", async () => {
expect((await localGet("/projects/demo/frame-token")).status).not.toBe(403);
});
});