Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
Harden serve /mcp against DNS rebinding: apply the web handler's Host/Origin checks
anirudhkumar-nanonetsbb8afc858af3
diff --git a/src/serve.ts b/src/serve.tsindex 8b1b60a1..46afdd31 100644--- a/src/serve.ts+++ b/src/serve.ts@@ -140,6 +140,11 @@ export async function startServe(opts: ServeOptions = {}): Promise<RunningServerconst transports: Record<string, StreamableHTTPServerTransport> = {};async function handleMcp(req: IncomingMessage, res: ServerResponse): Promise<void> {+ // Same browser hardening as the web handler: on a loopback bind, reject+ // foreign Host/Origin headers (DNS-rebinding / CSRF) before doing anything.+ // /mcp routes around app.handler, so this guard must be applied explicitly.+ if (app.rejectForeignRequest(req, res)) return;+// Gate /mcp with the same bearer token the web /api uses when exposed.if (app.exposed && !app.isAuthorized(req)) {res.writeHead(401, { "content-type": "application/json" });diff --git a/src/web.ts b/src/web.tsindex 5c509585..8c677718 100644--- a/src/web.ts+++ b/src/web.ts@@ -104,6 +104,12 @@ export interface WebApp {handler: (req: IncomingMessage, res: ServerResponse) => void;/** True if a presented bearer token authorizes /api access (always true when unguarded). */isAuthorized: (req: IncomingMessage) => boolean;+ /**+ * Browser-facing hardening (DNS-rebinding / CSRF): returns true and writes an+ * error response if the request should be rejected. Callers that route around+ * {@link WebApp.handler} (e.g. `serve`'s `/mcp`) must run this first.+ */+ rejectForeignRequest: (req: IncomingMessage, res: ServerResponse) => boolean;/** Whether the server is exposed beyond loopback (a token is then required). */exposed: boolean;/** The active access token, if any. */@@ -437,6 +443,7 @@ export function createWebApp(opts: WebAppOptions): WebApp {return {handler,isAuthorized,+ rejectForeignRequest,exposed: EXPOSED,webToken: WEB_TOKEN,sharePath: SHARE_PATH,diff --git a/test/serve.test.ts b/test/serve.test.tsindex a5024f04..b26fff80 100644--- a/test/serve.test.ts+++ b/test/serve.test.ts@@ -5,6 +5,7 @@*/import { test } from "node:test";import assert from "node:assert/strict";+import { request } from "node:http";import { ContextGraphEngine } from "../src/index.js";import { startServe } from "../src/serve.js";import { Client } from "@modelcontextprotocol/sdk/client/index.js";@@ -72,3 +73,36 @@ test("serve requires no token on loopback and 404s unknown paths", async () => {await server.close();}});++test("serve rejects /mcp requests with a foreign Host header (DNS-rebinding defense)", async () => {+ const engine = new ContextGraphEngine({ dbPath: ":memory:", ...fakeProviders() });+ const server = await startServe({ engine, host: "127.0.0.1", port: 0, watch: false });+ try {+ // fetch() forbids setting Host, so drive a raw request with a spoofed host —+ // the shape a DNS-rebinding attack takes (browser rebinds evil.com → 127.0.0.1).+ const status = await new Promise<number>((resolve, reject) => {+ const req = request(+ {+ host: "127.0.0.1",+ port: server.port,+ path: "/mcp",+ method: "POST",+ headers: {+ host: "evil.example.com",+ "content-type": "application/json",+ accept: "application/json, text/event-stream",+ },+ },+ (res) => {+ res.resume();+ resolve(res.statusCode ?? 0);+ },+ );+ req.on("error", reject);+ req.end(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }));+ });+ assert.equal(status, 403, "a foreign Host header is rejected on /mcp, not just /api");+ } finally {+ await server.close();+ }+});