Skip to content

Commit 110a300

Browse files
Dextheking1Dextheking1
authored andcommitted
fix(studio): guard API writes with the shared sameOriginPost predicate
Replace the guard's own Origin-host-equals-Host comparison with the CLI server's sameOriginPost, lifted into studio-server as helpers/requestIdentity (new ./request-identity subpath) together with isLoopbackHost and identityAllowed. The CLI imports the same definition from there; desktopRoutes and telemetryIdentity re-export so their callers and tests do not move. The old comparison let a page whose DNS name resolves to 127.0.0.1 through, because its Origin and Host agree with each other. sameOriginPost also requires the Host to be an identity the server answers to, and refuses any Sec-Fetch-Site other than same-origin. Regression tests cover the rebinding pair, a no-Origin write on such a host, and the same-site case.
1 parent 42574a7 commit 110a300

8 files changed

Lines changed: 236 additions & 157 deletions

File tree

‎packages/cli/src/server/desktopRoutes.ts‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,13 @@ import {
55
desktopInstalled,
66
openInDesktop,
77
} from "../utils/desktopApp.js";
8-
import { identityAllowed } from "./telemetryIdentity.js";
8+
import { sameOriginPost } from "@hyperframes/studio-server/request-identity";
99

10-
const CTA_ID = /^[A-Za-z0-9-]{1,64}$/;
10+
// Re-exported for this module's tests; the definition is shared with
11+
// the studio API's write guard.
12+
export { sameOriginPost };
1113

12-
/** A bodiless POST is a simple request, so any page can send one to localhost: it has to come from this Studio. */
13-
export function sameOriginPost(headers: {
14-
host?: string;
15-
origin?: string;
16-
fetchSite?: string;
17-
}): boolean {
18-
const { host, origin, fetchSite } = headers;
19-
if (!host || !identityAllowed(host)) return false;
20-
if (fetchSite && fetchSite !== "same-origin") return false;
21-
return origin === undefined || origin === `http://${host}`;
22-
}
14+
const CTA_ID = /^[A-Za-z0-9-]{1,64}$/;
2315

2416
/** The desktop-app button's route: show it or not, the download, and whether the app here takes the project. */
2517
export function mountDesktopRoutes(

‎packages/cli/src/server/telemetryIdentity.ts‎

Lines changed: 15 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
// server's heavy render dependencies (@hyperframes/producer, engine, …).
1717
// ---------------------------------------------------------------------------
1818

19-
import { hostname, networkInterfaces } from "node:os";
19+
import { identityAllowed, isLoopbackHost } from "@hyperframes/studio-server/request-identity";
2020
import { readConfig, readConfigFresh } from "../telemetry/config.js";
2121
import {
2222
resetTelemetryPostureCache,
@@ -25,6 +25,12 @@ import {
2525
import { canaryDecisionsForStudio, type CliCanaryDecision } from "../telemetry/canary.js";
2626
import { detectAgentRuntime } from "../telemetry/agent_runtime.js";
2727

28+
// The host-identity half of this module moved to
29+
// @hyperframes/studio-server/request-identity, where the studio API's
30+
// write guard shares the same definition. Re-exported so this module's
31+
// existing importers keep one source for it.
32+
export { identityAllowed, isLoopbackHost };
33+
2834
/**
2935
* The CLI's anonymous distinct id to hand to Studio, or null when CLI telemetry
3036
* is disabled or no id is available. Fail-silent — telemetry must never break
@@ -58,33 +64,6 @@ function resolveCliBucketSeed(): string | null {
5864
}
5965
}
6066

61-
/**
62-
* Is this request's `Host` a loopback name the studio server could have been
63-
* reached on directly?
64-
*
65-
* A bare `[::1]`/`localhost`/dotted-quad check rather than a full parse: the
66-
* port is irrelevant (any port on loopback is us), and anything exotic enough
67-
* to miss here should be refused rather than guessed at.
68-
*
69-
* Scope, stated precisely: this is a **DNS-rebinding mitigation for browsers**,
70-
* not access control. A browser sets `Host` from the URL it was given, so a
71-
* page that rebinds its own hostname to 127.0.0.1 arrives carrying that
72-
* hostname and is refused. A non-browser client sets `Host` to whatever it
73-
* likes, so this stops nothing there — but on a loopback-bound server such a
74-
* client is already local, and on a LAN-bound one it can read the project
75-
* files through the unauthenticated studio API anyway. See `identityAllowed`.
76-
*/
77-
export function isLoopbackHost(host: string | undefined): boolean {
78-
if (!host) return false;
79-
// Strip the port. IPv6 literals are bracketed (`[::1]:1234`), so take the
80-
// bracketed part when present and only split on ":" otherwise.
81-
const bracketed = /^\[([^\]]+)\]/.exec(host);
82-
const hostname = (bracketed ? bracketed[1] : host.split(":")[0])?.toLowerCase() ?? "";
83-
if (hostname === "localhost" || hostname === "::1" || hostname === "0:0:0:0:0:0:0:1") return true;
84-
// 127.0.0.0/8 — the whole loopback block, not just 127.0.0.1.
85-
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
86-
}
87-
8867
// JSON.stringify does not escape "<" or "/". Escaping both means no
8968
// "</script>" (or "</…") sequence can form in the emitted value, so it can
9069
// never terminate the inline <script> or open a new tag. (The values are
@@ -197,96 +176,6 @@ export function buildStudioHeadScripts(
197176
return `${buildCliIdentityScript(options)}${envScript}`;
198177
}
199178

200-
/**
201-
* The `<head>` scripts for a request, given its `Host`.
202-
*
203-
* The Host split lives here rather than in the route so it is testable
204-
* without a Studio bundle on disk — the route's own test can only reach the
205-
* injection branch when `packages/studio/dist` happens to be built, which is
206-
* true locally and false in the CI test lane.
207-
*/
208-
/** Hostname of a `Host` header, port and IPv6 brackets removed. */
209-
function hostnameOf(host: string | undefined): string {
210-
if (!host) return "";
211-
const bracketed = /^\[([^\]]+)\]/.exec(host);
212-
return (bracketed ? bracketed[1] : host.split(":")[0])?.toLowerCase() ?? "";
213-
}
214-
215-
/**
216-
* Names this machine legitimately answers to on a wildcard bind: every
217-
* interface address, plus its own hostname and the `.local` mDNS form people
218-
* actually type. Fail closed — a throw yields an empty set, which denies.
219-
*/
220-
function localNames(): Set<string> {
221-
const names = new Set<string>();
222-
try {
223-
for (const entries of Object.values(networkInterfaces())) {
224-
for (const entry of entries ?? []) names.add(entry.address.toLowerCase());
225-
}
226-
const self = hostname().toLowerCase();
227-
if (self !== "") {
228-
names.add(self);
229-
// `my-box` is reachable as `my-box.local`, and a `my-box.lan.example`
230-
// FQDN is reachable by its short form. Register both directions.
231-
names.add(`${self}.local`);
232-
const short = self.split(".")[0];
233-
if (short !== undefined && short !== "") {
234-
names.add(short);
235-
names.add(`${short}.local`);
236-
}
237-
}
238-
} catch {
239-
/* fail closed */
240-
}
241-
return names;
242-
}
243-
244-
/**
245-
* Wildcard binds answer on every local name; a specific bind on itself only.
246-
*
247-
* This is the part that was missing: the previous rule accepted ANY Host once
248-
* the env var was set, so a rebinding page could name itself `evil.example.com`
249-
* and still be handed the CLI identity.
250-
*/
251-
function hostMatchesBind(host: string | undefined, bind: string): boolean {
252-
const requested = hostnameOf(host);
253-
if (requested === "") return false;
254-
const bound = bind.toLowerCase();
255-
if (requested === bound) return true;
256-
return bound === "0.0.0.0" || bound === "::" || bound === "*"
257-
? localNames().has(requested)
258-
: false;
259-
}
260-
261-
/**
262-
* May this request receive the CLI's identity (distinct id + bucket seed)?
263-
*
264-
* The server binds loopback by DEFAULT and exposes the LAN only when an
265-
* operator sets `HYPERFRAMES_PREVIEW_HOST` (portUtils.ts, F-001). A loopback
266-
* `Host` is always fine: whatever reached us came via loopback, and the only
267-
* interesting attacker is a rebinding browser page — which the Host check
268-
* catches, because a browser cannot forge `Host`.
269-
*
270-
* For anything else the bind decides:
271-
*
272-
* - **Unset, or bound to loopback.** No LAN exposure was requested, so the
273-
* Host check is a live rebinding mitigation and a non-loopback Host is
274-
* refused. Previously ANY non-empty value disabled the check, so even
275-
* `HYPERFRAMES_PREVIEW_HOST=127.0.0.1` — which exposes nothing — turned the
276-
* loopback service from hostile-Host refusal into accept-everything.
277-
* - **Bound to a LAN address.** The operator opted into exposure, so identity
278-
* has to reach the LAN name the user browses or the CLI-to-Studio stitch
279-
* breaks and Studio mints a second person for the same human. But it is
280-
* still checked: the Host must name an address this machine actually
281-
* answers on, not any attacker-chosen name a rebinding page supplies.
282-
*/
283-
export function identityAllowed(host: string | undefined): boolean {
284-
if (isLoopbackHost(host)) return true;
285-
const bind = (process.env["HYPERFRAMES_PREVIEW_HOST"] ?? "").trim();
286-
if (bind === "" || isLoopbackHost(bind)) return false;
287-
return hostMatchesBind(host, bind);
288-
}
289-
290179
/**
291180
* Re-read the persisted telemetry preference for this request.
292181
*
@@ -309,6 +198,14 @@ export function refreshTelemetryPosture(): void {
309198
}
310199
}
311200

201+
/**
202+
* The `<head>` scripts for a request, given its `Host`.
203+
*
204+
* The Host split lives here rather than in the route so it is testable
205+
* without a Studio bundle on disk — the route's own test can only reach the
206+
* injection branch when `packages/studio/dist` happens to be built, which is
207+
* true locally and false in the CI test lane.
208+
*/
312209
export function buildStudioHeadScriptsForHost(envScript: string, host: string | undefined): string {
313210
refreshTelemetryPosture();
314211
return buildStudioHeadScripts(envScript, { includeIdentity: identityAllowed(host) });

‎packages/studio-server/package-subpaths.json‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@
2626
"types": "./dist/helpers/safePath.d.ts",
2727
"environments": ["bun", "node"]
2828
},
29+
"./request-identity": {
30+
"source": "./src/helpers/requestIdentity.ts",
31+
"runtime": "./dist/helpers/requestIdentity.js",
32+
"types": "./dist/helpers/requestIdentity.d.ts",
33+
"environments": ["bun", "node"]
34+
},
2935
"./hf-ids": {
3036
"source": "./src/helpers/hfIdPersist.ts",
3137
"runtime": "./dist/helpers/hfIdPersist.js",

‎packages/studio-server/package.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@
3333
"import": "./src/helpers/safePath.ts",
3434
"types": "./src/helpers/safePath.ts"
3535
},
36+
"./request-identity": {
37+
"bun": "./src/helpers/requestIdentity.ts",
38+
"node": "./dist/helpers/requestIdentity.js",
39+
"import": "./src/helpers/requestIdentity.ts",
40+
"types": "./src/helpers/requestIdentity.ts"
41+
},
3642
"./hf-ids": {
3743
"bun": "./src/helpers/hfIdPersist.ts",
3844
"node": "./dist/helpers/hfIdPersist.js",
@@ -122,6 +128,10 @@
122128
"import": "./dist/helpers/safePath.js",
123129
"types": "./dist/helpers/safePath.d.ts"
124130
},
131+
"./request-identity": {
132+
"import": "./dist/helpers/requestIdentity.js",
133+
"types": "./dist/helpers/requestIdentity.d.ts"
134+
},
125135
"./hf-ids": {
126136
"import": "./dist/helpers/hfIdPersist.js",
127137
"types": "./dist/helpers/hfIdPersist.d.ts"

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,40 @@ describe("createStudioApi cross-origin write guard", () => {
8585
expect(res.status).toBe(403);
8686
});
8787

88+
it("rejects a write from a DNS name pointing at loopback, even when Origin and Host match", async () => {
89+
// The attacker's page is served from a name that resolves to 127.0.0.1,
90+
// so its Origin and Host agree with each other and a guard that only
91+
// compares the pair lets it through. The shared predicate also requires
92+
// the Host to be an identity this server answers to, and
93+
// "rebind.example" is not one, whatever it resolves to.
94+
const { app, projectDir } = createApp();
95+
const res = await createFile(app, {
96+
Host: "rebind.example:9999",
97+
Origin: "http://rebind.example:9999",
98+
"Sec-Fetch-Site": "same-origin",
99+
"Content-Type": "text/plain",
100+
});
101+
expect(res.status).toBe(403);
102+
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
103+
});
104+
105+
it("rejects a write with no Origin when the Host is a DNS name, not a server identity", async () => {
106+
const { app, projectDir } = createApp();
107+
const res = await createFile(app, { Host: "rebind.example:9999" });
108+
expect(res.status).toBe(403);
109+
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
110+
});
111+
112+
it("rejects a same-site write even when Origin and Host match", async () => {
113+
const { app } = createApp();
114+
const res = await createFile(app, {
115+
Origin: "http://localhost",
116+
"Sec-Fetch-Site": "same-site",
117+
"Content-Type": "text/plain",
118+
});
119+
expect(res.status).toBe(403);
120+
});
121+
88122
it("allows a same-origin write (Origin host matches Host)", async () => {
89123
const { app, projectDir } = createApp();
90124
const res = await createFile(app, {

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

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,15 @@ import { registerGlobalAssetRoutes } from "./routes/globalAssets.js";
1919
import { registerHistoryRoutes } from "./routes/history.js";
2020
import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
2121
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
22+
import { sameOriginPost } from "./helpers/requestIdentity.js";
2223

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;
24+
/** Host named by a request URL, or undefined when it does not parse. */
25+
function urlHost(url: string): string | undefined {
3326
try {
34-
originHost = new URL(origin).host;
27+
return new URL(url).host || undefined;
3528
} catch {
36-
originHost = null;
29+
return undefined;
3730
}
38-
return !!originHost && !!host && originHost.toLowerCase() === host.toLowerCase();
3931
}
4032

4133
/**
@@ -47,27 +39,37 @@ function writeOriginAllowed(origin: string | undefined, host: string | undefined
4739
export function createStudioApi(adapter: StudioApiAdapter): Hono {
4840
const api = new Hono();
4941
// 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
42+
// Studio page this same server serves. A state-changing request that did
43+
// not come from that page is a cross-origin request from some other
5344
// website open in the user's browser. CORS does not stop such requests
5445
// from being SENT: POST with a text/plain or form body is "simple" and
5546
// needs no preflight. It only stops the page reading the response, which
5647
// 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.
48+
// those writes outright. Reads are unaffected: the guard covers state
49+
// changes only.
50+
//
51+
// The predicate is the CLI server's own `sameOriginPost`, shared from
52+
// helpers/requestIdentity so both servers give one answer. Comparing the
53+
// Origin host to the Host header alone is not enough: a page whose own
54+
// DNS name resolves to 127.0.0.1 sends a matching pair and walks through.
55+
// `sameOriginPost` also requires the Host to be an identity this server
56+
// answers to (a loopback literal, or the LAN name it was bound with) and
57+
// refuses any Sec-Fetch-Site other than "same-origin". Callers with no
58+
// Origin header (curl, tests, in-process) still pass on a loopback Host,
59+
// which is the only Host a loopback-bound server can be reached on. When
60+
// the Host header is absent the request never came over the wire
61+
// (in-process callers address the app by URL, and a real server builds
62+
// that URL from the Host header), so the URL's host is the same value.
6063
api.use(async function rejectCrossOriginWrites(c, next) {
6164
if (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS") {
6265
return next();
6366
}
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-
}
67+
const allowed = sameOriginPost({
68+
host: c.req.header("host") ?? urlHost(c.req.url),
69+
origin: c.req.header("origin"),
70+
fetchSite: c.req.header("sec-fetch-site"),
71+
});
72+
if (!allowed) return c.json({ error: "forbidden" }, 403);
7173
return next();
7274
});
7375
api.use(async function answerProjectDirMissingAfterErrorHandlers(c, next) {

0 commit comments

Comments
 (0)