Security: constant time sha comparison for mcp token, DRY

This commit is contained in:
shamoon
2026-07-13 10:22:44 -07:00
parent 75822f632a
commit b7fb4405e4
4 changed files with 20 additions and 15 deletions
+4 -9
View File
@@ -4,13 +4,6 @@ import { NextResponse } from "next/server";
const authEnabled = Boolean(process.env.HOMEPAGE_AUTH_ENABLED); const authEnabled = Boolean(process.env.HOMEPAGE_AUTH_ENABLED);
const authSecret = process.env.NEXTAUTH_SECRET || process.env.HOMEPAGE_AUTH_SECRET; 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) { export async function middleware(req) {
// Check the Host header, if HOMEPAGE_ALLOWED_HOSTS is set // Check the Host header, if HOMEPAGE_ALLOWED_HOSTS is set
const host = req.headers.get("host"); 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 }); return NextResponse.json({ error: "Host validation failed. See logs for more details." }, { status: 400 });
} }
if (authEnabled && !new URL(req.url).pathname.startsWith("/api/healthcheck")) { const pathname = new URL(req.url).pathname;
if (new URL(req.url).pathname === "/api/mcp" && hasMcpToken(req)) { if (authEnabled && !pathname.startsWith("/api/healthcheck")) {
// The MCP API handler authorizes both bearer tokens and Homepage sessions.
if (pathname === "/api/mcp") {
return NextResponse.next(); return NextResponse.next();
} }
+2 -5
View File
@@ -131,15 +131,12 @@ describe("middleware", () => {
expect(res).toEqual({ type: "next" }); 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_ENABLED = "true";
process.env.HOMEPAGE_AUTH_SECRET = "secret"; process.env.HOMEPAGE_AUTH_SECRET = "secret";
process.env.HOMEPAGE_MCP_TOKEN = "mcp-secret";
const middleware = await loadMiddleware(); const middleware = await loadMiddleware();
const res = await middleware( const res = await middleware(createReq("localhost:3000", "http://localhost:3000/api/mcp"));
createReq("localhost:3000", "http://localhost:3000/api/mcp", { authorization: "Bearer mcp-secret" }),
);
expect(getToken).not.toHaveBeenCalled(); expect(getToken).not.toHaveBeenCalled();
expect(NextResponse.next).toHaveBeenCalled(); expect(NextResponse.next).toHaveBeenCalled();
+10 -1
View File
@@ -1,4 +1,5 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { createHash, timingSafeEqual } from "node:crypto";
import { join } from "path"; import { join } from "path";
import yaml from "js-yaml"; import yaml from "js-yaml";
@@ -61,6 +62,12 @@ function requiredToken() {
return process.env.HOMEPAGE_MCP_TOKEN; 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) { function jsonRpcResult(id, result) {
return { jsonrpc: "2.0", id, result }; return { jsonrpc: "2.0", id, result };
} }
@@ -440,7 +447,9 @@ export function mcpTokenAuthorized(req) {
if (!token) return false; if (!token) return false;
const authHeader = req.headers.authorization; 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) { export function handleMcpRequest(message) {
+4
View File
@@ -626,5 +626,9 @@ describe("utils/mcp/homepage-mcp", () => {
expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer secret" } })).toBe(true); expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer secret" } })).toBe(true);
expect(mod.mcpTokenAuthorized({ headers: { "x-homepage-mcp-token": "secret" } })).toBe(true); expect(mod.mcpTokenAuthorized({ headers: { "x-homepage-mcp-token": "secret" } })).toBe(true);
expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer wrong" } })).toBe(false); 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);
}); });
}); });