Skip to content

Commit 98cfa71

Browse files
jrusso1020claude
andcommitted
fix(studio): check Host on the dev server's API routes and honor preview allowed hosts
The Studio Vite dev server now applies the same Host rule as the CLI preview server to the routes its plugin serves (/api/*, /__hyperframes_config), registered ahead of the plugin's other middleware, and also accepts the IP-literal and configured hosts Vite allows by default. HYPERFRAMES_PREVIEW_ALLOWED_HOSTS is now fed into Vite's server.allowedHosts, so a host listed there loads the Studio page as well as passing the API's checks. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c6d243a commit 98cfa71

2 files changed

Lines changed: 172 additions & 0 deletions

File tree

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
import { EventEmitter } from "node:events";
2+
import type { IncomingMessage, ServerResponse } from "node:http";
3+
import type { Plugin, ViteDevServer } from "vite";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import config from "./vite.config";
6+
7+
const ENV = "HYPERFRAMES_PREVIEW_ALLOWED_HOSTS";
8+
9+
type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => unknown;
10+
11+
interface Reply {
12+
status: number | undefined;
13+
body: string;
14+
}
15+
16+
const httpServers: EventEmitter[] = [];
17+
18+
afterEach(() => {
19+
// Closes the plugin's project watcher.
20+
for (const httpServer of httpServers.splice(0)) httpServer.emit("close");
21+
vi.unstubAllEnvs();
22+
});
23+
24+
function devApiPlugin(): Plugin {
25+
const plugin = (config.plugins ?? [])
26+
.flat(Infinity)
27+
.find(
28+
(p): p is Plugin =>
29+
typeof p === "object" && p !== null && "name" in p && p.name === "studio-dev-api",
30+
);
31+
if (!plugin) throw new Error("studio-dev-api plugin not found");
32+
return plugin;
33+
}
34+
35+
// Stands in for the studio-server module so an allowed /api/ request has something to reach.
36+
function fakeStudioServerModule(): Record<string, unknown> {
37+
return {
38+
createStudioApi: () => ({ fetch: async () => Response.json({ ok: true }) }),
39+
previewAllowedHostsFromEnv: () => [],
40+
identifyFileWrite: () => null,
41+
fileContentVersion: () => "v",
42+
affectsPreview: () => true,
43+
openProjectHistory: async () => null,
44+
DELETED_VERSION: "deleted",
45+
};
46+
}
47+
48+
function startPlugin(): Middleware[] {
49+
const middlewares: Middleware[] = [];
50+
const httpServer = new EventEmitter();
51+
httpServers.push(httpServer);
52+
const server = {
53+
middlewares: { use: (fn: Middleware) => void middlewares.push(fn) },
54+
config: { server: { host: "127.0.0.1" } },
55+
httpServer,
56+
ws: { send: () => {} },
57+
ssrLoadModule: async () => fakeStudioServerModule(),
58+
} as unknown as ViteDevServer;
59+
const configureServer = devApiPlugin().configureServer as (s: ViteDevServer) => void;
60+
configureServer(server);
61+
return middlewares;
62+
}
63+
64+
// Runs the request down the plugin's middlewares the way connect would; `undefined` status means every one passed it on.
65+
function request(middlewares: Middleware[], url: string, host: string): Promise<Reply> {
66+
return new Promise((resolve) => {
67+
const reply: Reply = { status: undefined, body: "" };
68+
const res = Object.assign(new EventEmitter(), {
69+
headersSent: false,
70+
writeHead(status: number) {
71+
reply.status = status;
72+
res.headersSent = true;
73+
return res;
74+
},
75+
write(chunk: Uint8Array | string) {
76+
reply.body += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
77+
return true;
78+
},
79+
end(chunk?: string) {
80+
if (chunk) reply.body += chunk;
81+
resolve(reply);
82+
},
83+
});
84+
const req = { url, method: "GET", headers: { host } } as IncomingMessage;
85+
const run = (index: number): void => {
86+
const middleware = middlewares[index];
87+
if (!middleware) return resolve(reply);
88+
void middleware(req, res as unknown as ServerResponse, () => run(index + 1));
89+
};
90+
run(0);
91+
});
92+
}
93+
94+
describe("studio dev server host check", () => {
95+
it("refuses a foreign Host on the plugin's API and config routes", async () => {
96+
vi.stubEnv("HYPERFRAMES_PREVIEW_PROJECT_DIR", "/tmp/project");
97+
vi.stubEnv("HYPERFRAMES_PREVIEW_PROJECT_NAME", "project");
98+
const middlewares = startPlugin();
99+
for (const url of ["/api/projects", "/__hyperframes_config", "/api/runtime.js"]) {
100+
const reply = await request(middlewares, url, "other.example:5190");
101+
expect(reply.status, url).toBe(403);
102+
expect(JSON.parse(reply.body).error, url).toContain(`"other.example:5190"`);
103+
expect(JSON.parse(reply.body).error, url).toContain(ENV);
104+
}
105+
});
106+
107+
it("serves loopback and IP-literal hosts", async () => {
108+
vi.stubEnv("HYPERFRAMES_PREVIEW_PROJECT_DIR", "/tmp/project");
109+
vi.stubEnv("HYPERFRAMES_PREVIEW_PROJECT_NAME", "project");
110+
const middlewares = startPlugin();
111+
for (const host of ["localhost:5190", "127.0.0.1:5190", "[::1]:5190", "192.168.1.20:5190"]) {
112+
expect((await request(middlewares, "/api/projects", host)).status, host).toBe(200);
113+
expect((await request(middlewares, "/__hyperframes_config", host)).status, host).toBe(200);
114+
}
115+
expect((await request(middlewares, "/api/projects", "[fe80::1]:5190")).status).toBe(200);
116+
});
117+
118+
it(`serves a host listed in ${ENV}`, async () => {
119+
vi.stubEnv(ENV, "studio.tunnel.example, other.tunnel.example");
120+
const middlewares = startPlugin();
121+
expect((await request(middlewares, "/api/projects", "studio.tunnel.example")).status).toBe(200);
122+
expect((await request(middlewares, "/api/projects", "evil.tunnel.example")).status).toBe(403);
123+
});
124+
125+
it("leaves routes the plugin does not own to Vite's own host check", async () => {
126+
const middlewares = startPlugin();
127+
expect((await request(middlewares, "/", "other.example:5190")).status).toBeUndefined();
128+
});
129+
130+
it(`adds ${ENV} hosts to server.allowedHosts so Vite serves the page on them`, async () => {
131+
vi.stubEnv(ENV, "studio.tunnel.example");
132+
vi.resetModules();
133+
const { default: fresh } = await import("./vite.config");
134+
expect(fresh.server?.allowedHosts).toEqual(["studio.tunnel.example"]);
135+
});
136+
});

‎packages/studio/vite.config.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
lstatSync,
1010
realpathSync,
1111
} from "node:fs";
12+
import { isIP } from "node:net";
1213
import { join, resolve } from "node:path";
1314
import { readNodeRequestBody } from "./vite.request-body.js";
1415
import { bindNodeRequestSignal } from "./vite.request-signal.js";
@@ -18,6 +19,11 @@ import { previewConfigPayload } from "./vite.preview-config";
1819
import { loadStudioServerDevModule } from "./vite.studio-server-module";
1920
import type { openProjectHistory } from "@hyperframes/studio-server";
2021
import { previewChangeOwner } from "./vite.preview-watch";
22+
import {
23+
hostHeaderAllowed,
24+
PREVIEW_ALLOWED_HOSTS_ENV,
25+
previewAllowedHostsFromEnv,
26+
} from "../studio-server/src/helpers/requestIdentity";
2127

2228
async function loadRuntimeSourceForDev(
2329
server: import("vite").ViteDevServer,
@@ -91,6 +97,12 @@ async function bridgeHonoResponse(
9197
res.end();
9298
}
9399

100+
// Vite allows any IP-literal Host by default, which is what keeps `--host` on a LAN address working.
101+
function isIpLiteralHost(host: string): boolean {
102+
const bracketed = /^\[([^\]]+)\]/.exec(host);
103+
return bracketed ? isIP(bracketed[1]!) === 6 : isIP(host.split(":")[0]!) === 4;
104+
}
105+
94106
// ── Vite plugin ──────────────────────────────────────────────────────────────
95107

96108
function devProjectApi(): Plugin {
@@ -197,6 +209,28 @@ function devProjectApi(): Plugin {
197209
return _api;
198210
};
199211

212+
// Vite runs its own Host check after the middlewares added here, so the
213+
// plugin's routes check Host first: the CLI preview server's rule plus
214+
// the IP literals and configured host Vite allows by default.
215+
const allowedHosts = [...previewAllowedHostsFromEnv()];
216+
if (typeof server.config.server.host === "string")
217+
allowedHosts.push(server.config.server.host);
218+
server.middlewares.use((req, res, next) => {
219+
const url = req.url ?? "";
220+
if (url !== "/__hyperframes_config" && !url.startsWith("/api/")) return next();
221+
const host = req.headers.host ?? "";
222+
if (hostHeaderAllowed(host, allowedHosts) || isIpLiteralHost(host)) return next();
223+
res.writeHead(403, { "Content-Type": "application/json" });
224+
res.end(
225+
JSON.stringify({
226+
error:
227+
`forbidden: host "${host}" is not allowed. ` +
228+
`Set ${PREVIEW_ALLOWED_HOSTS_ENV}=${host} to allow it ` +
229+
`(comma separated for several hosts).`,
230+
}),
231+
);
232+
});
233+
200234
server.middlewares.use((req, res, next) => {
201235
if (req.url !== "/__hyperframes_config") return next();
202236
const payload = previewConfigPayload(process.env, process.pid, studioPkg.version);
@@ -347,6 +381,8 @@ export default defineConfig({
347381
},
348382
server: {
349383
port: 5190,
384+
// Vite's defaults (localhost, IP literals) still apply on top of this list.
385+
allowedHosts: previewAllowedHostsFromEnv(),
350386
watch: {
351387
// A composition lives under this package's root, so Vite's HMR sees a
352388
// write to one as an html page dependency changing and full-reloads the

0 commit comments

Comments
 (0)