🐛 Check Host and Origin headers in the MCP server (#13117)

* 🐛 Check Host and Origin headers in the MCP server

The MCP endpoint, the REPL server and the plugin WebSocket accepted
requests with any Host and Origin header, so a web page open in the
user's browser could drive a local MCP server: connect as the plugin
and call its tools.

RequestGuard checks both headers against an allowlist and rejects other
requests with HTTP 403, or WebSocket close code 1008. The list comes
from PENPOT_MCP_ALLOWED_HOSTS, where "*" turns the check off. When it
is unset, local mode allows only loopback names and remote mode allows
any host, since remote mode relies on user tokens and has no file
access.

AI-assisted-by: claude-opus-5-5

* 🐛 Keep the Host and Origin check on in single-user remote mode

The default allowlist followed remote mode, so a single-user server with
PENPOT_MCP_REMOTE_MODE=true accepted any Host and Origin. It requires no
user token either, so a web page could still drive it and run code in the
user's Penpot session. The default now follows multi-user mode: single-user
servers allow only loopback names, and multi-user servers, which rely on
user tokens, allow any host. Startup warns when the check is off in
single-user mode.

PENPOT_MCP_ALLOWED_HOSTS entries with a scheme, port or path never matched,
so every request failed with 403. The server now refuses to start and names
the bad entry.

AI-assisted-by: claude-opus-5-5
This commit is contained in:
Alonso Torres 2026-11-17 16:01:49 +01:00 committed by GitHub
parent e6eb8bcd5a
commit eb2c8cf359
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 346 additions and 5 deletions

View File

@ -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.

View File

@ -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` |

View File

@ -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;

View File

@ -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<string, string>): Promise<number> {
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.
*/

View File

@ -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<void> {
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}`);

View File

@ -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");
});

View File

@ -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");

View File

@ -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,

View File

@ -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());
}

View File

@ -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(), "<any>");
});
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(), "<any>");
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}"`)
);
}
});

View File

@ -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<string, string | undefined>, 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 ? "<any>" : 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,
});
};
}