Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/packages/studio-server.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,29 @@ Studio reads the flag once, when its modules load, so set
`window.__HF_STUDIO_ENV__` before loading Studio; the CLI injects it, but a host
that mounts the API itself must inject it too.

The API is unauthenticated, so state-changing requests are checked against
the request's own origin, scheme included: a write is accepted only when it
comes from the Studio page this server serves. Loopback works with no setup.
If you mount the API on a public host name (your own domain, a tunnel, a
Codespaces address), name it in `allowedHosts` so writes from that origin
pass:

```ts
app.route(
"/api",
createStudioApi(adapter, { allowedHosts: ["studio.example.com"] }),
);
```

With `hyperframes preview` and the Studio dev server there is no code to
change: both read the extra hosts from `HYPERFRAMES_PREVIEW_ALLOWED_HOSTS`
(comma separated) and pass them as `allowedHosts`. A refused write answers
403 with the refused host named and this variable as the fix:

```bash
HYPERFRAMES_PREVIEW_ALLOWED_HOSTS=demo.tunnels.example hyperframes preview
```

A `StudioApiAdapter` supplies:

- project listing and resolution;
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/server/desktopRoutes.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Hono } from "hono";
import { describe, expect, it, vi } from "vitest";
import { desktopDownloadUrl, type DesktopOpenResult } from "../utils/desktopApp.js";
import { mountDesktopRoutes, sameOriginPost } from "./desktopRoutes.js";
import { mountDesktopRoutes } from "./desktopRoutes.js";
import { sameOriginPost } from "@hyperframes/studio-server/request-identity";

const STUDIO = {
host: "localhost:3002",
Expand Down
26 changes: 13 additions & 13 deletions packages/cli/src/server/desktopRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,19 @@ import {
desktopInstalled,
openInDesktop,
} from "../utils/desktopApp.js";
import { identityAllowed } from "./telemetryIdentity.js";
import { sameOriginPost } from "@hyperframes/studio-server/request-identity";

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

/** A bodiless POST is a simple request, so any page can send one to localhost: it has to come from this Studio. */
export function sameOriginPost(headers: {
host?: string;
origin?: string;
fetchSite?: string;
}): boolean {
const { host, origin, fetchSite } = headers;
if (!host || !identityAllowed(host)) return false;
if (fetchSite && fetchSite !== "same-origin") return false;
return origin === undefined || origin === `http://${host}`;
/** Scheme of a request URL ("http" or "https"), or undefined when it does not parse. */
function urlSchemeOf(url: string): string | undefined {
try {
return new URL(url).protocol.replace(/:$/, "") || undefined;
} catch {
return undefined;
}
}

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

/** The desktop-app button's route: show it or not, the download, and whether the app here takes the project. */
export function mountDesktopRoutes(
app: Hono,
Expand Down Expand Up @@ -49,6 +46,9 @@ export function mountDesktopRoutes(
host: c.req.header("host"),
origin: c.req.header("origin"),
fetchSite: c.req.header("sec-fetch-site"),
proto: urlSchemeOf(c.req.url),
forwardedProto: c.req.header("x-forwarded-proto"),
forwardedHost: c.req.header("x-forwarded-host"),
});
if (!allowed) return c.json({ error: "forbidden" }, 403);
if (!ready)
Expand Down
130 changes: 130 additions & 0 deletions packages/cli/src/server/studioServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1063,3 +1063,133 @@ describe("Studio file-change SSE", () => {
expect(payload).toContain('"projectId":"demo-project"');
});
});

describe("createStudioServer /api write guard allowed hosts", () => {
const TUNNEL_HOST = "demo.tunnels.example";

async function tunnelWrite(projectDir: string): Promise<Response> {
// A write from the Studio page behind a tunnel, driven through the
// CLI's own /api/* forwarder, the way a browser save reaches the API.
return server!.app.request(
`http://${TUNNEL_HOST}/api/projects/${encodeURIComponent(basename(projectDir))}/files/planted.html`,
{
method: "POST",
headers: {
Host: TUNNEL_HOST,
Origin: `https://${TUNNEL_HOST}`,
"X-Forwarded-Proto": "https",
"Content-Type": "text/plain",
},
body: "<html>planted</html>",
},
);
}

it("refuses a tunnel write without the env var, naming the host and the var", async () => {
const projectDir = tmpProject();
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
server = createStudioServer({ projectDir });

const res = await tunnelWrite(projectDir);
expect(res.status).toBe(403);
const body = (await res.json()) as { error: string };
expect(body.error).toContain(TUNNEL_HOST);
expect(body.error).toContain("HYPERFRAMES_PREVIEW_ALLOWED_HOSTS");
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
});

it("accepts a tunnel write when HYPERFRAMES_PREVIEW_ALLOWED_HOSTS names the host", async () => {
const projectDir = tmpProject();
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS = `other.example, ${TUNNEL_HOST}`;
try {
server = createStudioServer({ projectDir });
const res = await tunnelWrite(projectDir);
expect(res.status).toBe(201);
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
} finally {
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
}
});
});

describe("createStudioServer Host check on every route", () => {
const FOREIGN_HOST = "rebound.example:3002";

function read(path: string, host: string, extra: Record<string, string> = {}): Promise<Response> {
return Promise.resolve(
server!.app.request(`http://${host}${path}`, { headers: { Host: host, ...extra } }),
);
}

function routes(projectDir: string): string[] {
const id = encodeURIComponent(basename(projectDir));
return [
"/__hyperframes_config",
"/api/projects",
`/api/projects/${id}/files/index.html`,
"/api/events",
"/",
];
}

it("refuses reads on every route for a Host the server does not answer on", async () => {
const projectDir = tmpProject();
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
server = createStudioServer({ projectDir });

for (const path of routes(projectDir)) {
const res = await read(path, FOREIGN_HOST);
expect(res.status, path).toBe(403);
const text = await res.text();
expect(text, path).not.toContain("secret-body");
expect(text, path).not.toContain(projectDir);
expect(text, path).toContain("HYPERFRAMES_PREVIEW_ALLOWED_HOSTS");
}
});

it("does not let X-Forwarded-Host stand in for the Host header", async () => {
const projectDir = tmpProject();
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
server = createStudioServer({ projectDir });

const res = await read("/__hyperframes_config", FOREIGN_HOST, {
"X-Forwarded-Host": "localhost:3002",
});
expect(res.status).toBe(403);
});

it("answers loopback names", async () => {
const projectDir = tmpProject();
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
server = createStudioServer({ projectDir });

for (const host of ["localhost:3002", "127.0.0.1:3002", "[::1]:3002"]) {
const config = await read("/__hyperframes_config", host);
expect(config.status, host).toBe(200);
const file = await read(
`/api/projects/${encodeURIComponent(basename(projectDir))}/files/index.html`,
host,
);
expect(file.status, host).toBe(200);
expect(await file.text(), host).toContain("secret-body");
}
});

it("answers a host named in HYPERFRAMES_PREVIEW_ALLOWED_HOSTS", async () => {
const projectDir = tmpProject();
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS = "demo.tunnels.example";
try {
server = createStudioServer({ projectDir });
const res = await read("/__hyperframes_config", "demo.tunnels.example");
expect(res.status).toBe(200);
const other = await read("/__hyperframes_config", FOREIGN_HOST);
expect(other.status).toBe(403);
} finally {
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
}
});
});
24 changes: 23 additions & 1 deletion packages/cli/src/server/studioServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ import {
import { emitStudioRenderComplete, emitStudioRenderError } from "./studioRenderTelemetry.js";
import { startRenderCpuSampler } from "../telemetry/renderCpu.js";
import { mountDesktopRoutes } from "./desktopRoutes.js";
import {
hostHeaderAllowed,
PREVIEW_ALLOWED_HOSTS_ENV,
previewAllowedHostsFromEnv,
} from "@hyperframes/studio-server/request-identity";
import { isDevMode } from "../utils/env.js";
import { insideHostApp } from "../utils/desktopApp.js";
import { runRenderSetupWorker } from "../utils/cancellableProcess.js";
Expand Down Expand Up @@ -903,6 +908,23 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
// ── Build the Hono app ─────────────────────────────────────────────────

const app = new Hono();
// Extra hosts from HYPERFRAMES_PREVIEW_ALLOWED_HOSTS (Codespaces, tunnels).
const allowedHosts = previewAllowedHostsFromEnv();

// Every route answers only loopback, the bind or an allowed host; a browser cannot forge Host.
app.use(async function refuseUnknownHost(c, next) {
const host = c.req.header("host") ?? new URL(c.req.url).host;
if (hostHeaderAllowed(host, allowedHosts)) return next();
return c.json(
{
error:
`forbidden: host "${host}" is not allowed. ` +
`Set ${PREVIEW_ALLOWED_HOSTS_ENV}=${host} to allow it ` +
`(comma separated for several hosts).`,
},
403,
);
});

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