Skip to content

Commit f318d3d

Browse files
jrusso1020Dextheking1claude
authored
fix(studio-server): refuse cross-origin writes and unknown hosts on the preview server (heygen-com#7490)
* fix(studio-server): reject cross-origin state-changing requests Non-GET routes in createStudioApi answer 403 unless the shared sameOriginPost predicate (lifted into studio-server's ./request-identity subpath) accepts the request: the Host must be a server identity, a present Sec-Fetch-Site must be same-origin, and a present Origin must match the effective host and scheme. Hosts behind Codespaces or tunnels allow their public name with HYPERFRAMES_PREVIEW_ALLOWED_HOSTS, read by `hyperframes preview` and the Studio dev server. Squashed from heygen-com#6128 (42574a7, 110a300, 89011e1, 41c6626, 27193bb) onto current main. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(cli): the preview server answers only the hosts it is reached by Every route of `hyperframes preview` (the forwarded studio API, the SSE stream, /__hyperframes_config and the Studio page) now answers only loopback names, the HYPERFRAMES_PREVIEW_HOST bind, or a host listed in HYPERFRAMES_PREVIEW_ALLOWED_HOSTS, the same list the write guard uses. Only the Host header counts here, since a page can set X-Forwarded-Host on its own requests and a read carries no Origin to compare it with. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Dextheking1 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent b4c7f9c commit f318d3d

14 files changed

Lines changed: 721 additions & 143 deletions

‎docs/packages/studio-server.mdx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,29 @@ 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+
64+
With `hyperframes preview` and the Studio dev server there is no code to
65+
change: both read the extra hosts from `HYPERFRAMES_PREVIEW_ALLOWED_HOSTS`
66+
(comma separated) and pass them as `allowedHosts`. A refused write answers
67+
403 with the refused host named and this variable as the fix:
68+
69+
```bash
70+
HYPERFRAMES_PREVIEW_ALLOWED_HOSTS=demo.tunnels.example hyperframes preview
71+
```
72+
5073
A `StudioApiAdapter` supplies:
5174

5275
- 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: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,19 @@ 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}$/;
11-
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}`;
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+
}
2217
}
2318

19+
const CTA_ID = /^[A-Za-z0-9-]{1,64}$/;
20+
2421
/** The desktop-app button's route: show it or not, the download, and whether the app here takes the project. */
2522
export function mountDesktopRoutes(
2623
app: Hono,
@@ -49,6 +46,9 @@ export function mountDesktopRoutes(
4946
host: c.req.header("host"),
5047
origin: c.req.header("origin"),
5148
fetchSite: c.req.header("sec-fetch-site"),
49+
proto: urlSchemeOf(c.req.url),
50+
forwardedProto: c.req.header("x-forwarded-proto"),
51+
forwardedHost: c.req.header("x-forwarded-host"),
5252
});
5353
if (!allowed) return c.json({ error: "forbidden" }, 403);
5454
if (!ready)

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

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,3 +1063,133 @@ describe("Studio file-change SSE", () => {
10631063
expect(payload).toContain('"projectId":"demo-project"');
10641064
});
10651065
});
1066+
1067+
describe("createStudioServer /api write guard allowed hosts", () => {
1068+
const TUNNEL_HOST = "demo.tunnels.example";
1069+
1070+
async function tunnelWrite(projectDir: string): Promise<Response> {
1071+
// A write from the Studio page behind a tunnel, driven through the
1072+
// CLI's own /api/* forwarder, the way a browser save reaches the API.
1073+
return server!.app.request(
1074+
`http://${TUNNEL_HOST}/api/projects/${encodeURIComponent(basename(projectDir))}/files/planted.html`,
1075+
{
1076+
method: "POST",
1077+
headers: {
1078+
Host: TUNNEL_HOST,
1079+
Origin: `https://${TUNNEL_HOST}`,
1080+
"X-Forwarded-Proto": "https",
1081+
"Content-Type": "text/plain",
1082+
},
1083+
body: "<html>planted</html>",
1084+
},
1085+
);
1086+
}
1087+
1088+
it("refuses a tunnel write without the env var, naming the host and the var", async () => {
1089+
const projectDir = tmpProject();
1090+
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
1091+
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
1092+
server = createStudioServer({ projectDir });
1093+
1094+
const res = await tunnelWrite(projectDir);
1095+
expect(res.status).toBe(403);
1096+
const body = (await res.json()) as { error: string };
1097+
expect(body.error).toContain(TUNNEL_HOST);
1098+
expect(body.error).toContain("HYPERFRAMES_PREVIEW_ALLOWED_HOSTS");
1099+
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
1100+
});
1101+
1102+
it("accepts a tunnel write when HYPERFRAMES_PREVIEW_ALLOWED_HOSTS names the host", async () => {
1103+
const projectDir = tmpProject();
1104+
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
1105+
process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS = `other.example, ${TUNNEL_HOST}`;
1106+
try {
1107+
server = createStudioServer({ projectDir });
1108+
const res = await tunnelWrite(projectDir);
1109+
expect(res.status).toBe(201);
1110+
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
1111+
} finally {
1112+
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
1113+
}
1114+
});
1115+
});
1116+
1117+
describe("createStudioServer Host check on every route", () => {
1118+
const FOREIGN_HOST = "rebound.example:3002";
1119+
1120+
function read(path: string, host: string, extra: Record<string, string> = {}): Promise<Response> {
1121+
return Promise.resolve(
1122+
server!.app.request(`http://${host}${path}`, { headers: { Host: host, ...extra } }),
1123+
);
1124+
}
1125+
1126+
function routes(projectDir: string): string[] {
1127+
const id = encodeURIComponent(basename(projectDir));
1128+
return [
1129+
"/__hyperframes_config",
1130+
"/api/projects",
1131+
`/api/projects/${id}/files/index.html`,
1132+
"/api/events",
1133+
"/",
1134+
];
1135+
}
1136+
1137+
it("refuses reads on every route for a Host the server does not answer on", async () => {
1138+
const projectDir = tmpProject();
1139+
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
1140+
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
1141+
server = createStudioServer({ projectDir });
1142+
1143+
for (const path of routes(projectDir)) {
1144+
const res = await read(path, FOREIGN_HOST);
1145+
expect(res.status, path).toBe(403);
1146+
const text = await res.text();
1147+
expect(text, path).not.toContain("secret-body");
1148+
expect(text, path).not.toContain(projectDir);
1149+
expect(text, path).toContain("HYPERFRAMES_PREVIEW_ALLOWED_HOSTS");
1150+
}
1151+
});
1152+
1153+
it("does not let X-Forwarded-Host stand in for the Host header", async () => {
1154+
const projectDir = tmpProject();
1155+
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
1156+
server = createStudioServer({ projectDir });
1157+
1158+
const res = await read("/__hyperframes_config", FOREIGN_HOST, {
1159+
"X-Forwarded-Host": "localhost:3002",
1160+
});
1161+
expect(res.status).toBe(403);
1162+
});
1163+
1164+
it("answers loopback names", async () => {
1165+
const projectDir = tmpProject();
1166+
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
1167+
server = createStudioServer({ projectDir });
1168+
1169+
for (const host of ["localhost:3002", "127.0.0.1:3002", "[::1]:3002"]) {
1170+
const config = await read("/__hyperframes_config", host);
1171+
expect(config.status, host).toBe(200);
1172+
const file = await read(
1173+
`/api/projects/${encodeURIComponent(basename(projectDir))}/files/index.html`,
1174+
host,
1175+
);
1176+
expect(file.status, host).toBe(200);
1177+
expect(await file.text(), host).toContain("secret-body");
1178+
}
1179+
});
1180+
1181+
it("answers a host named in HYPERFRAMES_PREVIEW_ALLOWED_HOSTS", async () => {
1182+
const projectDir = tmpProject();
1183+
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
1184+
process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS = "demo.tunnels.example";
1185+
try {
1186+
server = createStudioServer({ projectDir });
1187+
const res = await read("/__hyperframes_config", "demo.tunnels.example");
1188+
expect(res.status).toBe(200);
1189+
const other = await read("/__hyperframes_config", FOREIGN_HOST);
1190+
expect(other.status).toBe(403);
1191+
} finally {
1192+
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
1193+
}
1194+
});
1195+
});

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

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ import {
3636
import { emitStudioRenderComplete, emitStudioRenderError } from "./studioRenderTelemetry.js";
3737
import { startRenderCpuSampler } from "../telemetry/renderCpu.js";
3838
import { mountDesktopRoutes } from "./desktopRoutes.js";
39+
import {
40+
hostHeaderAllowed,
41+
PREVIEW_ALLOWED_HOSTS_ENV,
42+
previewAllowedHostsFromEnv,
43+
} from "@hyperframes/studio-server/request-identity";
3944
import { isDevMode } from "../utils/env.js";
4045
import { insideHostApp } from "../utils/desktopApp.js";
4146
import { runRenderSetupWorker } from "../utils/cancellableProcess.js";
@@ -903,6 +908,23 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
903908
// ── Build the Hono app ─────────────────────────────────────────────────
904909

905910
const app = new Hono();
911+
// Extra hosts from HYPERFRAMES_PREVIEW_ALLOWED_HOSTS (Codespaces, tunnels).
912+
const allowedHosts = previewAllowedHostsFromEnv();
913+
914+
// Every route answers only loopback, the bind or an allowed host; a browser cannot forge Host.
915+
app.use(async function refuseUnknownHost(c, next) {
916+
const host = c.req.header("host") ?? new URL(c.req.url).host;
917+
if (hostHeaderAllowed(host, allowedHosts)) return next();
918+
return c.json(
919+
{
920+
error:
921+
`forbidden: host "${host}" is not allowed. ` +
922+
`Set ${PREVIEW_ALLOWED_HOSTS_ENV}=${host} to allow it ` +
923+
`(comma separated for several hosts).`,
924+
},
925+
403,
926+
);
927+
});
906928

907929
// Config probe endpoint — used by port detection to identify existing
908930
// HyperFrames instances and reuse them instead of spawning duplicates.
@@ -1088,7 +1110,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
10881110
// Mount the shared studio API at /api.
10891111
// Use fetch() forwarding (not .route()) so the sub-app sees paths without
10901112
// the /api prefix — the shared module's path extraction uses c.req.path.
1091-
const api = createStudioApi(adapter);
1113+
const api = createStudioApi(adapter, { allowedHosts });
10921114
app.all("/api/*", async (c) => {
10931115
const url = new URL(c.req.url);
10941116
url.pathname = url.pathname.slice(4); // Strip "/api" prefix

0 commit comments

Comments
 (0)