Skip to content

Email for professionals and teams

fix(mcp): accept the forwarded host when APP_URL is configured

Yi-111-a3a0801060332
diff --git a/src/app/mcp/route.ts b/src/app/mcp/route.ts
index a84b49b..6f1ff9a 100644
--- a/src/app/mcp/route.ts
+++ b/src/app/mcp/route.ts
@@ -8,11 +8,14 @@ async function handle(request: Request) {
const origin = request.headers.get("Origin");
if (origin && origin !== url.origin) return new Response("Invalid origin", { status: 403 });
const env = getEnv();
- if (env.APP_URL && url.host !== new URL(env.APP_URL).host) return new Response("Invalid host", { status: 403 });
+ const appUrl = env.APP_URL ? new URL(env.APP_URL) : null;
+ const forwardedHost = (request.headers.get("x-forwarded-host")?.split(",")[0] ?? request.headers.get("Host") ?? "").trim();
+ if (appUrl && forwardedHost !== appUrl.host && url.host !== appUrl.host) return new Response("Invalid host", { status: 403 });
+ const effectiveOrigin = appUrl && forwardedHost === appUrl.host ? appUrl.origin : url.origin;
const principal = await authenticateMcpRequest(env, request);
if (!principal) return new Response("Unauthorized", { status: 401, headers: { "WWW-Authenticate": "Bearer" } });
if (!await allowAgentRequest(env, `mcp:${principal.keyId}`)) return new Response("Rate limit exceeded", { status: 429 });
- const handler = createMailflareMcpHandler(env, principal, url.origin, request.headers.get("Authorization") ?? "");
+ const handler = createMailflareMcpHandler(env, principal, effectiveOrigin, request.headers.get("Authorization") ?? "");
try { return await handler.fetch(request); }
finally { await handler.close(); }
}
diff --git a/tests/mcp-host-validation.test.mjs b/tests/mcp-host-validation.test.mjs
new file mode 100644
index 0000000..ec4c500
--- /dev/null
+++ b/tests/mcp-host-validation.test.mjs
@@ -0,0 +1,65 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import test, { after } from "node:test";
+import { build } from "esbuild";
+
+const project = join(dirname(fileURLToPath(import.meta.url)), "..");
+const temporary = mkdtempSync(join(project, "node_modules", "mcp-host-test-"));
+after(() => { rmSync(temporary, { recursive: true, force: true }); delete globalThis.mcpEnv; delete globalThis.mcpPrincipal; delete globalThis.mcpAllow; delete globalThis.mcpCalls; });
+const mocks = {
+ "@/lib/cloudflare": "export function getEnv(){return globalThis.mcpEnv}",
+ "@/lib/mcp/auth": "export async function authenticateMcpRequest(){return globalThis.mcpPrincipal}",
+ "@/lib/mcp/server": "export function createMailflareMcpHandler(env, principal, origin, authorization){ globalThis.mcpCalls.push({ env, principal, origin, authorization }); return { fetch: () => new Response('ok'), close: async () => {} }; }",
+ "@/lib/agent/rate-limit": "export async function allowAgentRequest(){return globalThis.mcpAllow}",
+};
+await build({ entryPoints: [join(project, "src/app/mcp/route.ts")], outfile: join(temporary, "route.mjs"), bundle: true, platform: "node", format: "esm", packages: "external", alias: { "@": join(project, "src") }, logLevel: "silent", plugins: [{ name: "route-fixtures", setup(builder) {
+ builder.onResolve({ filter: /^@\/lib\/(cloudflare|mcp\/auth|mcp\/server|agent\/rate-limit)$/ }, args => ({ path: args.path, namespace: "mock" }));
+ builder.onLoad({ filter: /.*/, namespace: "mock" }, args => ({ contents: mocks[args.path], loader: "js" }));
+} }] });
+const { POST } = await import(pathToFileURL(join(temporary, "route.mjs")).href);
+
+const request = (url, headers = {}) => new Request(url, { method: "POST", headers });
+const setup = (env) => {
+ globalThis.mcpEnv = env;
+ globalThis.mcpPrincipal = { keyId: "key" };
+ globalThis.mcpAllow = true;
+ globalThis.mcpCalls = [];
+};
+
+test("APP_URL set: a forwarded host matching APP_URL is accepted and gets the public origin", async () => {
+ setup({ APP_URL: "https://mail.example.com" });
+ const response = await POST(request("http://127.0.0.1:3000/mcp", { "x-forwarded-host": "mail.example.com", Host: "mail.example.com" }));
+ assert.equal(response.status, 200);
+ assert.equal(globalThis.mcpCalls.length, 1);
+ assert.equal(globalThis.mcpCalls[0].origin, "https://mail.example.com");
+});
+
+test("APP_URL set: a non-matching host is still rejected", async () => {
+ setup({ APP_URL: "https://mail.example.com" });
+ const response = await POST(request("http://127.0.0.1:3000/mcp", { Host: "evil.example" }));
+ assert.equal(response.status, 403);
+ assert.deepEqual(globalThis.mcpCalls, []);
+});
+
+test("APP_URL set: the reconstructed host still matches", async () => {
+ setup({ APP_URL: "https://mail.example.com" });
+ const response = await POST(request("https://mail.example.com/mcp"));
+ assert.equal(response.status, 200);
+ assert.equal(globalThis.mcpCalls[0].origin, "https://mail.example.com");
+});
+
+test("APP_URL set: the first entry of a forwarded-host list wins", async () => {
+ setup({ APP_URL: "https://mail.example.com" });
+ const response = await POST(request("http://127.0.0.1:3000/mcp", { "x-forwarded-host": "mail.example.com, proxy.internal" }));
+ assert.equal(response.status, 200);
+ assert.equal(globalThis.mcpCalls[0].origin, "https://mail.example.com");
+});
+
+test("APP_URL unset: any host is accepted and the reconstructed origin is used", async () => {
+ setup({});
+ const response = await POST(request("http://127.0.0.1:3000/mcp", { Host: "anything.example" }));
+ assert.equal(response.status, 200);
+ assert.equal(globalThis.mcpCalls[0].origin, "http://127.0.0.1:3000");
+});