diff --git a/src/middleware.js b/src/middleware.js index e4f72bca8..d38a2c9b6 100644 --- a/src/middleware.js +++ b/src/middleware.js @@ -4,13 +4,6 @@ import { NextResponse } from "next/server"; const authEnabled = Boolean(process.env.HOMEPAGE_AUTH_ENABLED); const authSecret = process.env.NEXTAUTH_SECRET || process.env.HOMEPAGE_AUTH_SECRET; -function hasMcpToken(req) { - const token = process.env.HOMEPAGE_MCP_TOKEN; - if (!token) return false; - - return req.headers.get("authorization") === `Bearer ${token}` || req.headers.get("x-homepage-mcp-token") === token; -} - export async function middleware(req) { // Check the Host header, if HOMEPAGE_ALLOWED_HOSTS is set const host = req.headers.get("host"); @@ -27,8 +20,10 @@ export async function middleware(req) { return NextResponse.json({ error: "Host validation failed. See logs for more details." }, { status: 400 }); } - if (authEnabled && !new URL(req.url).pathname.startsWith("/api/healthcheck")) { - if (new URL(req.url).pathname === "/api/mcp" && hasMcpToken(req)) { + const pathname = new URL(req.url).pathname; + if (authEnabled && !pathname.startsWith("/api/healthcheck")) { + // The MCP API handler authorizes both bearer tokens and Homepage sessions. + if (pathname === "/api/mcp") { return NextResponse.next(); } diff --git a/src/middleware.test.js b/src/middleware.test.js index 8d08f642b..fcdc49ea0 100644 --- a/src/middleware.test.js +++ b/src/middleware.test.js @@ -131,15 +131,12 @@ describe("middleware", () => { expect(res).toEqual({ type: "next" }); }); - it("allows MCP requests with a bearer token when auth is enabled", async () => { + it("delegates MCP authorization to the API handler", async () => { process.env.HOMEPAGE_AUTH_ENABLED = "true"; process.env.HOMEPAGE_AUTH_SECRET = "secret"; - process.env.HOMEPAGE_MCP_TOKEN = "mcp-secret"; const middleware = await loadMiddleware(); - const res = await middleware( - createReq("localhost:3000", "http://localhost:3000/api/mcp", { authorization: "Bearer mcp-secret" }), - ); + const res = await middleware(createReq("localhost:3000", "http://localhost:3000/api/mcp")); expect(getToken).not.toHaveBeenCalled(); expect(NextResponse.next).toHaveBeenCalled(); diff --git a/src/utils/mcp/homepage-mcp.js b/src/utils/mcp/homepage-mcp.js index 0eea0a57b..11f0f956e 100644 --- a/src/utils/mcp/homepage-mcp.js +++ b/src/utils/mcp/homepage-mcp.js @@ -1,4 +1,5 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; +import { createHash, timingSafeEqual } from "node:crypto"; import { join } from "path"; import yaml from "js-yaml"; @@ -61,6 +62,12 @@ function requiredToken() { return process.env.HOMEPAGE_MCP_TOKEN; } +function tokenMatches(provided, expectedDigest) { + if (typeof provided !== "string") return false; + const providedDigest = createHash("sha256").update(provided, "utf8").digest(); + return timingSafeEqual(providedDigest, expectedDigest); +} + function jsonRpcResult(id, result) { return { jsonrpc: "2.0", id, result }; } @@ -440,7 +447,9 @@ export function mcpTokenAuthorized(req) { if (!token) return false; const authHeader = req.headers.authorization; - return authHeader === `Bearer ${token}` || req.headers["x-homepage-mcp-token"] === token; + const bearerToken = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7) : null; + const expectedDigest = createHash("sha256").update(token, "utf8").digest(); + return tokenMatches(bearerToken, expectedDigest) || tokenMatches(req.headers["x-homepage-mcp-token"], expectedDigest); } export function handleMcpRequest(message) { diff --git a/src/utils/mcp/homepage-mcp.test.js b/src/utils/mcp/homepage-mcp.test.js index 7eb5b111c..15c3b8e86 100644 --- a/src/utils/mcp/homepage-mcp.test.js +++ b/src/utils/mcp/homepage-mcp.test.js @@ -626,5 +626,9 @@ describe("utils/mcp/homepage-mcp", () => { expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer secret" } })).toBe(true); expect(mod.mcpTokenAuthorized({ headers: { "x-homepage-mcp-token": "secret" } })).toBe(true); expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer wrong" } })).toBe(false); + + process.env.HOMEPAGE_MCP_TOKEN = "é"; + expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer a" } })).toBe(false); + expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer é" } })).toBe(true); }); });