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