Fix: move mcp method ordering

This commit is contained in:
shamoon
2026-08-21 06:29:55 -07:00
parent 6c551ace34
commit c57117daae
2 changed files with 40 additions and 5 deletions
+6 -5
View File
@@ -15,6 +15,12 @@ export default async function handler(req, res) {
return res.status(404).end("Not Found");
}
// Method check precedes auth so CORS preflights aren't answered with a 401.
if (req.method !== "POST") {
res.setHeader("Allow", "POST");
return res.status(405).end("Method Not Allowed");
}
const tokenError = mcpTokenConfigError();
if (tokenError) {
createLogger("mcp").error(tokenError);
@@ -25,11 +31,6 @@ export default async function handler(req, res) {
return res.status(401).json({ error: "Unauthorized" });
}
if (req.method !== "POST") {
res.setHeader("Allow", "POST");
return res.status(405).end("Method Not Allowed");
}
const response = handleMcpRequest(req.body);
if (!response) {
return res.status(202).end();
+34
View File
@@ -214,4 +214,38 @@ describe("pages/api/mcp", () => {
expect(res.status).toHaveBeenCalledWith(405);
expect(res.setHeader).toHaveBeenCalledWith("Allow", "POST");
});
it("answers unauthenticated CORS preflights with 405 rather than 401", async () => {
process.env.HOMEPAGE_MCP_ENABLED = "true";
process.env.HOMEPAGE_MCP_TOKEN = "mcp-tok-0123456789abcdefghijklmnopqrstuv";
const handler = await loadHandler();
const res = mockResponse();
// a preflight never carries the Authorization header the browser strips
await handler(
{
method: "OPTIONS",
headers: {
origin: "https://claude.ai",
"access-control-request-method": "POST",
"access-control-request-headers": "authorization,content-type",
},
},
res,
);
expect(res.status).toHaveBeenCalledWith(405);
expect(res.setHeader).toHaveBeenCalledWith("Allow", "POST");
expect(getServerSession).not.toHaveBeenCalled();
});
it("still returns 404 for non-POST requests while disabled", async () => {
delete process.env.HOMEPAGE_MCP_ENABLED;
const handler = await loadHandler();
const res = mockResponse();
await handler({ method: "OPTIONS", headers: {} }, res);
expect(res.status).toHaveBeenCalledWith(404);
});
});