fix: answer only the loopback Host on the render and capture file servers (#7853)

The CLI static project server and the producer and engine file servers bind
127.0.0.1, but answered any Host header. They now refuse a request whose Host
is not 127.0.0.1, localhost or [::1] at their own port (or the in-process
origin the CLI hands out when listen is refused), and their responses carry
frame-ancestors 'self' and X-Frame-Options: SAMEORIGIN so another site cannot
frame the served page.
This commit is contained in:
Michael Wang
2026-11-15 18:09:10 +00:00
committed by GitHub
parent 70d60ce037
commit f891a30581
9 changed files with 277 additions and 5 deletions
@@ -0,0 +1,74 @@
import { afterEach, describe, expect, it } from "vitest";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { request, type IncomingHttpHeaders } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { serveStaticProjectHtml, type StaticProjectServer } from "./staticProjectServer.js";
interface Answer {
status: number;
headers: IncomingHttpHeaders;
body: string;
}
function getWithHost(port: number, path: string, host: string): Promise<Answer> {
return new Promise((resolveAnswer, rejectAnswer) => {
const req = request({ hostname: "127.0.0.1", port, path, headers: { host } }, (res) => {
let body = "";
res.setEncoding("utf8");
res.on("data", (chunk: string) => (body += chunk));
res.on("end", () =>
resolveAnswer({ status: res.statusCode ?? 0, headers: res.headers, body }),
);
});
req.on("error", rejectAnswer);
req.end();
});
}
describe("serveStaticProjectHtml Host and framing", () => {
let projectDir: string;
let server: StaticProjectServer;
afterEach(async () => {
await server?.close();
rmSync(projectDir, { recursive: true, force: true });
});
async function serve(): Promise<StaticProjectServer> {
projectDir = mkdtempSync(join(tmpdir(), "hf-static-host-"));
writeFileSync(join(projectDir, "style.css"), "body{}");
server = await serveStaticProjectHtml(projectDir, "<html><body>page</body></html>");
return server;
}
it.each(["/", "/index.html", "/style.css"])(
"refuses %s when Host names another site",
async (path) => {
const { port } = await serve();
for (const host of [`rebound.example:${port}`, "rebound.example", `localhost:${port + 1}`]) {
const answer = await getWithHost(port, path, host);
expect(answer.status).toBe(403);
expect(answer.body).not.toContain("page");
expect(answer.body).not.toContain("body{}");
}
},
);
it.each(["127.0.0.1", "localhost", "[::1]"])("answers its own port on %s", async (name) => {
const { port } = await serve();
const page = await getWithHost(port, "/", `${name}:${port}`);
expect(page.status).toBe(200);
expect(page.body).toContain("page");
const asset = await getWithHost(port, "/style.css", `${name}:${port}`);
expect(asset.status).toBe(200);
expect(asset.body).toBe("body{}");
});
it("forbids another site from framing the page", async () => {
const { port } = await serve();
const page = await getWithHost(port, "/", `127.0.0.1:${port}`);
expect(page.headers["content-security-policy"]).toBe("frame-ancestors 'self'");
expect(page.headers["x-frame-options"]).toBe("SAMEORIGIN");
});
});
+29 -4
View File
@@ -28,7 +28,11 @@ import {
PROXY_VARIANT_CONFIG,
type ProxyVariantRequest,
} from "@hyperframes/studio-server/media-codec-map";
import { listenOnBrowserSafePort } from "@hyperframes/engine";
import {
isOwnLoopbackHost,
listenOnBrowserSafePort,
SAME_ORIGIN_FRAMING_HEADERS,
} from "@hyperframes/engine";
export interface StaticProjectServer {
url: string;
@@ -78,7 +82,11 @@ function socketPair(): [Duplex, Duplex] {
}
/** Hands one request to `server` over an in-memory socket, so its handler (Range, proxies) answers unchanged. */
function answerInProcess(server: Server, request: InProcessRequest): Promise<InProcessResponse> {
function answerInProcess(
server: Server,
host: string,
request: InProcessRequest,
): Promise<InProcessResponse> {
const [client, served] = socketPair();
server.emit("connection", served);
return new Promise((resolveAnswer, rejectAnswer) => {
@@ -86,7 +94,7 @@ function answerInProcess(server: Server, request: InProcessRequest): Promise<InP
{
method: request.method,
path: request.path,
headers: { ...request.headers, connection: "close" },
headers: { ...request.headers, host, connection: "close" },
// No `agent`: Node uses createConnection only when no agent is given.
createConnection: () => client as never,
},
@@ -303,9 +311,23 @@ export async function serveStaticProjectHtml(
)
: html;
let listeningPort = -1;
let inProcessHost: string | undefined;
const answersHost = (host: string | undefined) =>
isOwnLoopbackHost(host, listeningPort) ||
(inProcessHost !== undefined && host === inProcessHost);
// fallow-ignore-next-line complexity
const server = createServer((req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
if (!answersHost(req.headers.host)) {
res.writeHead(403, { "Content-Type": "text/plain" });
res.end("Forbidden");
return;
}
for (const [name, value] of Object.entries(SAME_ORIGIN_FRAMING_HEADERS)) {
res.setHeader(name, value);
}
const url = req.url ?? "/";
if (url === "/" || url === "/index.html") {
res.writeHead(200, { "Content-Type": getMimeType("index.html") });
@@ -371,7 +393,9 @@ export async function serveStaticProjectHtml(
server.removeAllListeners("error");
// A sandbox (e.g. an agent's) may refuse listen(); the browser asks this origin and the process answers.
const url = `http://hyperframes-${++inProcessServers}.localhost/`;
const answer = (request: InProcessRequest) => answerInProcess(server, request);
const host = new URL(url).host;
inProcessHost = host;
const answer = (request: InProcessRequest) => answerInProcess(server, host, request);
inProcessAnswers.set(new URL(url).origin, answer);
return {
url,
@@ -384,6 +408,7 @@ export async function serveStaticProjectHtml(
};
}
listeningPort = port;
return {
url: `http://127.0.0.1:${port}/`,
port,
+6
View File
@@ -387,6 +387,12 @@ export {
settleOnBrowserSafePort,
} from "./utils/browserSafePort.js";
export {
answerOwnLoopbackHostOnly,
isOwnLoopbackHost,
SAME_ORIGIN_FRAMING_HEADERS,
} from "./utils/loopbackOnly.js";
export { readWebGlVendorInfoFromCanvas } from "./utils/readWebGlVendorInfoFromCanvas.js";
export {
@@ -0,0 +1,52 @@
import { afterEach, describe, expect, it } from "vitest";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { request } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createFileServer, type FileServerHandle } from "./fileServer.js";
function statusWithHost(port: number, path: string, host: string): Promise<number> {
return new Promise((resolveStatus, rejectStatus) => {
const req = request({ hostname: "127.0.0.1", port, path, headers: { host } }, (res) => {
res.resume();
res.on("end", () => resolveStatus(res.statusCode ?? 0));
});
req.on("error", rejectStatus);
req.end();
});
}
describe("createFileServer Host and framing", () => {
let projectDir: string;
let server: FileServerHandle | undefined;
afterEach(() => {
server?.close();
server = undefined;
rmSync(projectDir, { recursive: true, force: true });
});
async function serve(): Promise<FileServerHandle> {
projectDir = mkdtempSync(join(tmpdir(), "hf-engine-file-server-host-"));
writeFileSync(join(projectDir, "index.html"), "<!doctype html><html><body>page</body></html>");
writeFileSync(join(projectDir, "style.css"), "body{}");
server = await createFileServer({ projectDir });
return server;
}
it("refuses the page and its assets when Host names another site", async () => {
const { port } = await serve();
for (const path of ["/", "/style.css"]) {
expect(await statusWithHost(port, path, `rebound.example:${port}`)).toBe(403);
expect(await statusWithHost(port, path, `127.0.0.1:${port}`)).toBe(200);
}
});
it("answers its own URL and forbids another site from framing the page", async () => {
const { url } = await serve();
const response = await fetch(`${url}/`);
expect(response.status).toBe(200);
expect(response.headers.get("content-security-policy")).toBe("frame-ancestors 'self'");
expect(response.headers.get("x-frame-options")).toBe("SAMEORIGIN");
});
});
@@ -13,6 +13,7 @@ import { join, extname } from "node:path";
import { injectScriptsIntoHtml } from "@hyperframes/core/compiler";
import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path";
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
import { answerOwnLoopbackHostOnly } from "../utils/loopbackOnly.js";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -120,6 +121,9 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer
const bodyScripts = options.bodyScripts ?? [];
const app = new Hono();
let listeningPort = -1;
const boundToLoopbackOnly = ["127.0.0.1", "localhost", "::1"].includes(hostname);
if (boundToLoopbackOnly) answerOwnLoopbackHostOnly(app, () => listeningPort);
app.get("/*", (c) => {
let requestPath = c.req.path;
@@ -158,6 +162,7 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer
return new Promise((resolve) => {
const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
const actualPort = info.port;
listeningPort = actualPort;
const url = `http://localhost:${actualPort}`;
resolve({
url,
+23
View File
@@ -0,0 +1,23 @@
import type { Hono } from "hono";
/** A page cannot forge Host, so a site that rebinds its own name to 127.0.0.1 is refused here. */
export function isOwnLoopbackHost(host: string | undefined, port: number): boolean {
const name = host?.toLowerCase();
return name === `127.0.0.1:${port}` || name === `localhost:${port}` || name === `[::1]:${port}`;
}
/** The runtime hands an editing port to its parent frame, so another site must not frame these pages. */
export const SAME_ORIGIN_FRAMING_HEADERS = {
"Content-Security-Policy": "frame-ancestors 'self'",
"X-Frame-Options": "SAMEORIGIN",
} as const;
export function answerOwnLoopbackHostOnly(app: Hono, boundPort: () => number): void {
app.use(async function refuseForeignHostAndFraming(c, next) {
if (!isOwnLoopbackHost(c.req.header("host"), boundPort())) return c.text("Forbidden", 403);
await next();
for (const [name, value] of Object.entries(SAME_ORIGIN_FRAMING_HEADERS)) {
c.res.headers.set(name, value);
}
});
}
@@ -26,6 +26,7 @@
"src/services/distributed/renderSpan.integration.test.ts",
"src/services/fileServer.test.ts",
"src/services/fileServer.file-race.test.ts",
"src/services/fileServer.host.test.ts",
"src/services/fileServer.listenError.test.ts",
"src/services/outsideProjectAssets.test.ts",
"src/services/healthWorker.test.ts",
@@ -0,0 +1,83 @@
import { afterEach, describe, expect, it } from "vitest";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { request, type IncomingHttpHeaders } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createFileServer, type FileServerHandle } from "./fileServer.js";
interface Answer {
status: number;
headers: IncomingHttpHeaders;
body: string;
}
function getWithHost(port: number, path: string, host: string): Promise<Answer> {
return new Promise((resolveAnswer, rejectAnswer) => {
const req = request({ hostname: "127.0.0.1", port, path, headers: { host } }, (res) => {
let body = "";
res.setEncoding("utf8");
res.on("data", (chunk: string) => (body += chunk));
res.on("end", () =>
resolveAnswer({ status: res.statusCode ?? 0, headers: res.headers, body }),
);
});
req.on("error", rejectAnswer);
req.end();
});
}
describe("createFileServer Host and framing", () => {
let projectDir: string;
let server: FileServerHandle | undefined;
afterEach(() => {
server?.close();
server = undefined;
rmSync(projectDir, { recursive: true, force: true });
});
async function serve(): Promise<FileServerHandle> {
projectDir = mkdtempSync(join(tmpdir(), "hf-file-server-host-"));
writeFileSync(join(projectDir, "index.html"), "<!doctype html><html><body>page</body></html>");
writeFileSync(join(projectDir, "style.css"), "body{}");
server = await createFileServer({ projectDir, preHeadScripts: [], headScripts: [] });
return server;
}
it.each(["/", "/index.html", "/style.css"])(
"refuses %s when Host names another site",
async (path) => {
const { port } = await serve();
for (const host of [`rebound.example:${port}`, "rebound.example", `localhost:${port + 1}`]) {
const answer = await getWithHost(port, path, host);
expect(answer.status).toBe(403);
expect(answer.body).not.toContain("page");
expect(answer.body).not.toContain("body{}");
}
},
);
it.each(["127.0.0.1", "localhost", "[::1]"])("answers its own port on %s", async (name) => {
const { port } = await serve();
const page = await getWithHost(port, "/index.html", `${name}:${port}`);
expect(page.status).toBe(200);
expect(page.body).toContain("page");
const asset = await getWithHost(port, "/style.css", `${name}:${port}`);
expect(asset.status).toBe(200);
expect(asset.body).toBe("body{}");
});
it("answers the URL it hands the capture browser", async () => {
const { url } = await serve();
const response = await fetch(`${url}/index.html`);
expect(response.status).toBe(200);
expect(await response.text()).toContain("page");
});
it("forbids another site from framing the page", async () => {
const { url } = await serve();
const response = await fetch(`${url}/`);
expect(response.headers.get("content-security-policy")).toBe("frame-ancestors 'self'");
expect(response.headers.get("x-frame-options")).toBe("SAMEORIGIN");
});
});
+4 -1
View File
@@ -10,7 +10,7 @@
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { settleOnBrowserSafePort } from "@hyperframes/engine";
import { answerOwnLoopbackHostOnly, settleOnBrowserSafePort } from "@hyperframes/engine";
import type { IncomingMessage } from "node:http";
import {
existsSync,
@@ -817,11 +817,13 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer
const app = new Hono();
const warnLeftOut = (line: string) => console.warn(`[FileServer] ${line}`);
let listeningPort = -1;
app.use(async function loadEachFileOnlyAsItsNamedType(c, next) {
await next();
c.res.headers.set("X-Content-Type-Options", "nosniff");
});
answerOwnLoopbackHostOnly(app, () => listeningPort);
app.get("/*", async (c) => {
let requestPath = c.req.path;
@@ -971,6 +973,7 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer
const bound =
port === 0 ? settleOnBrowserSafePort(server, "127.0.0.1") : Promise.resolve(info.port);
bound.then((boundPort) => {
listeningPort = boundPort;
resolve({
url: `http://localhost:${boundPort}`,
port: boundPort,