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
74 changes: 74 additions & 0 deletions packages/cli/src/utils/staticProjectServer.host.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
33 changes: 29 additions & 4 deletions packages/cli/src/utils/staticProjectServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -78,15 +82,19 @@ 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) => {
const req = httpRequest(
{
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,
},
Expand Down Expand Up @@ -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") });
Expand Down Expand Up @@ -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,
Expand All @@ -384,6 +408,7 @@ export async function serveStaticProjectHtml(
};
}

listeningPort = port;
return {
url: `http://127.0.0.1:${port}/`,
port,
Expand Down
6 changes: 6 additions & 0 deletions packages/engine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
52 changes: 52 additions & 0 deletions packages/engine/src/services/fileServer.host.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
5 changes: 5 additions & 0 deletions packages/engine/src/services/fileServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { join, extname } from "node:path";
import { injectScriptsIntoHtml } from "@hyperframes/core/compiler";
import { isPrivateFileUnder, isVcsOrSecretPath } 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",
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
23 changes: 23 additions & 0 deletions packages/engine/src/utils/loopbackOnly.ts
Original file line number Diff line number Diff line change
@@ -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);
}
});
}
1 change: 1 addition & 0 deletions packages/producer/scripts/integration-tests.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
83 changes: 83 additions & 0 deletions packages/producer/src/services/fileServer.host.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
5 changes: 4 additions & 1 deletion packages/producer/src/services/fileServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
Loading