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.
This commit is contained in:
Dextheking1
2026-10-23 12:28:21 +00:00
parent c4c1e621d4
commit 42574a7a4e
2 changed files with 155 additions and 0 deletions
@@ -0,0 +1,113 @@
// @vitest-environment node
// Node environment on purpose: the package default (happy-dom) implements
// the browser fetch spec, which drops forbidden request headers such as
// Origin and Sec-Fetch-Site when a Request is constructed. A test that
// simulates cross-origin browser traffic has to set exactly those headers,
// so it needs Node's fetch classes, which keep them.
import { afterEach, describe, expect, it } from "vitest";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createStudioApi } from "./createStudioApi";
import { stubAdapter } from "./routes/stubAdapter.test-helpers";
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function createApp(): { app: ReturnType<typeof createStudioApi>; projectDir: string } {
const projectDir = mkdtempSync(join(tmpdir(), "hf-origin-guard-"));
tempDirs.push(projectDir);
return { app: createStudioApi(stubAdapter(projectDir)), projectDir };
}
const EVIL_ORIGIN = "http://evil.example:9999";
function createFile(
app: ReturnType<typeof createStudioApi>,
headers: Record<string, string>,
name = "planted.html",
): Promise<Response> {
// A real browser request always carries a Host header; app.request does
// not derive one in this environment, so send it explicitly. That keeps
// every case exercising the Origin comparison itself.
return app.request(`http://localhost/projects/demo/files/${name}`, {
method: "POST",
headers: { Host: "localhost", ...headers },
body: "<html>planted</html>",
});
}
describe("createStudioApi cross-origin write guard", () => {
it("rejects a cross-origin POST file create and writes nothing", async () => {
const { app, projectDir } = createApp();
const res = await createFile(app, { Origin: EVIL_ORIGIN, "Content-Type": "text/plain" });
expect(res.status).toBe(403);
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
});
it("rejects a cross-origin multipart upload", async () => {
const { app, projectDir } = createApp();
const form = new FormData();
form.append("files", new File(["planted"], "planted.html", { type: "text/html" }));
const res = await app.request("http://localhost/projects/demo/upload", {
method: "POST",
headers: { Host: "localhost", Origin: EVIL_ORIGIN },
body: form,
});
expect(res.status).toBe(403);
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
});
it("rejects a write whose Origin is the opaque literal null", async () => {
const { app } = createApp();
const res = await createFile(app, { Origin: "null", "Content-Type": "text/plain" });
expect(res.status).toBe(403);
});
it("rejects a write marked cross-site by Fetch Metadata even without Origin", async () => {
const { app } = createApp();
const res = await createFile(app, { "Sec-Fetch-Site": "cross-site" });
expect(res.status).toBe(403);
});
it("rejects a cross-origin PUT overwrite", async () => {
const { app } = createApp();
const res = await app.request("http://localhost/projects/demo/files/planted.html", {
method: "PUT",
headers: { Host: "localhost", Origin: EVIL_ORIGIN, "If-None-Match": "*" },
body: "overwritten",
});
expect(res.status).toBe(403);
});
it("allows a same-origin write (Origin host matches Host)", async () => {
const { app, projectDir } = createApp();
const res = await createFile(app, {
Origin: "http://localhost",
"Content-Type": "text/plain",
});
expect(res.status).toBe(201);
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
});
it("allows a write with no Origin header (non-browser callers)", async () => {
const { app, projectDir } = createApp();
const res = await createFile(app, { "Content-Type": "text/plain" });
expect(res.status).toBe(201);
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
});
it("does not block reads from any origin", async () => {
const { app } = createApp();
await createFile(app, { "Content-Type": "text/plain" });
const res = await app.request("http://localhost/projects/demo/files/planted.html", {
headers: { Origin: EVIL_ORIGIN },
});
expect(res.status).toBe(200);
});
});
@@ -20,6 +20,24 @@ import { registerHistoryRoutes } from "./routes/history.js";
import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
/**
* Whether a state-changing request's Origin names the host the request was
* sent to. No Origin header means a non-browser caller (curl, tests,
* in-process), which is allowed. An unparseable Origin (including the
* literal "null" a sandboxed page sends) names no host this server serves,
* so it never matches.
*/
function writeOriginAllowed(origin: string | undefined, host: string | undefined): boolean {
if (origin === undefined) return true;
let originHost: string | null = null;
try {
originHost = new URL(origin).host;
} catch {
originHost = null;
}
return !!originHost && !!host && originHost.toLowerCase() === host.toLowerCase();
}
/**
* Create a Hono sub-app with all studio API routes.
*
@@ -28,6 +46,30 @@ import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
*/
export function createStudioApi(adapter: StudioApiAdapter): Hono {
const api = new Hono();
// The studio API is unauthenticated and its only legitimate caller is the
// Studio page this same server serves. A state-changing request that
// carries an Origin naming a different host than the request's Host did
// not come from that page: it is a cross-origin request from some other
// website open in the user's browser. CORS does not stop such requests
// from being SENT: POST with a text/plain or form body is "simple" and
// needs no preflight. It only stops the page reading the response, which
// a fire-and-forget file write or render trigger does not need. Reject
// those writes outright. Requests with no Origin header (curl, tests,
// in-process callers) are not browser traffic and keep working, as do
// reads: the guard covers state changes only.
api.use(async function rejectCrossOriginWrites(c, next) {
if (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS") {
return next();
}
// Fetch Metadata: a cross-site request is refused even when the Origin
// header was stripped (some same-site-but-cross-origin setups send
// Sec-Fetch-Site: same-site, which stays allowed).
const crossSite = c.req.header("sec-fetch-site") === "cross-site";
if (crossSite || !writeOriginAllowed(c.req.header("origin"), c.req.header("host"))) {
return c.json({ error: "forbidden" }, 403);
}
return next();
});
api.use(async function answerProjectDirMissingAfterErrorHandlers(c, next) {
const hostHeaders = new Headers(c.res.headers);
await next();