feat(oauth): add standard MCP OAuth 2.1 (RFC 9728/8414/7591 + PKCE S256) with dual-auth for Gemini, ChatGPT & Claude Web

This commit is contained in:
Amirul Islam Redwan71
2026-11-24 04:19:12 +06:00
parent 5e25a6277c
commit eeba92042c
10 changed files with 2747 additions and 19 deletions
+7 -1
View File
@@ -8,6 +8,7 @@ import { loadConfig } from "./config.js";
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
import { createRateLimiter } from "./middleware/rate_limit.js";
import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, verifyWebhookSignature, recordAuditLog, initDynamicAuthStore, upsertDynamicKeyHash, setTenantDynamicKeyStatus, listDynamicKeySummaries, } from "./middleware/auth.js";
import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js";
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
import { APP_VERSION } from "./version.js";
import path from "node:path";
@@ -127,12 +128,14 @@ export function keysFromRequest(req) {
};
}
export const app = express();
app.set("trust proxy", 1);
app.use(express.json({
limit: "1mb",
verify: (req, _res, buf) => {
req.rawBody = buf;
},
}));
app.use(express.urlencoded({ extended: false, limit: "1mb" }));
// Robust Malformed JSON Syntax Error Guard
app.use((err, _req, res, next) => {
if (err && (err.type === "entity.parse.failed" || err.status === 400)) {
@@ -149,7 +152,7 @@ app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT");
res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key");
res.header("Access-Control-Expose-Headers", "mcp-session-id");
res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate");
if (req.method === "OPTIONS") {
return res.sendStatus(204);
}
@@ -164,6 +167,8 @@ app.get("/favicon.ico", (_req, res) => {
res.status(204).end();
});
});
// Standard MCP OAuth 2.1 + PKCE (S256) + RFC 9728 + RFC 8414 + RFC 7591 Dynamic Client Registration
registerOAuthRoutes(app);
app.use(optionalAuthMiddleware);
// Dynamic Tenant API Key Sync & Revocation Routes (Called by Snehalata / Admin Master Key)
app.get("/admin/tokens", (req, res) => {
@@ -347,6 +352,7 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
});
}
if (!req.auraAuth?.authenticated) {
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, req.auraAuth?.tenantId === "invalid"));
return res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header.",
+24 -7
View File
@@ -1,5 +1,6 @@
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
import { verifyOAuthAccessToken, buildWwwAuthenticateHeader } from "./oauth.js";
const READ_TOOLS = new Set([
"list_couriers",
"track_parcel",
@@ -82,6 +83,8 @@ export async function initDynamicAuthStore(pool) {
`);
}
catch (ddlErr) {
// Least-privilege runtime DB roles (e.g. aura_courier_runtime) intentionally lack schema CREATE;
// the table is pre-provisioned, so continue cleanly to load rows below.
if (!/permission denied/i.test(String(ddlErr?.message || ""))) {
console.warn("[Auth] Dynamic key table DDL skipped:", ddlErr?.message);
}
@@ -196,6 +199,20 @@ export function resolveAuthContext(req) {
isAdmin: false,
};
}
// 0. Standard MCP OAuth 2.1 JWT Access Token (Google Gemini, ChatGPT, Claude Web)
if (token.startsWith("eyJ") && token.split(".").length === 3) {
const oauthClaims = verifyOAuthAccessToken(token);
if (oauthClaims) {
return {
authenticated: true,
tenantId: oauthClaims.sub,
scopes: Array.isArray(oauthClaims.scp) && oauthClaims.scp.length ? oauthClaims.scp : ["read"],
isByok,
isAdmin: Boolean(oauthClaims.adm),
callerToken: token,
};
}
}
// 1. Master / Admin Key (Full Read + Write across all tenants)
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
return {
@@ -376,20 +393,19 @@ export function requireMcpAuth(req, res, next) {
})));
return;
}
// If a caller explicitly passed an invalid / forged token, always reject with 401
// If a caller explicitly passed an invalid / expired / forged token, always reject with 401 + RFC 9728 WWW-Authenticate
if (ctx.tenantId === "invalid") {
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, true));
res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "Invalid or forged Authorization token.",
message: "Invalid or expired Authorization token.",
retryable: false,
source: "validator",
})));
return;
}
// Allow unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping)
const isDiscovery = method === "initialize" ||
method === "notifications/initialized" ||
method === "tools/list" ||
// Allow stateless public catalog discovery (tools/list, ping) for MCP directories while requiring auth on initialize/tools/call so OAuth 2.1 clients (Gemini, ChatGPT, Claude Web) trigger automatic OAuth discovery via 401 WWW-Authenticate.
const isDiscovery = method === "tools/list" ||
method === "ping";
if (isDiscovery) {
return next();
@@ -399,9 +415,10 @@ export function requireMcpAuth(req, res, next) {
return next();
}
if (!ctx.authenticated) {
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, false));
res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Please provide your API key or BYOK carrier keys.",
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Authenticate via MCP OAuth 2.1 or provide your API key / BYOK carrier keys.",
retryable: false,
source: "validator",
})));
+19
View File
@@ -0,0 +1,19 @@
import type { Express, Request } from "express";
import { type AuthScope } from "./auth.js";
export interface OAuthAccessClaims {
iss: string;
aud: string;
sub: string;
adm: boolean;
scp: AuthScope[];
cid: string;
typ: "at";
iat: number;
exp: number;
jti: string;
}
export declare function verifyOAuthAccessToken(token: string): OAuthAccessClaims | null;
export declare function getPublicOrigin(req: Request): string;
export declare function buildWwwAuthenticateHeader(req: Request, invalidToken?: boolean): string;
export declare function isAllowedRedirectUri(uri: string): boolean;
export declare function registerOAuthRoutes(app: Express): void;
+1013
View File
File diff suppressed because it is too large Load Diff