diff --git a/.serena/memories/mcp/core.md b/.serena/memories/mcp/core.md index 8ca829c32f..d62dd9d840 100644 --- a/.serena/memories/mcp/core.md +++ b/.serena/memories/mcp/core.md @@ -120,6 +120,14 @@ From the `mcp/` directory, run - Authorization/discovery URLs, self-contained client IDs, consent and PKCE/code binding, backend Redis state, deployment wiring, and compatibility limits: `mem:mcp/oauth`. +## Host and Origin allowlist (`RequestGuard`) + +- `RequestGuard` checks `Host` and `Origin` (hostname only, port ignored) on `/mcp`, the REPL (Express middleware, 403) and the plugin WebSocket (close `1008` before any message is read). It stops web pages on the user's machine from driving a local server (DNS rebinding, cross-site WebSocket). +- Allowlist: `PENPOT_MCP_ALLOWED_HOSTS` (`*` turns the check off); unset → loopback only in single-user mode (local or remote: no other barrier, `execute_code` still runs in the user's session), any host in multi-user mode (relies on user tokens; behind nginx `/mcp/ws` the server sees `Host: penpot-mcp:4402`). A missing `Origin` passes (non-browser clients). +- Entries must be `*`, a hostname or a bracketed IPv6 address; one with a scheme, port or path makes `fromEnvironment` throw, so the server does not start. Startup logs a `warn` when the check is off in single-user mode. +- The plugin iframe has `allow-same-origin`, so its WebSocket carries the real plugin origin (`http://localhost:4400` locally, the Penpot origin when integrated). +- Test mocks of `PenpotMcpServer` passed to `PluginBridge` must provide `requestGuard`. + ## Backend tools (`submit_feedback`) - Tools that call the Penpot backend directly (not through the plugin) register only when `PENPOT_MCP_BACKEND_URI` is nonblank (`PenpotMcpServer.initTools`). Currently only `SubmitFeedbackTool`. @@ -140,7 +148,7 @@ For parallel devenvs, prefer same-origin MCP routing: each Penpot instance shoul ## Plugin reconnect policy - The plugin treats WebSocket close code `1008` (policy violation) as terminal: it stops auto-reconnecting and stays disconnected until the user explicitly reconnects. Other close codes keep the capped-backoff retry. The decision lives in `ReconnectPolicy.ts` (`shouldReconnectAfterClose`), kept as a pure module so it is unit-testable without DOM/CSS. -- The MCP server emits `1008` for a missing `userToken` in multi-user mode, for missing/invalid connection metadata, and to close a connection displaced by a newer one with the same user and session ID. +- The MCP server emits `1008` for a `Host`/`Origin` outside the `RequestGuard` allowlist, for a missing `userToken` in multi-user mode, for missing/invalid connection metadata, and to close a connection displaced by a newer one with the same user and session ID. - Session IDs are deterministic per tab and file, so a reconnect reuses its ID while the old socket may be half-open: the newest connection wins (`PluginBridge.displaceConnection`). Across instances, each new connection publishes a session claim on a per-user Redis channel; an instance displaces its local connection only on a foreign claim that arrives after its own claim (channel order, no clocks). Discovery deduplicates by session ID. - A tab rejected with `1008` never reaches `connected`, so the frontend's 60s reconnect watcher (`start-reconnect-watcher` in `app.main.data.workspace.mcp`, started only on `connected`) does not engage; recovery is manual via the MCP menu. diff --git a/mcp/README.md b/mcp/README.md index 2f1636d24a..5be56120b0 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -295,7 +295,8 @@ The Penpot MCP server can be configured using environment variables. | `PENPOT_MCP_REPL_PORT` | Port for the REPL server (development/debugging) | `4403` | | `PENPOT_MCP_REPL_HOST` | Address on which the REPL server listens (binds to) | `localhost` | | `PENPOT_MCP_REPL_ENABLE` | Explicitly enable/disable the REPL server. Set to `true` to enable. When unset, defaults to the value of `PENPOT_MCP_DEVENV`. The REPL server never starts in multi-user mode. | (unset) | -| `PENPOT_MCP_REMOTE_MODE` | Enable remote mode (disables file system access). Set to `true` to enable. | `false` | +| `PENPOT_MCP_REMOTE_MODE` | Enable remote mode (disables file system access). Set to `true` to enable. In single-user mode it does not open the server to other hosts; see `PENPOT_MCP_ALLOWED_HOSTS`. | `false` | +| `PENPOT_MCP_ALLOWED_HOSTS` | Comma-separated hostnames (no ports; IPv6 in brackets) that requests to the MCP endpoint, the plugin WebSocket and the REPL server may carry in their `Host` and `Origin` headers. Requests with any other hostname are rejected, which stops web pages from driving the server. Entries with a scheme, port or path stop the server from starting. When unset, single-user mode allows only `localhost`, `127.0.0.1` and `[::1]`, with or without remote mode, and multi-user mode allows any hostname. Set it when clients, the plugin or a proxy reach a single-user server under another name. Set it to `*` to turn the check off (not recommended in single-user mode: any web page you open can then drive the server). | (unset) | | `PENPOT_MCP_DEVENV` | Enable Penpot development environment tools in local single-user mode. Set to `true` to enable. | `false` | | `PENPOT_MCP_TOOL_TIMEOUT_S` | Timeout, in seconds, for tool calls dispatched to the Penpot plugin | `120` | | `PENPOT_MCP_MAX_BODY_SIZE` | Maximum size of a JSON request body accepted by the MCP endpoint, in any format supported by Express (e.g. `10mb`) | `10mb` | diff --git a/mcp/packages/plugin/src/ReconnectPolicy.ts b/mcp/packages/plugin/src/ReconnectPolicy.ts index 9d2947894d..5767977906 100644 --- a/mcp/packages/plugin/src/ReconnectPolicy.ts +++ b/mcp/packages/plugin/src/ReconnectPolicy.ts @@ -1,8 +1,9 @@ /** * WebSocket close code the MCP server uses for policy violations. * - * The server rejects a second plugin connection for the same user token, and - * connections missing a token in multi-user mode, with this code. + * The server rejects a second plugin connection for the same user token, + * connections missing a token in multi-user mode, and connections whose `Host` + * or `Origin` is not allowed, with this code. */ export const WS_CLOSE_POLICY_VIOLATION = 1008; diff --git a/mcp/packages/server/src/PenpotMcpServer.http.test.ts b/mcp/packages/server/src/PenpotMcpServer.http.test.ts index d5534de879..0698bbe1e9 100644 --- a/mcp/packages/server/src/PenpotMcpServer.http.test.ts +++ b/mcp/packages/server/src/PenpotMcpServer.http.test.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { request as httpRequest } from "node:http"; import { afterEach, beforeEach, test } from "node:test"; import { type CallToolResult, Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import { PenpotMcpServer } from "./PenpotMcpServer"; @@ -173,6 +174,72 @@ test("OAuth challenges missing credentials and accepts bearer and query tokens", } }); +/** + * Posts an MCP initialize request with the given extra headers and returns the response status. + * + * Uses `node:http`, since `fetch` does not let the caller set the `Host` header. + */ +function initializeStatus(headers: Record): Promise { + const body = JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "guard-test", version: "1" }, + }, + }); + return new Promise((resolve, reject) => { + const req = httpRequest( + `${baseUrl}/mcp`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + ...headers, + }, + }, + (res) => { + res.resume(); + resolve(res.statusCode!); + } + ); + req.on("error", reject); + req.end(body); + }); +} + +for (const remoteMode of [undefined, "true"]) { + test(`single-user mode rejects requests from foreign hosts and origins (remote mode: ${remoteMode})`, async () => { + await server.stop(); + if (remoteMode === undefined) { + delete process.env.PENPOT_MCP_REMOTE_MODE; + } else { + process.env.PENPOT_MCP_REMOTE_MODE = remoteMode; + } + delete process.env.PENPOT_MCP_ALLOWED_HOSTS; + server = new PenpotMcpServer(false); + await server.start(); + + assert.equal(await initializeStatus({ Host: `attacker.example:${server.port}` }), 403); + assert.equal( + await initializeStatus({ Host: `localhost:${server.port}`, Origin: "https://attacker.example" }), + 403 + ); + assert.equal(await initializeStatus({ Host: `localhost:${server.port}` }), 200); + assert.equal( + await initializeStatus({ Host: `127.0.0.1:${server.port}`, Origin: "http://localhost:4400" }), + 200 + ); + }); +} + +test("multi-user mode accepts requests from any host by default", async () => { + assert.equal(await initializeStatus({ Host: `penpot.example.com`, Origin: "https://penpot.example.com" }), 200); +}); + /** * Makes the plugin bridge answer each dispatched task at once with the given responses, in order. */ diff --git a/mcp/packages/server/src/PenpotMcpServer.ts b/mcp/packages/server/src/PenpotMcpServer.ts index 56f7ac5b2c..d9a1668f89 100644 --- a/mcp/packages/server/src/PenpotMcpServer.ts +++ b/mcp/packages/server/src/PenpotMcpServer.ts @@ -25,6 +25,7 @@ import { NreplClient } from "./NreplClient"; import { ReplServer } from "./ReplServer"; import { ApiDocs } from "./ApiDocs"; import { McpAuthentication } from "./McpAuthentication"; +import { RequestGuard } from "./RequestGuard"; /** * Session context for request-scoped data. @@ -115,6 +116,11 @@ export class PenpotMcpServer { private httpServer?: HttpServer; private readonly mcpHandler: McpHttpHandler; private readonly authentication: McpAuthentication; + + /** + * Check of the `Host` and `Origin` headers of HTTP and plugin WebSocket requests. + */ + public readonly requestGuard: RequestGuard; public readonly pluginBridge: PluginBridge; private readonly replServer: ReplServer | null; private apiDocs: ApiDocs; @@ -167,6 +173,8 @@ export class PenpotMcpServer { this.maxBodySize = process.env.PENPOT_MCP_MAX_BODY_SIZE ?? "10mb"; const toolTimeoutSecs = parseInt(process.env.PENPOT_MCP_TOOL_TIMEOUT_S ?? "120", 10); + this.requestGuard = RequestGuard.fromEnvironment(process.env, this.isMultiUserMode()); + this.configLoader = new ConfigurationLoader(process.cwd()); this.apiDocs = new ApiDocs(); @@ -190,7 +198,7 @@ export class PenpotMcpServer { this.pluginBridge = new PluginBridge(this, this.webSocketPort, toolTimeoutSecs, this.redisBridge); if (shouldStartReplServer(PenpotMcpServer.isReplEnabled(process.env), this.isMultiUserMode())) { - this.replServer = new ReplServer(this.pluginBridge, this.replPort, this.replHost); + this.replServer = new ReplServer(this.pluginBridge, this.requestGuard, this.replPort, this.replHost); } else { this.replServer = null; } @@ -332,6 +340,7 @@ export class PenpotMcpServer { async start(): Promise { const { default: express } = await import("express"); this.app = express(); + this.app.use(this.requestGuard.httpMiddleware); this.app.use(express.json({ limit: this.maxBodySize })); this.setupHttpEndpoints(); @@ -345,6 +354,13 @@ export class PenpotMcpServer { ); this.logger.info(`Remote mode: ${this.isRemoteMode()}`); this.logger.info(`DevEnv mode: ${this.isDevEnv()}`); + this.logger.info(`Allowed hosts and origins: ${this.requestGuard.describe()}`); + if (this.requestGuard.allowsAny() && !this.isMultiUserMode()) { + this.logger.warn( + "Host and Origin check is off and no user token is required: " + + "any web page opened in a browser that reaches this server can drive it" + ); + } this.logger.info(`Modern Streamable HTTP endpoint: http://${this.host}:${this.port}/mcp`); this.logger.info(`WebSocket server URL: ws://${this.host}:${this.webSocketPort}`); diff --git a/mcp/packages/server/src/PluginBridge.sessions.test.ts b/mcp/packages/server/src/PluginBridge.sessions.test.ts index 3e676725f2..428e3d736f 100644 --- a/mcp/packages/server/src/PluginBridge.sessions.test.ts +++ b/mcp/packages/server/src/PluginBridge.sessions.test.ts @@ -5,6 +5,7 @@ import { WebSocket } from "ws"; import { HEARTBEAT_REQUEST_INTERVAL_MS, PluginBridge } from "./PluginBridge"; import { PluginTask } from "./PluginTask"; import type { PenpotMcpServer } from "./PenpotMcpServer"; +import { RequestGuard } from "./RequestGuard"; let bridge: PluginBridge; let port = 17_600; @@ -22,6 +23,7 @@ beforeEach(() => { host: "127.0.0.1", isMultiUserMode: () => multiUser, getSessionContext: () => ({ userToken }), + requestGuard: RequestGuard.allowing(["localhost", "127.0.0.1"]), } as PenpotMcpServer, port, 1 @@ -203,3 +205,34 @@ test("a task fails at once when its plugin connection closes before answering", // well within the 1s task timeout of these tests assert.ok(Date.now() - started < 500); }); + +test("closes a WebSocket opened by a page on a foreign site with a policy violation", async () => { + const socket = new WebSocket(`ws://127.0.0.1:${port}?userToken=alice`, { + headers: { Origin: "http://attacker.example" }, + }); + sockets.push(socket); + const [code] = await once(socket, "close", { signal: AbortSignal.timeout(1500) }); + assert.equal(code, 1008); + assert.equal(bridge.getUserConnections("alice"), undefined); +}); + +test("closes a WebSocket that reaches the server under a foreign host name", async () => { + const socket = new WebSocket(`ws://127.0.0.1:${port}?userToken=alice`, { + headers: { Host: `attacker.example:${port}` }, + }); + sockets.push(socket); + const [code] = await once(socket, "close", { signal: AbortSignal.timeout(1500) }); + assert.equal(code, 1008); +}); + +test("accepts a WebSocket opened by a plugin page served from an allowed host", async () => { + const socket = new WebSocket(`ws://127.0.0.1:${port}?userToken=alice`, { + headers: { Origin: "http://localhost:4400" }, + }); + sockets.push(socket); + await once(socket, "open"); + const initialized = once(socket, "message", { signal: AbortSignal.timeout(1500) }); + socket.send(JSON.stringify({ type: "initialize", session: { sessionId: "tab", fileId: null, fileName: null } })); + const [message] = await initialized; + assert.equal(JSON.parse(message.toString()).type, "initialized"); +}); diff --git a/mcp/packages/server/src/PluginBridge.ts b/mcp/packages/server/src/PluginBridge.ts index 8bf426e9a8..50fe62fa78 100644 --- a/mcp/packages/server/src/PluginBridge.ts +++ b/mcp/packages/server/src/PluginBridge.ts @@ -127,6 +127,14 @@ export class PluginBridge implements TaskDispatchHost { */ private setupWebSocketHandlers(): void { this.wsServer.on("connection", (ws: WebSocket, request: http.IncomingMessage) => { + // reject pages on foreign sites before reading any message + const guardResult = this.mcpServer.requestGuard.check(request.headers); + if (!guardResult.isAllowed) { + this.logger.warn("Rejected WebSocket connection: %s", guardResult.reason); + ws.close(1008, "Origin or host not allowed; see PENPOT_MCP_ALLOWED_HOSTS"); + return; + } + // extract userToken from query parameters const url = new URL(request.url!, `ws://${request.headers.host}`); const userToken = url.searchParams.get("userToken"); diff --git a/mcp/packages/server/src/RedisBridge.test.ts b/mcp/packages/server/src/RedisBridge.test.ts index c64650ef1e..37daac69a6 100644 --- a/mcp/packages/server/src/RedisBridge.test.ts +++ b/mcp/packages/server/src/RedisBridge.test.ts @@ -5,6 +5,7 @@ import Redis, { type Command } from "ioredis"; import { WebSocket } from "ws"; import { RedisBridge } from "./RedisBridge"; import { PluginBridge } from "./PluginBridge"; +import { RequestGuard } from "./RequestGuard"; import { PluginTask } from "./PluginTask"; import type { PenpotMcpServer } from "./PenpotMcpServer"; import type { PenpotSession } from "@penpot/mcp-common"; @@ -163,6 +164,7 @@ function instance(t: TestContext) { host: "127.0.0.1", isMultiUserMode: () => true, getSessionContext: () => ({ userToken: "alice" }), + requestGuard: RequestGuard.allowingAny(), } as PenpotMcpServer, wsPort, 0.1, diff --git a/mcp/packages/server/src/ReplServer.ts b/mcp/packages/server/src/ReplServer.ts index 1894ade79a..51db327c81 100644 --- a/mcp/packages/server/src/ReplServer.ts +++ b/mcp/packages/server/src/ReplServer.ts @@ -4,6 +4,7 @@ import { fileURLToPath } from "url"; import { PluginBridge } from "./PluginBridge"; import { ExecuteCodePluginTask } from "./tasks/ExecuteCodePluginTask"; import { createLogger } from "./logger"; +import type { RequestGuard } from "./RequestGuard"; /** * Web-based REPL server for executing code through the PluginBridge. @@ -22,6 +23,7 @@ export class ReplServer { constructor( private readonly pluginBridge: PluginBridge, + private readonly requestGuard: RequestGuard, port: number = 4403, host: string = "localhost" ) { @@ -36,6 +38,7 @@ export class ReplServer { * Sets up Express middleware for request parsing and static content. */ private setupMiddleware(): void { + this.app.use(this.requestGuard.httpMiddleware); this.app.use(express.json()); } diff --git a/mcp/packages/server/src/RequestGuard.test.ts b/mcp/packages/server/src/RequestGuard.test.ts new file mode 100644 index 0000000000..ea60180b0b --- /dev/null +++ b/mcp/packages/server/src/RequestGuard.test.ts @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { RequestGuard } from "./RequestGuard"; + +test("single-user mode allows only loopback hosts and origins by default", () => { + const guard = RequestGuard.fromEnvironment({}, false); + assert.equal(guard.allowsAny(), false); + assert.equal(guard.check({ host: "localhost:4401" }).isAllowed, true); + assert.equal(guard.check({ host: "127.0.0.1:4401", origin: "http://localhost:4400" }).isAllowed, true); + assert.equal(guard.check({ host: "[::1]:4401" }).isAllowed, true); + assert.equal(guard.check({ host: "attacker.example:4401" }).isAllowed, false); + assert.equal(guard.check({ host: "localhost:4401", origin: "https://attacker.example" }).isAllowed, false); + assert.equal(guard.check({ host: "localhost:4401", origin: "null" }).isAllowed, false); + assert.equal(guard.check({}).isAllowed, false); +}); + +test("multi-user mode allows any host and origin by default", () => { + const guard = RequestGuard.fromEnvironment({ PENPOT_MCP_ALLOWED_HOSTS: " , " }, true); + assert.equal(guard.allowsAny(), true); + assert.equal(guard.check({ host: "penpot.example.com", origin: "https://other.example" }).isAllowed, true); + assert.equal(guard.describe(), ""); +}); + +test("the configured hosts replace the default in either mode", () => { + for (const isMultiUserMode of [false, true]) { + const guard = RequestGuard.fromEnvironment( + { PENPOT_MCP_ALLOWED_HOSTS: " Penpot.Example.com, localhost " }, + isMultiUserMode + ); + assert.equal(guard.describe(), "penpot.example.com, localhost"); + assert.equal(guard.check({ host: "penpot.example.com", origin: "https://penpot.example.com" }).isAllowed, true); + assert.equal(guard.check({ host: "localhost:4401" }).isAllowed, true); + assert.equal(guard.check({ host: "127.0.0.1:4401" }).isAllowed, false); + assert.equal(guard.check({ host: "penpot.example.com", origin: "https://attacker.example" }).isAllowed, false); + } +}); + +test("the wildcard turns the check off in single-user mode", () => { + const guard = RequestGuard.fromEnvironment({ PENPOT_MCP_ALLOWED_HOSTS: "localhost, *" }, false); + assert.equal(guard.describe(), ""); + assert.equal(guard.check({ host: "attacker.example", origin: "https://attacker.example" }).isAllowed, true); +}); + +test("hostnames, bracketed IPv6 addresses and the wildcard are valid entries", () => { + const guard = RequestGuard.fromEnvironment( + { PENPOT_MCP_ALLOWED_HOSTS: "localhost, 127.0.0.1, [::1], penpot-mcp, penpot_mcp, penpot.example.com" }, + false + ); + assert.equal(guard.check({ host: "penpot-mcp:4402" }).isAllowed, true); + assert.equal(guard.check({ host: "[::1]:4401" }).isAllowed, true); +}); + +test("entries with a scheme, port or path stop the server from starting", () => { + for (const entry of ["http://localhost", "localhost:4401", "localhost/", "[::1]:4401", "local host"]) { + assert.throws( + () => RequestGuard.fromEnvironment({ PENPOT_MCP_ALLOWED_HOSTS: `localhost, ${entry}` }, false), + (error: Error) => error.message.includes(`"${entry}"`) + ); + } +}); diff --git a/mcp/packages/server/src/RequestGuard.ts b/mcp/packages/server/src/RequestGuard.ts new file mode 100644 index 0000000000..d4a17c0adc --- /dev/null +++ b/mcp/packages/server/src/RequestGuard.ts @@ -0,0 +1,142 @@ +import type { IncomingHttpHeaders } from "node:http"; +import type { NextFunction, Request, Response } from "express"; +import { localhostAllowedHostnames, validateHostHeader, validateOriginHeader } from "@modelcontextprotocol/server"; +import { createLogger } from "./logger"; + +/** + * Outcome of checking the headers of one request against a {@link RequestGuard}. + */ +export class RequestGuardResult { + /** + * @param isAllowed whether the request may proceed + * @param reason why the request was rejected; empty when it is allowed + */ + constructor( + public readonly isAllowed: boolean, + public readonly reason: string = "" + ) {} +} + +/** + * Allowlist check of the `Host` and `Origin` headers of requests reaching the MCP server. + * + * Any web page the user opens can send requests to servers on the user's machine. The `Host` + * check stops DNS rebinding, where a page on a foreign domain whose name resolves to the + * loopback address reaches the server as a same-origin request. The `Origin` check stops + * pages on foreign sites from sending requests or opening the plugin WebSocket directly. + * Both headers are compared by hostname only, ignoring the port. A request without an + * `Origin` header comes from a client other than a browser and passes the `Origin` check. + * + * The allowed hostnames come from `PENPOT_MCP_ALLOWED_HOSTS`, where `*` allows any hostname. + * When it is unset, single-user mode allows only loopback hostnames, in local and remote mode + * alike, since it has no other barrier. Multi-user mode allows any hostname, since its server + * is reached under names it cannot know and relies on user tokens instead. + */ +export class RequestGuard { + /** + * Pattern of a valid allowlist entry: a hostname or a bracketed IPv6 address, without scheme or port. + */ + private static readonly HOSTNAME_PATTERN = /^(?:[a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])$/; + + private readonly logger = createLogger("RequestGuard"); + + /** + * @param allowedHostnames the hostnames allowed in `Host` and `Origin`, or null to allow any + */ + private constructor(private readonly allowedHostnames: string[] | null) {} + + /** + * Creates the guard configured by `PENPOT_MCP_ALLOWED_HOSTS`. + * + * The variable holds a comma-separated list of hostnames, without ports; IPv6 addresses + * go in brackets (e.g. `[::1]`). The entry `*` allows any hostname, which turns the check off. + * + * @param env the environment variables + * @param isMultiUserMode whether the server runs in multi-user mode + * @throws Error if an entry is neither `*` nor a hostname, e.g. when it has a scheme or port + */ + public static fromEnvironment(env: Record, isMultiUserMode: boolean): RequestGuard { + const configured = (env.PENPOT_MCP_ALLOWED_HOSTS ?? "") + .split(",") + .map((hostname) => hostname.trim().toLowerCase()) + .filter((hostname) => hostname.length > 0); + for (const hostname of configured) { + if (hostname !== "*" && !RequestGuard.HOSTNAME_PATTERN.test(hostname)) { + throw new Error( + `PENPOT_MCP_ALLOWED_HOSTS entry "${hostname}" is not a hostname; ` + + "give hostnames without scheme, port or path (e.g. localhost, [::1])" + ); + } + } + if (configured.includes("*")) { + return RequestGuard.allowingAny(); + } + if (configured.length > 0) { + return new RequestGuard(configured); + } + return isMultiUserMode ? RequestGuard.allowingAny() : RequestGuard.allowing(localhostAllowedHostnames()); + } + + /** + * Creates a guard that allows only the given hostnames. + */ + public static allowing(hostnames: string[]): RequestGuard { + return new RequestGuard([...hostnames]); + } + + /** + * Creates a guard that allows every request. + */ + public static allowingAny(): RequestGuard { + return new RequestGuard(null); + } + + /** + * Indicates whether the guard allows every request. + */ + public allowsAny(): boolean { + return this.allowedHostnames === null; + } + + /** + * Describes the allowed hostnames, for logging. + */ + public describe(): string { + return this.allowedHostnames === null ? "" : this.allowedHostnames.join(", "); + } + + /** + * Checks the `Host` and `Origin` headers of a request. + */ + public check(headers: IncomingHttpHeaders): RequestGuardResult { + if (this.allowedHostnames === null) { + return new RequestGuardResult(true); + } + const host = validateHostHeader(headers.host, this.allowedHostnames); + if (!host.ok) { + return new RequestGuardResult(false, host.message); + } + const origin = validateOriginHeader(headers.origin, this.allowedHostnames); + if (!origin.ok) { + return new RequestGuardResult(false, origin.message); + } + return new RequestGuardResult(true); + } + + /** + * Express middleware that answers a rejected request with HTTP 403. + */ + public readonly httpMiddleware = (req: Request, res: Response, next: NextFunction): void => { + const result = this.check(req.headers); + if (result.isAllowed) { + next(); + return; + } + this.logger.warn("Rejected HTTP request to %s: %s", req.path, result.reason); + res.status(403).json({ + jsonrpc: "2.0", + error: { code: -32000, message: `${result.reason}; see PENPOT_MCP_ALLOWED_HOSTS` }, + id: null, + }); + }; +}