Skip to content

Commit 89011e1

Browse files
Dextheking1Dextheking1
authored andcommitted
fix(studio): scheme-aware origin check, allowedHosts option
sameOriginPost compares the Origin against the request's own origin in a scheme-aware way: the scheme comes from the request URL, or from x-forwarded-proto when a TLS proxy supplies it, and x-forwarded-host is honored for tunnels that rewrite Host. An https origin on the same host now passes, where every write behind a TLS proxy 403d before. createStudioApi gains an allowedHosts option naming extra hosts the guard accepts, for hosts mounting the API on their own domain. Default is unchanged: loopback, or the HYPERFRAMES_PREVIEW_HOST bind. desktopRoutes drops its sameOriginPost re-export; its test imports the shared subpath directly. Comments trimmed so the comment ratchet passes. Docs note in docs/packages/studio-server.mdx. Tests: origin guard suite 17/17 (6 new: https same-origin write, forwarded proto, https origin on a plain http request, allowedHosts accept and reject, tunnel with rewritten Host). Full studio-server suite 1360 passed, 1 failed (history file-mode, fails on the base commit too in this environment). CLI server suites 226 passed. Typecheck, oxlint, oxfmt clean.
1 parent 110a300 commit 89011e1

7 files changed

Lines changed: 193 additions & 111 deletions

File tree

‎docs/packages/studio-server.mdx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,20 @@ Studio reads the flag once, when its modules load, so set
4747
`window.__HF_STUDIO_ENV__` before loading Studio; the CLI injects it, but a host
4848
that mounts the API itself must inject it too.
4949

50+
The API is unauthenticated, so state-changing requests are checked against
51+
the request's own origin, scheme included: a write is accepted only when it
52+
comes from the Studio page this server serves. Loopback works with no setup.
53+
If you mount the API on a public host name (your own domain, a tunnel, a
54+
Codespaces address), name it in `allowedHosts` so writes from that origin
55+
pass:
56+
57+
```ts
58+
app.route(
59+
"/api",
60+
createStudioApi(adapter, { allowedHosts: ["studio.example.com"] }),
61+
);
62+
```
63+
5064
A `StudioApiAdapter` supplies:
5165

5266
- project listing and resolution;

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { Hono } from "hono";
22
import { describe, expect, it, vi } from "vitest";
33
import { desktopDownloadUrl, type DesktopOpenResult } from "../utils/desktopApp.js";
4-
import { mountDesktopRoutes, sameOriginPost } from "./desktopRoutes.js";
4+
import { mountDesktopRoutes } from "./desktopRoutes.js";
5+
import { sameOriginPost } from "@hyperframes/studio-server/request-identity";
56

67
const STUDIO = {
78
host: "localhost:3002",

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,14 @@ import {
77
} from "../utils/desktopApp.js";
88
import { sameOriginPost } from "@hyperframes/studio-server/request-identity";
99

10-
// Re-exported for this module's tests; the definition is shared with
11-
// the studio API's write guard.
12-
export { sameOriginPost };
10+
/** Scheme of a request URL ("http" or "https"), or undefined when it does not parse. */
11+
function urlSchemeOf(url: string): string | undefined {
12+
try {
13+
return new URL(url).protocol.replace(/:$/, "") || undefined;
14+
} catch {
15+
return undefined;
16+
}
17+
}
1318

1419
const CTA_ID = /^[A-Za-z0-9-]{1,64}$/;
1520

@@ -40,6 +45,9 @@ export function mountDesktopRoutes(
4045
host: c.req.header("host"),
4146
origin: c.req.header("origin"),
4247
fetchSite: c.req.header("sec-fetch-site"),
48+
proto: urlSchemeOf(c.req.url),
49+
forwardedProto: c.req.header("x-forwarded-proto"),
50+
forwardedHost: c.req.header("x-forwarded-host"),
4351
});
4452
if (!allowed) return c.json({ error: "forbidden" }, 403);
4553
if (!ready)

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

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,107 @@ describe("createStudioApi cross-origin write guard", () => {
144144
});
145145
expect(res.status).toBe(200);
146146
});
147+
148+
it("allows an HTTPS same-origin write", async () => {
149+
const { app, projectDir } = createApp();
150+
const res = await app.request("https://localhost:3002/projects/demo/files/planted.html", {
151+
method: "POST",
152+
headers: {
153+
Host: "localhost:3002",
154+
Origin: "https://localhost:3002",
155+
"Content-Type": "text/plain",
156+
},
157+
body: "<html>planted</html>",
158+
});
159+
expect(res.status).toBe(201);
160+
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
161+
});
162+
163+
it("allows an HTTPS write behind a TLS proxy that forwards the proto", async () => {
164+
const { app, projectDir } = createApp();
165+
const res = await app.request("http://localhost:3002/projects/demo/files/planted.html", {
166+
method: "POST",
167+
headers: {
168+
Host: "localhost:3002",
169+
Origin: "https://localhost:3002",
170+
"X-Forwarded-Proto": "https",
171+
"Content-Type": "text/plain",
172+
},
173+
body: "<html>planted</html>",
174+
});
175+
expect(res.status).toBe(201);
176+
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
177+
});
178+
179+
it("rejects an HTTPS Origin on a request that arrived over plain HTTP", async () => {
180+
const { app, projectDir } = createApp();
181+
const res = await app.request("http://localhost:3002/projects/demo/files/planted.html", {
182+
method: "POST",
183+
headers: {
184+
Host: "localhost:3002",
185+
Origin: "https://localhost:3002",
186+
"Content-Type": "text/plain",
187+
},
188+
body: "<html>planted</html>",
189+
});
190+
expect(res.status).toBe(403);
191+
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
192+
});
193+
194+
it("allows a write on a host named in the allowedHosts option", async () => {
195+
const projectDir = mkdtempSync(join(tmpdir(), "hf-origin-guard-"));
196+
tempDirs.push(projectDir);
197+
const app = createStudioApi(stubAdapter(projectDir), {
198+
allowedHosts: ["studio.example.com"],
199+
});
200+
const res = await app.request("http://studio.example.com/projects/demo/files/planted.html", {
201+
method: "POST",
202+
headers: {
203+
Host: "studio.example.com",
204+
Origin: "https://studio.example.com",
205+
"X-Forwarded-Proto": "https",
206+
"Content-Type": "text/plain",
207+
},
208+
body: "<html>planted</html>",
209+
});
210+
expect(res.status).toBe(201);
211+
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
212+
});
213+
214+
it("rejects a write on that host without the allowedHosts option", async () => {
215+
const { app, projectDir } = createApp();
216+
const res = await app.request("http://studio.example.com/projects/demo/files/planted.html", {
217+
method: "POST",
218+
headers: {
219+
Host: "studio.example.com",
220+
Origin: "https://studio.example.com",
221+
"X-Forwarded-Proto": "https",
222+
"Content-Type": "text/plain",
223+
},
224+
body: "<html>planted</html>",
225+
});
226+
expect(res.status).toBe(403);
227+
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
228+
});
229+
230+
it("allows a write through a tunnel that rewrites Host and forwards its own", async () => {
231+
const projectDir = mkdtempSync(join(tmpdir(), "hf-origin-guard-"));
232+
tempDirs.push(projectDir);
233+
const app = createStudioApi(stubAdapter(projectDir), {
234+
allowedHosts: ["demo.tunnels.example"],
235+
});
236+
const res = await app.request("http://localhost/projects/demo/files/planted.html", {
237+
method: "POST",
238+
headers: {
239+
Host: "localhost",
240+
Origin: "https://demo.tunnels.example",
241+
"X-Forwarded-Proto": "https",
242+
"X-Forwarded-Host": "demo.tunnels.example",
243+
"Content-Type": "text/plain",
244+
},
245+
body: "<html>planted</html>",
246+
});
247+
expect(res.status).toBe(201);
248+
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
249+
});
147250
});

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

Lines changed: 23 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
2121
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
2222
import { sameOriginPost } from "./helpers/requestIdentity.js";
2323

24-
/** Host named by a request URL, or undefined when it does not parse. */
2524
function urlHost(url: string): string | undefined {
2625
try {
2726
return new URL(url).host || undefined;
@@ -30,36 +29,26 @@ function urlHost(url: string): string | undefined {
3029
}
3130
}
3231

33-
/**
34-
* Create a Hono sub-app with all studio API routes.
35-
*
36-
* Both the vite dev server and CLI embedded server mount this app
37-
* under /api, each providing their own adapter for host-specific behavior.
38-
*/
39-
export function createStudioApi(adapter: StudioApiAdapter): Hono {
32+
function urlScheme(url: string): string | undefined {
33+
try {
34+
return new URL(url).protocol.replace(/:$/, "") || undefined;
35+
} catch {
36+
return undefined;
37+
}
38+
}
39+
40+
export interface StudioApiOptions {
41+
/**
42+
* Extra host names the write guard accepts as this server, for hosts
43+
* mounting the API on their own domain or behind a tunnel or proxy.
44+
*/
45+
allowedHosts?: readonly string[];
46+
}
47+
48+
export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOptions = {}): Hono {
4049
const api = new Hono();
41-
// The studio API is unauthenticated and its only legitimate caller is the
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
44-
// website open in the user's browser. CORS does not stop such requests
45-
// from being SENT: POST with a text/plain or form body is "simple" and
46-
// needs no preflight. It only stops the page reading the response, which
47-
// a fire-and-forget file write or render trigger does not need. Reject
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.
50+
// This API is unauthenticated and simple cross-origin POSTs need no
51+
// preflight, so the guard rejects writes the shared predicate refuses.
6352
api.use(async function rejectCrossOriginWrites(c, next) {
6453
if (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS") {
6554
return next();
@@ -68,6 +57,10 @@ export function createStudioApi(adapter: StudioApiAdapter): Hono {
6857
host: c.req.header("host") ?? urlHost(c.req.url),
6958
origin: c.req.header("origin"),
7059
fetchSite: c.req.header("sec-fetch-site"),
60+
proto: urlScheme(c.req.url),
61+
forwardedProto: c.req.header("x-forwarded-proto"),
62+
forwardedHost: c.req.header("x-forwarded-host"),
63+
allowedHosts: options.allowedHosts,
7164
});
7265
if (!allowed) return c.json({ error: "forbidden" }, 403);
7366
return next();

0 commit comments

Comments
 (0)