mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 16:08:56 +00:00
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.
This commit is contained in:
@@ -5,22 +5,14 @@ import {
|
|||||||
desktopInstalled,
|
desktopInstalled,
|
||||||
openInDesktop,
|
openInDesktop,
|
||||||
} from "../utils/desktopApp.js";
|
} from "../utils/desktopApp.js";
|
||||||
import { identityAllowed } from "./telemetryIdentity.js";
|
import { sameOriginPost } from "@hyperframes/studio-server/request-identity";
|
||||||
|
|
||||||
|
// Re-exported for this module's tests; the definition is shared with
|
||||||
|
// the studio API's write guard.
|
||||||
|
export { sameOriginPost };
|
||||||
|
|
||||||
const CTA_ID = /^[A-Za-z0-9-]{1,64}$/;
|
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}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The desktop-app button's route: show it or not, the download, and whether the app here takes the project. */
|
/** The desktop-app button's route: show it or not, the download, and whether the app here takes the project. */
|
||||||
export function mountDesktopRoutes(
|
export function mountDesktopRoutes(
|
||||||
app: Hono,
|
app: Hono,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
// server's heavy render dependencies (@hyperframes/producer, engine, …).
|
// server's heavy render dependencies (@hyperframes/producer, engine, …).
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
import { hostname, networkInterfaces } from "node:os";
|
import { identityAllowed, isLoopbackHost } from "@hyperframes/studio-server/request-identity";
|
||||||
import { readConfig, readConfigFresh } from "../telemetry/config.js";
|
import { readConfig, readConfigFresh } from "../telemetry/config.js";
|
||||||
import {
|
import {
|
||||||
resetTelemetryPostureCache,
|
resetTelemetryPostureCache,
|
||||||
@@ -25,6 +25,12 @@ import {
|
|||||||
import { canaryDecisionsForStudio, type CliCanaryDecision } from "../telemetry/canary.js";
|
import { canaryDecisionsForStudio, type CliCanaryDecision } from "../telemetry/canary.js";
|
||||||
import { detectAgentRuntime } from "../telemetry/agent_runtime.js";
|
import { detectAgentRuntime } from "../telemetry/agent_runtime.js";
|
||||||
|
|
||||||
|
// The host-identity half of this module moved to
|
||||||
|
// @hyperframes/studio-server/request-identity, where the studio API's
|
||||||
|
// write guard shares the same definition. Re-exported so this module's
|
||||||
|
// existing importers keep one source for it.
|
||||||
|
export { identityAllowed, isLoopbackHost };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The CLI's anonymous distinct id to hand to Studio, or null when CLI telemetry
|
* The CLI's anonymous distinct id to hand to Studio, or null when CLI telemetry
|
||||||
* is disabled or no id is available. Fail-silent — telemetry must never break
|
* is disabled or no id is available. Fail-silent — telemetry must never break
|
||||||
@@ -58,33 +64,6 @@ function resolveCliBucketSeed(): string | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Is this request's `Host` a loopback name the studio server could have been
|
|
||||||
* reached on directly?
|
|
||||||
*
|
|
||||||
* A bare `[::1]`/`localhost`/dotted-quad check rather than a full parse: the
|
|
||||||
* port is irrelevant (any port on loopback is us), and anything exotic enough
|
|
||||||
* to miss here should be refused rather than guessed at.
|
|
||||||
*
|
|
||||||
* Scope, stated precisely: this is a **DNS-rebinding mitigation for browsers**,
|
|
||||||
* not access control. A browser sets `Host` from the URL it was given, so a
|
|
||||||
* page that rebinds its own hostname to 127.0.0.1 arrives carrying that
|
|
||||||
* hostname and is refused. A non-browser client sets `Host` to whatever it
|
|
||||||
* likes, so this stops nothing there — but on a loopback-bound server such a
|
|
||||||
* client is already local, and on a LAN-bound one it can read the project
|
|
||||||
* files through the unauthenticated studio API anyway. See `identityAllowed`.
|
|
||||||
*/
|
|
||||||
export function isLoopbackHost(host: string | undefined): boolean {
|
|
||||||
if (!host) return false;
|
|
||||||
// Strip the port. IPv6 literals are bracketed (`[::1]:1234`), so take the
|
|
||||||
// bracketed part when present and only split on ":" otherwise.
|
|
||||||
const bracketed = /^\[([^\]]+)\]/.exec(host);
|
|
||||||
const hostname = (bracketed ? bracketed[1] : host.split(":")[0])?.toLowerCase() ?? "";
|
|
||||||
if (hostname === "localhost" || hostname === "::1" || hostname === "0:0:0:0:0:0:0:1") return true;
|
|
||||||
// 127.0.0.0/8 — the whole loopback block, not just 127.0.0.1.
|
|
||||||
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
|
|
||||||
}
|
|
||||||
|
|
||||||
// JSON.stringify does not escape "<" or "/". Escaping both means no
|
// JSON.stringify does not escape "<" or "/". Escaping both means no
|
||||||
// "</script>" (or "</…") sequence can form in the emitted value, so it can
|
// "</script>" (or "</…") sequence can form in the emitted value, so it can
|
||||||
// never terminate the inline <script> or open a new tag. (The values are
|
// never terminate the inline <script> or open a new tag. (The values are
|
||||||
@@ -197,96 +176,6 @@ export function buildStudioHeadScripts(
|
|||||||
return `${buildCliIdentityScript(options)}${envScript}`;
|
return `${buildCliIdentityScript(options)}${envScript}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The `<head>` scripts for a request, given its `Host`.
|
|
||||||
*
|
|
||||||
* The Host split lives here rather than in the route so it is testable
|
|
||||||
* without a Studio bundle on disk — the route's own test can only reach the
|
|
||||||
* injection branch when `packages/studio/dist` happens to be built, which is
|
|
||||||
* true locally and false in the CI test lane.
|
|
||||||
*/
|
|
||||||
/** Hostname of a `Host` header, port and IPv6 brackets removed. */
|
|
||||||
function hostnameOf(host: string | undefined): string {
|
|
||||||
if (!host) return "";
|
|
||||||
const bracketed = /^\[([^\]]+)\]/.exec(host);
|
|
||||||
return (bracketed ? bracketed[1] : host.split(":")[0])?.toLowerCase() ?? "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Names this machine legitimately answers to on a wildcard bind: every
|
|
||||||
* interface address, plus its own hostname and the `.local` mDNS form people
|
|
||||||
* actually type. Fail closed — a throw yields an empty set, which denies.
|
|
||||||
*/
|
|
||||||
function localNames(): Set<string> {
|
|
||||||
const names = new Set<string>();
|
|
||||||
try {
|
|
||||||
for (const entries of Object.values(networkInterfaces())) {
|
|
||||||
for (const entry of entries ?? []) names.add(entry.address.toLowerCase());
|
|
||||||
}
|
|
||||||
const self = hostname().toLowerCase();
|
|
||||||
if (self !== "") {
|
|
||||||
names.add(self);
|
|
||||||
// `my-box` is reachable as `my-box.local`, and a `my-box.lan.example`
|
|
||||||
// FQDN is reachable by its short form. Register both directions.
|
|
||||||
names.add(`${self}.local`);
|
|
||||||
const short = self.split(".")[0];
|
|
||||||
if (short !== undefined && short !== "") {
|
|
||||||
names.add(short);
|
|
||||||
names.add(`${short}.local`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* fail closed */
|
|
||||||
}
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wildcard binds answer on every local name; a specific bind on itself only.
|
|
||||||
*
|
|
||||||
* This is the part that was missing: the previous rule accepted ANY Host once
|
|
||||||
* the env var was set, so a rebinding page could name itself `evil.example.com`
|
|
||||||
* and still be handed the CLI identity.
|
|
||||||
*/
|
|
||||||
function hostMatchesBind(host: string | undefined, bind: string): boolean {
|
|
||||||
const requested = hostnameOf(host);
|
|
||||||
if (requested === "") return false;
|
|
||||||
const bound = bind.toLowerCase();
|
|
||||||
if (requested === bound) return true;
|
|
||||||
return bound === "0.0.0.0" || bound === "::" || bound === "*"
|
|
||||||
? localNames().has(requested)
|
|
||||||
: false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* May this request receive the CLI's identity (distinct id + bucket seed)?
|
|
||||||
*
|
|
||||||
* The server binds loopback by DEFAULT and exposes the LAN only when an
|
|
||||||
* operator sets `HYPERFRAMES_PREVIEW_HOST` (portUtils.ts, F-001). A loopback
|
|
||||||
* `Host` is always fine: whatever reached us came via loopback, and the only
|
|
||||||
* interesting attacker is a rebinding browser page — which the Host check
|
|
||||||
* catches, because a browser cannot forge `Host`.
|
|
||||||
*
|
|
||||||
* For anything else the bind decides:
|
|
||||||
*
|
|
||||||
* - **Unset, or bound to loopback.** No LAN exposure was requested, so the
|
|
||||||
* Host check is a live rebinding mitigation and a non-loopback Host is
|
|
||||||
* refused. Previously ANY non-empty value disabled the check, so even
|
|
||||||
* `HYPERFRAMES_PREVIEW_HOST=127.0.0.1` — which exposes nothing — turned the
|
|
||||||
* loopback service from hostile-Host refusal into accept-everything.
|
|
||||||
* - **Bound to a LAN address.** The operator opted into exposure, so identity
|
|
||||||
* has to reach the LAN name the user browses or the CLI-to-Studio stitch
|
|
||||||
* breaks and Studio mints a second person for the same human. But it is
|
|
||||||
* still checked: the Host must name an address this machine actually
|
|
||||||
* answers on, not any attacker-chosen name a rebinding page supplies.
|
|
||||||
*/
|
|
||||||
export function identityAllowed(host: string | undefined): boolean {
|
|
||||||
if (isLoopbackHost(host)) return true;
|
|
||||||
const bind = (process.env["HYPERFRAMES_PREVIEW_HOST"] ?? "").trim();
|
|
||||||
if (bind === "" || isLoopbackHost(bind)) return false;
|
|
||||||
return hostMatchesBind(host, bind);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Re-read the persisted telemetry preference for this request.
|
* Re-read the persisted telemetry preference for this request.
|
||||||
*
|
*
|
||||||
@@ -309,6 +198,14 @@ export function refreshTelemetryPosture(): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `<head>` scripts for a request, given its `Host`.
|
||||||
|
*
|
||||||
|
* The Host split lives here rather than in the route so it is testable
|
||||||
|
* without a Studio bundle on disk — the route's own test can only reach the
|
||||||
|
* injection branch when `packages/studio/dist` happens to be built, which is
|
||||||
|
* true locally and false in the CI test lane.
|
||||||
|
*/
|
||||||
export function buildStudioHeadScriptsForHost(envScript: string, host: string | undefined): string {
|
export function buildStudioHeadScriptsForHost(envScript: string, host: string | undefined): string {
|
||||||
refreshTelemetryPosture();
|
refreshTelemetryPosture();
|
||||||
return buildStudioHeadScripts(envScript, { includeIdentity: identityAllowed(host) });
|
return buildStudioHeadScripts(envScript, { includeIdentity: identityAllowed(host) });
|
||||||
|
|||||||
@@ -26,6 +26,12 @@
|
|||||||
"types": "./dist/helpers/safePath.d.ts",
|
"types": "./dist/helpers/safePath.d.ts",
|
||||||
"environments": ["bun", "node"]
|
"environments": ["bun", "node"]
|
||||||
},
|
},
|
||||||
|
"./request-identity": {
|
||||||
|
"source": "./src/helpers/requestIdentity.ts",
|
||||||
|
"runtime": "./dist/helpers/requestIdentity.js",
|
||||||
|
"types": "./dist/helpers/requestIdentity.d.ts",
|
||||||
|
"environments": ["bun", "node"]
|
||||||
|
},
|
||||||
"./hf-ids": {
|
"./hf-ids": {
|
||||||
"source": "./src/helpers/hfIdPersist.ts",
|
"source": "./src/helpers/hfIdPersist.ts",
|
||||||
"runtime": "./dist/helpers/hfIdPersist.js",
|
"runtime": "./dist/helpers/hfIdPersist.js",
|
||||||
|
|||||||
@@ -33,6 +33,12 @@
|
|||||||
"import": "./src/helpers/safePath.ts",
|
"import": "./src/helpers/safePath.ts",
|
||||||
"types": "./src/helpers/safePath.ts"
|
"types": "./src/helpers/safePath.ts"
|
||||||
},
|
},
|
||||||
|
"./request-identity": {
|
||||||
|
"bun": "./src/helpers/requestIdentity.ts",
|
||||||
|
"node": "./dist/helpers/requestIdentity.js",
|
||||||
|
"import": "./src/helpers/requestIdentity.ts",
|
||||||
|
"types": "./src/helpers/requestIdentity.ts"
|
||||||
|
},
|
||||||
"./hf-ids": {
|
"./hf-ids": {
|
||||||
"bun": "./src/helpers/hfIdPersist.ts",
|
"bun": "./src/helpers/hfIdPersist.ts",
|
||||||
"node": "./dist/helpers/hfIdPersist.js",
|
"node": "./dist/helpers/hfIdPersist.js",
|
||||||
@@ -122,6 +128,10 @@
|
|||||||
"import": "./dist/helpers/safePath.js",
|
"import": "./dist/helpers/safePath.js",
|
||||||
"types": "./dist/helpers/safePath.d.ts"
|
"types": "./dist/helpers/safePath.d.ts"
|
||||||
},
|
},
|
||||||
|
"./request-identity": {
|
||||||
|
"import": "./dist/helpers/requestIdentity.js",
|
||||||
|
"types": "./dist/helpers/requestIdentity.d.ts"
|
||||||
|
},
|
||||||
"./hf-ids": {
|
"./hf-ids": {
|
||||||
"import": "./dist/helpers/hfIdPersist.js",
|
"import": "./dist/helpers/hfIdPersist.js",
|
||||||
"types": "./dist/helpers/hfIdPersist.d.ts"
|
"types": "./dist/helpers/hfIdPersist.d.ts"
|
||||||
|
|||||||
@@ -85,6 +85,40 @@ describe("createStudioApi cross-origin write guard", () => {
|
|||||||
expect(res.status).toBe(403);
|
expect(res.status).toBe(403);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("rejects a write from a DNS name pointing at loopback, even when Origin and Host match", async () => {
|
||||||
|
// The attacker's page is served from a name that resolves to 127.0.0.1,
|
||||||
|
// so its Origin and Host agree with each other and a guard that only
|
||||||
|
// compares the pair lets it through. The shared predicate also requires
|
||||||
|
// the Host to be an identity this server answers to, and
|
||||||
|
// "rebind.example" is not one, whatever it resolves to.
|
||||||
|
const { app, projectDir } = createApp();
|
||||||
|
const res = await createFile(app, {
|
||||||
|
Host: "rebind.example:9999",
|
||||||
|
Origin: "http://rebind.example:9999",
|
||||||
|
"Sec-Fetch-Site": "same-origin",
|
||||||
|
"Content-Type": "text/plain",
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a write with no Origin when the Host is a DNS name, not a server identity", async () => {
|
||||||
|
const { app, projectDir } = createApp();
|
||||||
|
const res = await createFile(app, { Host: "rebind.example:9999" });
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a same-site write even when Origin and Host match", async () => {
|
||||||
|
const { app } = createApp();
|
||||||
|
const res = await createFile(app, {
|
||||||
|
Origin: "http://localhost",
|
||||||
|
"Sec-Fetch-Site": "same-site",
|
||||||
|
"Content-Type": "text/plain",
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
it("allows a same-origin write (Origin host matches Host)", async () => {
|
it("allows a same-origin write (Origin host matches Host)", async () => {
|
||||||
const { app, projectDir } = createApp();
|
const { app, projectDir } = createApp();
|
||||||
const res = await createFile(app, {
|
const res = await createFile(app, {
|
||||||
|
|||||||
@@ -19,23 +19,15 @@ import { registerGlobalAssetRoutes } from "./routes/globalAssets.js";
|
|||||||
import { registerHistoryRoutes } from "./routes/history.js";
|
import { registerHistoryRoutes } from "./routes/history.js";
|
||||||
import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
|
import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
|
||||||
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
|
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
|
||||||
|
import { sameOriginPost } from "./helpers/requestIdentity.js";
|
||||||
|
|
||||||
/**
|
/** Host named by a request URL, or undefined when it does not parse. */
|
||||||
* Whether a state-changing request's Origin names the host the request was
|
function urlHost(url: string): string | undefined {
|
||||||
* sent to. No Origin header means a non-browser caller (curl, tests,
|
|
||||||
* in-process), which is allowed. An unparseable Origin (including the
|
|
||||||
* literal "null" a sandboxed page sends) names no host this server serves,
|
|
||||||
* so it never matches.
|
|
||||||
*/
|
|
||||||
function writeOriginAllowed(origin: string | undefined, host: string | undefined): boolean {
|
|
||||||
if (origin === undefined) return true;
|
|
||||||
let originHost: string | null = null;
|
|
||||||
try {
|
try {
|
||||||
originHost = new URL(origin).host;
|
return new URL(url).host || undefined;
|
||||||
} catch {
|
} catch {
|
||||||
originHost = null;
|
return undefined;
|
||||||
}
|
}
|
||||||
return !!originHost && !!host && originHost.toLowerCase() === host.toLowerCase();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -47,27 +39,37 @@ function writeOriginAllowed(origin: string | undefined, host: string | undefined
|
|||||||
export function createStudioApi(adapter: StudioApiAdapter): Hono {
|
export function createStudioApi(adapter: StudioApiAdapter): Hono {
|
||||||
const api = new Hono();
|
const api = new Hono();
|
||||||
// The studio API is unauthenticated and its only legitimate caller is the
|
// The studio API is unauthenticated and its only legitimate caller is the
|
||||||
// Studio page this same server serves. A state-changing request that
|
// Studio page this same server serves. A state-changing request that did
|
||||||
// carries an Origin naming a different host than the request's Host did
|
// not come from that page is a cross-origin request from some other
|
||||||
// not come from that page: it is a cross-origin request from some other
|
|
||||||
// website open in the user's browser. CORS does not stop such requests
|
// website open in the user's browser. CORS does not stop such requests
|
||||||
// from being SENT: POST with a text/plain or form body is "simple" and
|
// from being SENT: POST with a text/plain or form body is "simple" and
|
||||||
// needs no preflight. It only stops the page reading the response, which
|
// needs no preflight. It only stops the page reading the response, which
|
||||||
// a fire-and-forget file write or render trigger does not need. Reject
|
// a fire-and-forget file write or render trigger does not need. Reject
|
||||||
// those writes outright. Requests with no Origin header (curl, tests,
|
// those writes outright. Reads are unaffected: the guard covers state
|
||||||
// in-process callers) are not browser traffic and keep working, as do
|
// changes only.
|
||||||
// reads: the guard covers state changes only.
|
//
|
||||||
|
// The predicate is the CLI server's own `sameOriginPost`, shared from
|
||||||
|
// helpers/requestIdentity so both servers give one answer. Comparing the
|
||||||
|
// Origin host to the Host header alone is not enough: a page whose own
|
||||||
|
// DNS name resolves to 127.0.0.1 sends a matching pair and walks through.
|
||||||
|
// `sameOriginPost` also requires the Host to be an identity this server
|
||||||
|
// answers to (a loopback literal, or the LAN name it was bound with) and
|
||||||
|
// refuses any Sec-Fetch-Site other than "same-origin". Callers with no
|
||||||
|
// Origin header (curl, tests, in-process) still pass on a loopback Host,
|
||||||
|
// which is the only Host a loopback-bound server can be reached on. When
|
||||||
|
// the Host header is absent the request never came over the wire
|
||||||
|
// (in-process callers address the app by URL, and a real server builds
|
||||||
|
// that URL from the Host header), so the URL's host is the same value.
|
||||||
api.use(async function rejectCrossOriginWrites(c, next) {
|
api.use(async function rejectCrossOriginWrites(c, next) {
|
||||||
if (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS") {
|
if (c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS") {
|
||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
// Fetch Metadata: a cross-site request is refused even when the Origin
|
const allowed = sameOriginPost({
|
||||||
// header was stripped (some same-site-but-cross-origin setups send
|
host: c.req.header("host") ?? urlHost(c.req.url),
|
||||||
// Sec-Fetch-Site: same-site, which stays allowed).
|
origin: c.req.header("origin"),
|
||||||
const crossSite = c.req.header("sec-fetch-site") === "cross-site";
|
fetchSite: c.req.header("sec-fetch-site"),
|
||||||
if (crossSite || !writeOriginAllowed(c.req.header("origin"), c.req.header("host"))) {
|
});
|
||||||
return c.json({ error: "forbidden" }, 403);
|
if (!allowed) return c.json({ error: "forbidden" }, 403);
|
||||||
}
|
|
||||||
return next();
|
return next();
|
||||||
});
|
});
|
||||||
api.use(async function answerProjectDirMissingAfterErrorHandlers(c, next) {
|
api.use(async function answerProjectDirMissingAfterErrorHandlers(c, next) {
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
/**
|
||||||
|
* The one answer to "is this write same origin", shared by the CLI server
|
||||||
|
* and the studio API.
|
||||||
|
*
|
||||||
|
* Lifted out of the CLI server so both import this one definition: the CLI's
|
||||||
|
* open-in-desktop route and the studio API's write guard ask the same
|
||||||
|
* question, and two copies of the check would drift into two different
|
||||||
|
* answers. The split also keeps the predicate unit-testable without pulling
|
||||||
|
* in either server's heavier dependencies.
|
||||||
|
*/
|
||||||
|
import { hostname, networkInterfaces } from "node:os";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Is this request's `Host` a loopback name the studio server could have been
|
||||||
|
* reached on directly?
|
||||||
|
*
|
||||||
|
* A bare `[::1]`/`localhost`/dotted-quad check rather than a full parse: the
|
||||||
|
* port is irrelevant (any port on loopback is us), and anything exotic enough
|
||||||
|
* to miss here should be refused rather than guessed at.
|
||||||
|
*
|
||||||
|
* Scope, stated precisely: this is a **DNS-rebinding mitigation for browsers**,
|
||||||
|
* not access control. A browser sets `Host` from the URL it was given, so a
|
||||||
|
* page that rebinds its own hostname to 127.0.0.1 arrives carrying that
|
||||||
|
* hostname and is refused. A non-browser client sets `Host` to whatever it
|
||||||
|
* likes, so this stops nothing there — but on a loopback-bound server such a
|
||||||
|
* client is already local, and on a LAN-bound one it can read the project
|
||||||
|
* files through the unauthenticated studio API anyway. See `identityAllowed`.
|
||||||
|
*/
|
||||||
|
export function isLoopbackHost(host: string | undefined): boolean {
|
||||||
|
if (!host) return false;
|
||||||
|
// Strip the port. IPv6 literals are bracketed (`[::1]:1234`), so take the
|
||||||
|
// bracketed part when present and only split on ":" otherwise.
|
||||||
|
const bracketed = /^\[([^\]]+)\]/.exec(host);
|
||||||
|
const hostname = (bracketed ? bracketed[1] : host.split(":")[0])?.toLowerCase() ?? "";
|
||||||
|
if (hostname === "localhost" || hostname === "::1" || hostname === "0:0:0:0:0:0:0:1") return true;
|
||||||
|
// 127.0.0.0/8 — the whole loopback block, not just 127.0.0.1.
|
||||||
|
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hostname of a `Host` header, port and IPv6 brackets removed. */
|
||||||
|
function hostnameOf(host: string | undefined): string {
|
||||||
|
if (!host) return "";
|
||||||
|
const bracketed = /^\[([^\]]+)\]/.exec(host);
|
||||||
|
return (bracketed ? bracketed[1] : host.split(":")[0])?.toLowerCase() ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Names this machine legitimately answers to on a wildcard bind: every
|
||||||
|
* interface address, plus its own hostname and the `.local` mDNS form people
|
||||||
|
* actually type. Fail closed — a throw yields an empty set, which denies.
|
||||||
|
*/
|
||||||
|
function localNames(): Set<string> {
|
||||||
|
const names = new Set<string>();
|
||||||
|
try {
|
||||||
|
for (const entries of Object.values(networkInterfaces())) {
|
||||||
|
for (const entry of entries ?? []) names.add(entry.address.toLowerCase());
|
||||||
|
}
|
||||||
|
const self = hostname().toLowerCase();
|
||||||
|
if (self !== "") {
|
||||||
|
names.add(self);
|
||||||
|
// `my-box` is reachable as `my-box.local`, and a `my-box.lan.example`
|
||||||
|
// FQDN is reachable by its short form. Register both directions.
|
||||||
|
names.add(`${self}.local`);
|
||||||
|
const short = self.split(".")[0];
|
||||||
|
if (short !== undefined && short !== "") {
|
||||||
|
names.add(short);
|
||||||
|
names.add(`${short}.local`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* fail closed */
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wildcard binds answer on every local name; a specific bind on itself only.
|
||||||
|
*
|
||||||
|
* This is the part that was missing: the previous rule accepted ANY Host once
|
||||||
|
* the env var was set, so a rebinding page could name itself `evil.example.com`
|
||||||
|
* and still be handed the CLI identity.
|
||||||
|
*/
|
||||||
|
function hostMatchesBind(host: string | undefined, bind: string): boolean {
|
||||||
|
const requested = hostnameOf(host);
|
||||||
|
if (requested === "") return false;
|
||||||
|
const bound = bind.toLowerCase();
|
||||||
|
if (requested === bound) return true;
|
||||||
|
return bound === "0.0.0.0" || bound === "::" || bound === "*"
|
||||||
|
? localNames().has(requested)
|
||||||
|
: false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* May a request carrying this `Host` be treated as addressed to this server?
|
||||||
|
*
|
||||||
|
* The server binds loopback by DEFAULT and exposes the LAN only when an
|
||||||
|
* operator sets `HYPERFRAMES_PREVIEW_HOST` (portUtils.ts, F-001). A loopback
|
||||||
|
* `Host` is always fine: whatever reached us came via loopback, and the only
|
||||||
|
* interesting attacker is a rebinding browser page — which the Host check
|
||||||
|
* catches, because a browser cannot forge `Host`.
|
||||||
|
*
|
||||||
|
* For anything else the bind decides:
|
||||||
|
*
|
||||||
|
* - **Unset, or bound to loopback.** No LAN exposure was requested, so the
|
||||||
|
* Host check is a live rebinding mitigation and a non-loopback Host is
|
||||||
|
* refused. Previously ANY non-empty value disabled the check, so even
|
||||||
|
* `HYPERFRAMES_PREVIEW_HOST=127.0.0.1` — which exposes nothing — turned the
|
||||||
|
* loopback service from hostile-Host refusal into accept-everything.
|
||||||
|
* - **Bound to a LAN address.** The operator opted into exposure, so identity
|
||||||
|
* has to reach the LAN name the user browses or the CLI-to-Studio stitch
|
||||||
|
* breaks and Studio mints a second person for the same human. But it is
|
||||||
|
* still checked: the Host must name an address this machine actually
|
||||||
|
* answers on, not any attacker-chosen name a rebinding page supplies.
|
||||||
|
*/
|
||||||
|
export function identityAllowed(host: string | undefined): boolean {
|
||||||
|
if (isLoopbackHost(host)) return true;
|
||||||
|
const bind = (process.env["HYPERFRAMES_PREVIEW_HOST"] ?? "").trim();
|
||||||
|
if (bind === "" || isLoopbackHost(bind)) return false;
|
||||||
|
return hostMatchesBind(host, bind);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A bodiless POST is a simple request, so any page can send one to localhost:
|
||||||
|
* it has to come from this Studio. Both write guards apply this one function,
|
||||||
|
* the CLI server's open-in-desktop route and the studio API's write
|
||||||
|
* middleware, so the two servers cannot drift into different answers.
|
||||||
|
*/
|
||||||
|
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}`;
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ export default defineConfig({
|
|||||||
"helpers/finiteMutation": "src/helpers/finiteMutation.ts",
|
"helpers/finiteMutation": "src/helpers/finiteMutation.ts",
|
||||||
"helpers/sourceMutation": "src/helpers/sourceMutation.ts",
|
"helpers/sourceMutation": "src/helpers/sourceMutation.ts",
|
||||||
"helpers/safePath": "src/helpers/safePath.ts",
|
"helpers/safePath": "src/helpers/safePath.ts",
|
||||||
|
"helpers/requestIdentity": "src/helpers/requestIdentity.ts",
|
||||||
"helpers/hfIdPersist": "src/helpers/hfIdPersist.ts",
|
"helpers/hfIdPersist": "src/helpers/hfIdPersist.ts",
|
||||||
"helpers/encoderOptions": "src/helpers/encoderOptions.ts",
|
"helpers/encoderOptions": "src/helpers/encoderOptions.ts",
|
||||||
"history/index": "src/history/index.ts",
|
"history/index": "src/history/index.ts",
|
||||||
|
|||||||
Reference in New Issue
Block a user