Skip to content
Draft
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
23 changes: 23 additions & 0 deletions packages/cli/src/server/inertRefusal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// SECOPS-2642: sandbox gives an opaque origin no same-origin opener can read (COOP alone does not).
const INERT_REFUSAL_HEADERS = {
"Content-Type": "text/plain; charset=utf-8",
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "sandbox; default-src 'none'; frame-ancestors 'none'",
"X-Frame-Options": "DENY",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
"Referrer-Policy": "no-referrer",
"Cache-Control": "no-store",
} as const;

/** A fixed message, so nothing from the request URL reaches the body. */
export function inertRefusal(status: 400 | 404, message: string): Response {
return new Response(`${message}\n`, { status, headers: INERT_REFUSAL_HEADERS });
}

const OAUTH_RETURN_PARAMS = ["code", "state"] as const;

export function carriesOAuthReturn(url: string): boolean {
const params = new URL(url).searchParams;
return OAUTH_RETURN_PARAMS.some((name) => params.has(name));
}
4 changes: 2 additions & 2 deletions packages/cli/src/server/studioServer.file-race.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,9 @@ describe("Studio bundle file reads", () => {
expect(await response.text()).toContain("HyperFrames Studio unavailable");
});

it("still injects runtime environment into the SPA fallback", async () => {
it("still injects runtime environment into the Studio shell", async () => {
vi.stubEnv("VITE_STUDIO_STATIC_TEST", "runtime-value");
const response = await server.app.request("/editor");
const response = await server.app.request("/index.html");
expect(response.status).toBe(200);
const text = await response.text();
expect(text).toContain("Studio");
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/server/studioServer.staticAssets.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ describe("studio bundle cache policy", () => {
});

describe("studio shell framing", () => {
it("lets only its own origin frame the shell, on any SPA route", async () => {
for (const route of ["/", "/projects/demo"]) {
it("lets only its own origin frame the shell, on each entry route", async () => {
for (const route of ["/", "/index.html"]) {
const response = await server.app.request(route);

expect(response.status).toBe(200);
Expand Down
16 changes: 13 additions & 3 deletions packages/cli/src/server/studioServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
import { seekCompositionTimeline } from "../capture/captureCompositionFrame.js";
import { SAME_ORIGIN_FRAMING_HEADERS } from "@hyperframes/engine";
import { createThumbnailPages } from "./thumbnailPages.js";
import { carriesOAuthReturn, inertRefusal } from "./inertRefusal.js";
import {
assertWebGpuAdapterAvailable,
compositionRequiresWebGpu,
Expand Down Expand Up @@ -994,6 +995,12 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
// Extra hosts from HYPERFRAMES_PREVIEW_ALLOWED_HOSTS (Codespaces, tunnels).
const allowedHosts = previewAllowedHostsFromEnv();

// No Studio route takes an OAuth return, and project script runs on this origin (SECOPS-2642).
app.use(async function refuseOAuthReturn(c, next) {
if (!carriesOAuthReturn(c.req.url)) return next();
return inertRefusal(400, "This HyperFrames preview server does not accept sign-in returns.");
});

// Every route answers only loopback, the bind or an allowed host; a browser cannot forge Host.
app.use(async function refuseUnknownHost(c, next) {
const host = c.req.header("host") ?? new URL(c.req.url).host;
Expand Down Expand Up @@ -1254,8 +1261,8 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
return `<script>window.__HF_STUDIO_ENV__=${JSON.stringify(overrides)};</script>`;
}

// SPA fallback. The shell's own requests pass every same-origin check, so only its own pages may frame it.
app.get("*", (c) => {
// Studio routes by hash, so only its entry paths get the shell, and only its own pages may frame it.
const serveStudioShell = (c: Context) => {
for (const [name, value] of Object.entries(SAME_ORIGIN_FRAMING_HEADERS)) c.header(name, value);
const indexPath = resolve(studioDir, "index.html");
const indexContent = readBundleFile(indexPath);
Expand Down Expand Up @@ -1338,7 +1345,10 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
// `no-cache` not `no-store`: same refetch without an ETag, but `no-store`
// would blocklist the document from Chrome's bfcache.
return c.html(html, 200, { "Cache-Control": "no-cache" });
});
};
app.get("/", serveStudioShell);
app.get("/index.html", serveStudioShell);
app.all("*", () => inertRefusal(404, "Not found."));

const shutdown = async (): Promise<void> => {
shuttingDown = true;
Expand Down
132 changes: 132 additions & 0 deletions packages/cli/src/server/studioServer.unknownPaths.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as path from "node:path";
import { createStudioServer, type StudioServer } from "./studioServer.js";
import {
cleanupStudioServerRoot,
makeStudioServerRoot,
writeStudioIndexHtml,
} from "./studioServerTestFixture.js";

/**
* SECOPS-2642 (1). Studio routes by `location.hash` only, so it has no page
* that legitimately receives a path or an OAuth return. When the catch-all
* answered every unknown GET with the shell, an authorization redirect to the
* preview port (`/oauth/callback?code=…&state=…`) committed a same-origin page
* that re-mounted the project, and project script read the code from the
* address. The preview server must answer those with an inert refusal.
*/

const hooks = vi.hoisted(() => ({ studioDir: "" }));

// fallow-ignore-next-line code-duplication
vi.mock("node:path", async (importOriginal) => {
const actual = await importOriginal<typeof path>();
return {
...actual,
resolve: (...parts: string[]) =>
hooks.studioDir && parts.length === 2 && parts[0]?.endsWith("server") && parts[1] === "studio"
? hooks.studioDir
: actual.resolve(...parts),
};
});

const CODE = "victim-auth-code-1234";
const STATE = "attacker-state-5678";

let root: string;
let server: StudioServer;

beforeEach(() => {
const fixture = makeStudioServerRoot("hf-studio-unknown-paths-");
root = fixture.root;
hooks.studioDir = fixture.studioDir;
writeStudioIndexHtml(hooks.studioDir);
server = createStudioServer({ projectDir: fixture.projectDir });
});

afterEach(() => {
cleanupStudioServerRoot(server, root, () => (hooks.studioDir = ""));
});

function navigate(target: string, host = "127.0.0.1:3002"): Promise<Response> {
return Promise.resolve(
server.app.request(target, { headers: { host, "sec-fetch-mode": "navigate" } }),
);
}

async function expectInertRefusal(response: Response): Promise<void> {
expect(response.status).toBeGreaterThanOrEqual(400);
expect(response.headers.get("Content-Type")).toMatch(/^text\/plain/);
expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff");
expect(response.headers.get("Cross-Origin-Opener-Policy")).toBe("same-origin");
expect(response.headers.get("X-Frame-Options")).toBe("DENY");
const csp = response.headers.get("Content-Security-Policy") ?? "";
expect(csp).toContain("frame-ancestors 'none'");
// A CSP sandbox gives the document an opaque origin, so even a same-origin
// parent or opener that keeps a handle cannot read its address.
expect(csp).toMatch(/(^|;\s*)sandbox(;|$)/);
expect(response.headers.get("Referrer-Policy")).toBe("no-referrer");
expect(response.headers.get("Cache-Control")).toBe("no-store");
const body = await response.text();
expect(body).not.toContain("Studio");
expect(body).not.toContain("<");
expect(body).not.toContain(CODE);
expect(body).not.toContain(STATE);
}

describe("preview server unknown paths", () => {
it.each(["/oauth/callback", "/callback"])(
"refuses an OAuth return at %s instead of serving the Studio shell",
async (route) => {
const response = await navigate(`${route}?code=${CODE}&state=${STATE}`);
await expectInertRefusal(response);
},
);

it.each(["/editor", "/projects/demo", "/index.htm", "/some/deep/path?x=1"])(
"refuses unknown path %s",
async (route) => {
await expectInertRefusal(await navigate(route));
},
);

it("refuses an OAuth return on the localhost host too", async () => {
await expectInertRefusal(
await navigate(`/oauth/callback?code=${CODE}&state=${STATE}`, "localhost:3002"),
);
});

it.each([
`/?code=${CODE}&state=${STATE}`,
`/?code=${CODE}`,
`/?state=${STATE}`,
`/index.html?code=${CODE}&state=${STATE}`,
])("refuses an OAuth-shaped query on the entry route: %s", async (target) => {
await expectInertRefusal(await navigate(target));
});

it("refuses an OAuth-shaped query on a route that loads project script", async () => {
const response = await navigate(`/api/projects/project/preview?code=${CODE}&state=${STATE}`);
await expectInertRefusal(response);
});

it("refuses an OAuth-shaped query sent with a non-GET method", async () => {
const response = await server.app.request(`/oauth/callback?code=${CODE}&state=${STATE}`, {
method: "POST",
headers: { host: "127.0.0.1:3002" },
});
await expectInertRefusal(response);
});
});

describe("preview server entry routes", () => {
it.each(["/", "/index.html", "/?hf_canary_some_feature=on"])(
"still serves the Studio shell at %s",
async (route) => {
const response = await navigate(route);
expect(response.status).toBe(200);
expect(response.headers.get("Content-Type")).toMatch(/^text\/html/);
expect(await response.text()).toContain("Studio");
},
);
});
Loading