fix MCP auth token refresh and disable legacy SSE
This commit is contained in:
45
mcp-server/auth/mcpAuthMiddleware.js
Normal file
45
mcp-server/auth/mcpAuthMiddleware.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import { validateMcpToken } from "./mcpTokens.js";
|
||||
|
||||
const sendJson = (res, status, payload) => {
|
||||
res.status(status)
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.end(JSON.stringify(payload));
|
||||
};
|
||||
|
||||
export function createMcpAuthMiddleware({ validateToken = validateMcpToken } = {}) {
|
||||
return async (req, res, next) => {
|
||||
if (req.path !== "/mcp" && !req.path?.startsWith("/mcp/")) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Client-provided identity is never trusted on the public MCP transport.
|
||||
delete req.headers["x-acai-user"];
|
||||
|
||||
const secret = req.headers["x-mcp-secret"];
|
||||
if (!secret) {
|
||||
return sendJson(res, 401, { error: "X-MCP-Secret header required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await validateToken(secret);
|
||||
if (!auth?.user) {
|
||||
return sendJson(res, 401, { error: "Invalid MCP token" });
|
||||
}
|
||||
|
||||
req.headers["x-acai-user"] = auth.user;
|
||||
if (auth.project) {
|
||||
req.headers["x-project-name"] = auth.project;
|
||||
} else if (!req.headers["x-project-name"]) {
|
||||
return sendJson(res, 400, {
|
||||
error: "X-Project-Name header required for user-wide token",
|
||||
});
|
||||
}
|
||||
|
||||
req.mcpAuth = auth;
|
||||
return next();
|
||||
} catch (error) {
|
||||
console.error("[MCP auth] token validation failed:", error.message);
|
||||
return sendJson(res, 401, { error: "Invalid MCP token" });
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user