Skip to content

Commit 42574a7

Browse files
Dextheking1Dextheking1
authored andcommitted
fix(studio-server): reject cross-origin state-changing requests
The studio API is unauthenticated and loopback binding is the only mitigation (F-001). CORS-safelisted POSTs (text/plain, form data) are sent without a preflight, so any website open in the user's browser could create and upload project files and trigger renders while hyperframes preview runs. Add a guard in createStudioApi: non-GET requests are refused with 403 when the Origin host does not match the request Host, when the Origin is unparseable (including the opaque literal null), or when Fetch Metadata marks the request cross-site. Requests with no Origin header (curl, tests, in-process callers) and all reads are unaffected.
1 parent c4c1e62 commit 42574a7

2 files changed

Lines changed: 155 additions & 0 deletions

File tree

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
// @vitest-environment node
2+
// Node environment on purpose: the package default (happy-dom) implements
3+
// the browser fetch spec, which drops forbidden request headers such as
4+
// Origin and Sec-Fetch-Site when a Request is constructed. A test that
5+
// simulates cross-origin browser traffic has to set exactly those headers,
6+
// so it needs Node's fetch classes, which keep them.
7+
import { afterEach, describe, expect, it } from "vitest";
8+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
9+
import { tmpdir } from "node:os";
10+
import { join } from "node:path";
11+
import { createStudioApi } from "./createStudioApi";
12+
import { stubAdapter } from "./routes/stubAdapter.test-helpers";
13+
14+
const tempDirs: string[] = [];
15+
16+
afterEach(() => {
17+
for (const dir of tempDirs.splice(0)) {
18+
rmSync(dir, { recursive: true, force: true });
19+
}
20+
});
21+
22+
function createApp(): { app: ReturnType<typeof createStudioApi>; projectDir: string } {
23+
const projectDir = mkdtempSync(join(tmpdir(), "hf-origin-guard-"));
24+
tempDirs.push(projectDir);
25+
return { app: createStudioApi(stubAdapter(projectDir)), projectDir };
26+
}
27+
28+
const EVIL_ORIGIN = "http://evil.example:9999";
29+
30+
function createFile(
31+
app: ReturnType<typeof createStudioApi>,
32+
headers: Record<string, string>,
33+
name = "planted.html",
34+
): Promise<Response> {
35+
// A real browser request always carries a Host header; app.request does
36+
// not derive one in this environment, so send it explicitly. That keeps
37+
// every case exercising the Origin comparison itself.
38+
return app.request(`http://localhost/projects/demo/files/${name}`, {
39+
method: "POST",
40+
headers: { Host: "localhost", ...headers },
41+
body: "<html>planted</html>",
42+
});
43+
}
44+
45+
describe("createStudioApi cross-origin write guard", () => {
46+
it("rejects a cross-origin POST file create and writes nothing", async () => {
47+
const { app, projectDir } = createApp();
48+
const res = await createFile(app, { Origin: EVIL_ORIGIN, "Content-Type": "text/plain" });
49+
expect(res.status).toBe(403);
50+
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
51+
});
52+
53+
it("rejects a cross-origin multipart upload", async () => {
54+
const { app, projectDir } = createApp();
55+
const form = new FormData();
56+
form.append("files", new File(["planted"], "planted.html", { type: "text/html" }));
57+
const res = await app.request("http://localhost/projects/demo/upload", {
58+
method: "POST",
59+
headers: { Host: "localhost", Origin: EVIL_ORIGIN },
60+
body: form,
61+
});
62+
expect(res.status).toBe(403);
63+
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
64+
});
65+
66+
it("rejects a write whose Origin is the opaque literal null", async () => {
67+
const { app } = createApp();
68+
const res = await createFile(app, { Origin: "null", "Content-Type": "text/plain" });
69+
expect(res.status).toBe(403);
70+
});
71+
72+
it("rejects a write marked cross-site by Fetch Metadata even without Origin", async () => {
73+
const { app } = createApp();
74+
const res = await createFile(app, { "Sec-Fetch-Site": "cross-site" });
75+
expect(res.status).toBe(403);
76+
});
77+
78+
it("rejects a cross-origin PUT overwrite", async () => {
79+
const { app } = createApp();
80+
const res = await app.request("http://localhost/projects/demo/files/planted.html", {
81+
method: "PUT",
82+
headers: { Host: "localhost", Origin: EVIL_ORIGIN, "If-None-Match": "*" },
83+
body: "overwritten",
84+
});
85+
expect(res.status).toBe(403);
86+
});
87+
88+
it("allows a same-origin write (Origin host matches Host)", async () => {
89+
const { app, projectDir } = createApp();
90+
const res = await createFile(app, {
91+
Origin: "http://localhost",
92+
"Content-Type": "text/plain",
93+
});
94+
expect(res.status).toBe(201);
95+
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
96+
});
97+
98+
it("allows a write with no Origin header (non-browser callers)", async () => {
99+
const { app, projectDir } = createApp();
100+
const res = await createFile(app, { "Content-Type": "text/plain" });
101+
expect(res.status).toBe(201);
102+
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
103+
});
104+
105+
it("does not block reads from any origin", async () => {
106+
const { app } = createApp();
107+
await createFile(app, { "Content-Type": "text/plain" });
108+
const res = await app.request("http://localhost/projects/demo/files/planted.html", {
109+
headers: { Origin: EVIL_ORIGIN },
110+
});
111+
expect(res.status).toBe(200);
112+
});
113+
});

‎packages/studio-server/src/createStudioApi.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,24 @@ import { registerHistoryRoutes } from "./routes/history.js";
2020
import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
2121
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
2222

23+
/**
24+
* Whether a state-changing request's Origin names the host the request was
25+
* sent to. No Origin header means a non-browser caller (curl, tests,
26+
* in-process), which is allowed. An unparseable Origin (including the
27+
* literal "null" a sandboxed page sends) names no host this server serves,
28+
* so it never matches.
29+
*/
30+
function writeOriginAllowed(origin: string | undefined, host: string | undefined): boolean {
31+
if (origin === undefined) return true;
32+
let originHost: string | null = null;
33+
try {
34+
originHost = new URL(origin).host;
35+
} catch {
36+
originHost = null;
37+
}
38+
return !!originHost && !!host && originHost.toLowerCase() === host.toLowerCase();
39+
}
40+
2341
/**
2442
* Create a Hono sub-app with all studio API routes.
2543
*
@@ -28,6 +46,30 @@ import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
2846
*/
2947
export function createStudioApi(adapter: StudioApiAdapter): Hono {
3048
const api = new Hono();
49+
// The studio API is unauthenticated and its only legitimate caller is the
50+
// Studio page this same server serves. A state-changing request that
51+
// carries an Origin naming a different host than the request's Host did
52+
// not come from that page: it is a cross-origin request from some other
53+
// website open in the user's browser. CORS does not stop such requests
54+
// from being SENT: POST with a text/plain or form body is "simple" and
55+
// needs no preflight. It only stops the page reading the response, which
56+
// a fire-and-forget file write or render trigger does not need. Reject
57+
// those writes outright. Requests with no Origin header (curl, tests,
58+
// in-process callers) are not browser traffic and keep working, as do
59+
// reads: the guard covers state changes only.
60+
api.use(async function rejectCrossOriginWrites(c, next) {
61+
if (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS") {
62+
return next();
63+
}
64+
// Fetch Metadata: a cross-site request is refused even when the Origin
65+
// header was stripped (some same-site-but-cross-origin setups send
66+
// Sec-Fetch-Site: same-site, which stays allowed).
67+
const crossSite = c.req.header("sec-fetch-site") === "cross-site";
68+
if (crossSite || !writeOriginAllowed(c.req.header("origin"), c.req.header("host"))) {
69+
return c.json({ error: "forbidden" }, 403);
70+
}
71+
return next();
72+
});
3173
api.use(async function answerProjectDirMissingAfterErrorHandlers(c, next) {
3274
const hostHeaders = new Headers(c.res.headers);
3375
await next();

0 commit comments

Comments
 (0)