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 <noreply@anthropic.com>

* docs(cli): say how a preview address opened outside Studio behaves

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(studio-server): split who asks for a preview from how it is answered

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
James Russo
2026-11-24 11:05:26 +00:00
committed by GitHub
co-authored by Claude Fable 5.2
parent 51f189acf3
commit 7ea6e42f07
6 changed files with 88 additions and 12 deletions
+4
View File
@@ -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
@@ -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"), '<div data-composition-id="main"></div>');
fs.writeFileSync(path.join(project, "page.html"), "<script>document.title = 1</script>");
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");
}
});
});
+5 -1
View File
@@ -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
+28 -11
View File
@@ -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))
@@ -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<string, string> = {}) =>
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");
+1
View File
@@ -212,6 +212,7 @@ export function devProjectApi(): Plugin {
_api = mod.createStudioApi(adapter, {
allowedHosts: mod.previewAllowedHostsFromEnv(),
sandboxThumbnailCaptures: true,
sandboxDirectOpens: true,
});
}
return _api;