Skip to content
Merged
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
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
17 changes: 14 additions & 3 deletions packages/cli/src/server/studioServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ import {
HistoryBusyError,
HistoryClosedError,
historyCache,
carriesOAuthReturn,
inertRefusal,
refuseOAuthReturn,
} from "@hyperframes/studio-server";
import { encoderJobOptions } from "@hyperframes/studio-server/encoder-options";
import { isLinkFreeWithinProject } from "@hyperframes/studio-server/safe-path";
Expand Down Expand Up @@ -994,6 +997,11 @@ 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.
app.use(async function refuseOAuthReturnAtAnyPath(c, next) {
return carriesOAuthReturn(c.req.url) ? refuseOAuthReturn() : next();
});

// 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 +1262,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 +1346,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";

/**
* 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");
},
);
});
26 changes: 26 additions & 0 deletions packages/studio-server/src/helpers/inertRefusal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// The sandbox CSP 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;

export function inertRefusal(status: 400 | 404, fixedMessage: string): Response {
return new Response(`${fixedMessage}\n`, { status, headers: INERT_REFUSAL_HEADERS });
}

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

export function carriesOAuthReturn(urlOrRequestTarget: string): boolean {
const params = new URL(urlOrRequestTarget, "http://loopback").searchParams;
return OAUTH_RETURN_PARAMS.some((name) => params.has(name));
}

export function refuseOAuthReturn(): Response {
return inertRefusal(400, "This HyperFrames preview server does not accept sign-in returns.");
}
1 change: 1 addition & 0 deletions packages/studio-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export {
PREVIEW_ALLOWED_HOSTS_ENV,
previewAllowedHostsFromEnv,
} from "./helpers/requestIdentity.js";
export { carriesOAuthReturn, inertRefusal, refuseOAuthReturn } from "./helpers/inertRefusal.js";
export { MAX_UPLOAD_BYTES } from "./routes/files.js";
export {
createProjectSignature,
Expand Down
31 changes: 29 additions & 2 deletions packages/studio/vite.config.hosts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void)

interface Reply {
status: number | undefined;
headers: Record<string, string>;
body: string;
}

Expand Down Expand Up @@ -64,11 +65,12 @@ function startPlugin(): Middleware[] {
// Runs the request down the plugin's middlewares the way connect would; `undefined` status means every one passed it on.
function request(middlewares: Middleware[], url: string, host: string): Promise<Reply> {
return new Promise((resolve) => {
const reply: Reply = { status: undefined, body: "" };
const reply: Reply = { status: undefined, headers: {}, body: "" };
const res = Object.assign(new EventEmitter(), {
headersSent: false,
writeHead(status: number) {
writeHead(status: number, headers?: Record<string, string>) {
reply.status = status;
reply.headers = headers ?? {};
res.headersSent = true;
return res;
},
Expand Down Expand Up @@ -146,3 +148,28 @@ describe("studio dev server host check", () => {
expect(fresh.server?.allowedHosts).toEqual(["studio.tunnel.example"]);
});
});

// Dev and local-studio `preview` run this Vite server, whose SPA fallback serves the shell anywhere.
describe("studio dev server OAuth returns", () => {
it.each([
"/oauth/callback?code=SECRET&state=s",
"/callback?code=SECRET",
"/?code=SECRET",
"/index.html?state=s",
"/api/projects/project/preview?code=SECRET",
])("refuses %s inertly before any route or the SPA fallback", async (url) => {
const reply = await request(startPlugin(), url, "127.0.0.1:5190");
expect(reply.status).toBe(400);
expect(reply.headers["content-type"]).toMatch(/^text\/plain/);
expect(reply.headers["cross-origin-opener-policy"]).toBe("same-origin");
expect(reply.headers["content-security-policy"]).toMatch(/(^|;\s*)sandbox(;|$)/);
expect(reply.headers["content-security-policy"]).toContain("frame-ancestors 'none'");
expect(reply.headers["x-content-type-options"]).toBe("nosniff");
expect(reply.body).not.toContain("SECRET");
});

it("leaves the entry route without a return to Vite", async () => {
const reply = await request(startPlugin(), "/?hf_canary_x=on", "127.0.0.1:5190");
expect(reply.status).toBeUndefined();
});
});
6 changes: 6 additions & 0 deletions packages/studio/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { previewConfigPayload } from "./vite.preview-config";
import { loadStudioServerDevModule } from "./vite.studio-server-module";
import type { openProjectHistory } from "@hyperframes/studio-server";
import { previewChangeOwner } from "./vite.preview-watch";
import { carriesOAuthReturn, refuseOAuthReturn } from "../studio-server/src/helpers/inertRefusal";
import {
hostHeaderAllowed,
PREVIEW_ALLOWED_HOSTS_ENV,
Expand Down Expand Up @@ -220,6 +221,11 @@ function devProjectApi(): Plugin {
const allowedHosts = [...previewAllowedHostsFromEnv()];
if (typeof server.config.server.host === "string")
allowedHosts.push(server.config.server.host);
// Refuse an OAuth return first, before every route and Vite's own SPA fallback.
server.middlewares.use((req, res, next) => {
if (!carriesOAuthReturn(req.url ?? "/")) return next();
void bridgeHonoResponse(refuseOAuthReturn(), res);
});
server.middlewares.use((req, res, next) => {
const url = req.url ?? "";
if (url !== "/__hyperframes_config" && !url.startsWith("/api/")) return next();
Expand Down
Loading