From 7ea6e42f0773d424ea6ea0dafceb714880f82e2c Mon Sep 17 00:00:00 2001 From: James Russo Date: Tue, 24 Nov 2026 11:05:26 +0000 Subject: [PATCH] fix(studio): a project page opened straight from a link runs apart from Studio (#8697) * fix(studio): a project page opened straight from a link runs apart from Studio A preview document or project file reached by direct navigation (address bar, chat or mail link) is answered the way one framed by another site already is: in a sandbox, marked, and with its type fixed. Studio's own frames and thumbnail captures are answered as before. The CLI's Studio server and the Studio dev server ask for this; a host that opens previews in its own windows does not have to. Co-Authored-By: Claude Fable 5.2 * docs(cli): say how a preview address opened outside Studio behaves Co-Authored-By: Claude Fable 5.2 * refactor(studio-server): split who asks for a preview from how it is answered Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 --- docs/packages/cli.mdx | 4 ++ .../server/studioServer.staticAssets.test.ts | 16 ++++++++ packages/cli/src/server/studioServer.ts | 6 ++- packages/studio-server/src/createStudioApi.ts | 39 +++++++++++++------ .../src/routes/preview.sandbox.test.ts | 34 ++++++++++++++++ packages/studio/vite.config.ts | 1 + 6 files changed, 88 insertions(+), 12 deletions(-) diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index dbf1c3b388..e11f16fca4 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -1174,6 +1174,10 @@ Narrow the context with `--context-fields` (`server`, `selection`, `lint`, Your composition opens in HyperFrames Studio, and edits to `index.html` and its sub-compositions refresh live. Preview and render share the same runtime. +A preview address or project file opened by itself in a browser tab, outside +Studio, plays in a sandboxed page: it cannot call the Studio API and is not +editable from that tab. Open the Studio project URL to edit. + The server picks one of three modes by itself: **embedded** (the default for `npx` — Studio bundled in the CLI, no extra dependencies), **local studio** (Vite with full HMR, from a `@hyperframes/studio` source checkout), or diff --git a/packages/cli/src/server/studioServer.staticAssets.test.ts b/packages/cli/src/server/studioServer.staticAssets.test.ts index 7551e403f6..6246da826a 100644 --- a/packages/cli/src/server/studioServer.staticAssets.test.ts +++ b/packages/cli/src/server/studioServer.staticAssets.test.ts @@ -120,3 +120,19 @@ describe("studio shell framing", () => { expect(response.headers.get("X-Frame-Options")).toBe("SAMEORIGIN"); }); }); + +describe("a project page opened by direct navigation", () => { + it("is answered sandboxed by this server", async () => { + const project = path.join(root, "project"); + fs.writeFileSync(path.join(project, "index.html"), '
'); + fs.writeFileSync(path.join(project, "page.html"), ""); + const id = encodeURIComponent(path.basename(project)); + for (const file of ["page.html", "comp/page.html"]) { + const response = await server.app.request(`/api/projects/${id}/preview/${file}`, { + headers: { "sec-fetch-site": "none", "sec-fetch-dest": "document" }, + }); + expect(response.status).toBe(200); + expect(response.headers.get("Content-Security-Policy")).toBe("sandbox allow-scripts"); + } + }); +}); diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index a8edc1c9c2..da9c6c9849 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -1209,7 +1209,11 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { // Mount the shared studio API at /api. // Use fetch() forwarding (not .route()) so the sub-app sees paths without // the /api prefix — the shared module's path extraction uses c.req.path. - const api = createStudioApi(adapter, { allowedHosts, sandboxThumbnailCaptures: true }); + const api = createStudioApi(adapter, { + allowedHosts, + sandboxThumbnailCaptures: true, + sandboxDirectOpens: true, + }); app.all("/api/*", async (c) => { const url = new URL(c.req.url); url.pathname = url.pathname.replace(/^\/[^/]*/, ""); // Strip the "/api" segment however it is spelled diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts index c8d9732c08..2ae9ea7e1a 100644 --- a/packages/studio-server/src/createStudioApi.ts +++ b/packages/studio-server/src/createStudioApi.ts @@ -82,11 +82,6 @@ async function markPreviewForAnotherSite(c: Context) { } const FRAMED_DESTS = new Set(["document", "iframe", "frame", "embed", "object", "fencedframe"]); -const framedByAnotherSite = (c: Context) => { - if (!documentForAnotherSite(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); @@ -95,15 +90,32 @@ function withoutValidators(request: Request): Request { return new Request(request, { headers }); } +interface PreviewSandboxing { + captures: boolean; + directOpens: boolean; +} + +function previewAsker(c: Context, { captures, directOpens }: PreviewSandboxing) { + const capture = captures && isThumbnailCapture(c); + const openedDirectly = directOpens && !capture && c.req.header("sec-fetch-site") === "none"; + return { capture, openedDirectly, anotherSite: documentForAnotherSite(c) || openedDirectly }; +} + +const loadsAsPage = (c: Context) => { + const dest = c.req.header("sec-fetch-dest"); + return dest === undefined || FRAMED_DESTS.has(dest); +}; + const sandboxPreviewForAnotherSiteOrCapture = - (sandboxCaptures: boolean) => async (c: Context, next: Next) => { - if (framedByAnotherSite(c)) c.req.raw = withoutValidators(c.req.raw); + (sandboxing: PreviewSandboxing) => async (c: Context, next: Next) => { + const asker = previewAsker(c, sandboxing); + if (asker.anotherSite && loadsAsPage(c)) c.req.raw = withoutValidators(c.req.raw); await next(); c.header("Vary", "Sec-Fetch-Site, Referer", { append: true }); - const anotherSite = documentForAnotherSite(c); - if (anotherSite || (sandboxCaptures && isThumbnailCapture(c))) + if (asker.anotherSite || asker.capture) c.header("Content-Security-Policy", "sandbox allow-scripts"); - if (anotherSite) await markPreviewForAnotherSite(c); + if (asker.openedDirectly) c.header("X-Content-Type-Options", "nosniff"); + if (asker.anotherSite) await markPreviewForAnotherSite(c); }; async function refuseProxyWorkForAnotherSite(c: Context, next: Next) { @@ -171,6 +183,7 @@ const reportRefusals = export interface StudioApiOptions extends CaptureSandboxOption { allowedHosts?: readonly string[]; subCompositionDeadlineMs?: number; + sandboxDirectOpens?: boolean; } export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOptions = {}): Hono { @@ -178,6 +191,7 @@ export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOpt if (adapter.onRefusal) api.use(reportRefusals(adapter.onRefusal)); api.use(refuseServiceWorkerScripts); const sandboxThumbnailCaptures = options.sandboxThumbnailCaptures ?? false; + const sandboxDirectOpens = options.sandboxDirectOpens ?? false; const frameTokens = createFrameTokens(); const resolveProjectId = (id: string) => Promise.resolve() @@ -190,7 +204,10 @@ export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOpt api.use("/projects/:id/preview/*", refuseProxyWorkForAnotherSite); api.use( "/projects/:id/preview/*", - sandboxPreviewForAnotherSiteOrCapture(sandboxThumbnailCaptures), + sandboxPreviewForAnotherSiteOrCapture({ + captures: sandboxThumbnailCaptures, + directOpens: sandboxDirectOpens, + }), ); api.get("/projects/:id/frame-token", async (c) => { if (fromAnotherSite(c)) diff --git a/packages/studio-server/src/routes/preview.sandbox.test.ts b/packages/studio-server/src/routes/preview.sandbox.test.ts index 1aad925486..593ec509ac 100644 --- a/packages/studio-server/src/routes/preview.sandbox.test.ts +++ b/packages/studio-server/src/routes/preview.sandbox.test.ts @@ -91,6 +91,40 @@ describe("a preview document answered to another site", () => { }); }); +describe.each(routes)("%s opened by direct navigation", (_name, path, type) => { + const guarded = createStudioApi(adapter, { sandboxDirectOpens: true }); + const open = (app: typeof api, headers: Record = {}) => + app.request(`http://localhost${path}`, { + headers: { "sec-fetch-site": "none", "sec-fetch-dest": "document", ...headers }, + }); + + it("is sandboxed, marked and never sniffed when the host asks for it", async () => { + const res = await open(guarded); + 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("x-content-type-options")).toBe("nosniff"); + expect((await res.text()).includes("hyperframes-preview-for-another-site")).toBe( + type === "text/html", + ); + }); + + it("is answered in full, not from the copy a Studio frame cached", async () => { + const etag = (await get(path, "same-origin")).headers.get("etag"); + const res = await open(guarded, etag ? { "if-none-match": etag } : {}); + expect(res.status).toBe(200); + expect(res.headers.get("content-security-policy")).toBe(SANDBOX); + }); + + it("keeps its origin in a Studio frame, and for a host that does not ask", async () => { + const framed = await guarded.request(`http://localhost${path}`, { + headers: { "sec-fetch-site": "same-origin", "sec-fetch-dest": "iframe" }, + }); + expect(framed.headers.get("content-security-policy")).toBeNull(); + expect((await open(api)).headers.get("content-security-policy")).toBeNull(); + }); +}); + describe("a revalidated preview", () => { it("still names Sec-Fetch-Site in Vary on a 304 to the Studio's own pages", async () => { const etag = (await get("/projects/demo/preview", "same-origin")).headers.get("etag"); diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.ts index b0d6ec6a46..d965dd7e29 100644 --- a/packages/studio/vite.config.ts +++ b/packages/studio/vite.config.ts @@ -212,6 +212,7 @@ export function devProjectApi(): Plugin { _api = mod.createStudioApi(adapter, { allowedHosts: mod.previewAllowedHostsFromEnv(), sandboxThumbnailCaptures: true, + sandboxDirectOpens: true, }); } return _api;