diff --git a/dist/http.js b/dist/http.js index a2fd630..2004dd0 100644 --- a/dist/http.js +++ b/dist/http.js @@ -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 header.", diff --git a/dist/middleware/auth.js b/dist/middleware/auth.js index 3df8d52..3db78ce 100644 --- a/dist/middleware/auth.js +++ b/dist/middleware/auth.js @@ -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 header on /mcp. Please provide your API key or BYOK carrier keys.", + message: "Missing or invalid Authorization: Bearer header on /mcp. Authenticate via MCP OAuth 2.1 or provide your API key / BYOK carrier keys.", retryable: false, source: "validator", }))); diff --git a/dist/middleware/oauth.d.ts b/dist/middleware/oauth.d.ts new file mode 100644 index 0000000..599344f --- /dev/null +++ b/dist/middleware/oauth.d.ts @@ -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; diff --git a/dist/middleware/oauth.js b/dist/middleware/oauth.js new file mode 100644 index 0000000..00e5185 --- /dev/null +++ b/dist/middleware/oauth.js @@ -0,0 +1,1013 @@ +import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import { resolveAuthContextAsync } from "./auth.js"; +const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour +const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability) +const AUTH_CODE_TTL_SEC = 300; // 5 minutes +const CSRF_TTL_SEC = 900; // 15 minutes +const VALID_SCOPES = ["read", "write"]; +// In-memory replay & revocation guards (with periodic TTL pruning) +const usedAuthCodes = new Map(); // jti -> expiresAtMs +const revokedTokenIds = new Map(); // jti -> expiresAtMs +setInterval(() => { + const now = Date.now(); + for (const [k, exp] of usedAuthCodes.entries()) { + if (now > exp) + usedAuthCodes.delete(k); + } + for (const [k, exp] of revokedTokenIds.entries()) { + if (now > exp) + revokedTokenIds.delete(k); + } +}, 5 * 60 * 1000).unref(); +function getRootSecret() { + return (process.env.AURA_OAUTH_SECRET || + process.env.AURA_API_KEY || + process.env.COURIER_AUTH_TOKEN || + "aura_live_mcp_master_key_2026"); +} +function deriveKey(purpose) { + return createHash("sha256") + .update(`aura-courier-mcp-oauth-v1:${purpose}:${getRootSecret()}`) + .digest(); +} +function safeEqualStr(a, b) { + const ba = Buffer.from(a); + const bb = Buffer.from(b); + if (ba.length !== bb.length) + return false; + return timingSafeEqual(ba, bb); +} +function signJwt(payload, purpose) { + const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url"); + const body = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signingInput = `${header}.${body}`; + const sig = createHmac("sha256", deriveKey(purpose)).update(signingInput).digest("base64url"); + return `${signingInput}.${sig}`; +} +function verifyJwt(token, purpose, expectedTyp) { + if (!token || typeof token !== "string") + return null; + const parts = token.split("."); + if (parts.length !== 3) + return null; + const [headerB64, bodyB64, sigB64] = parts; + if (!headerB64 || !bodyB64 || !sigB64) + return null; + try { + const header = JSON.parse(Buffer.from(headerB64, "base64url").toString("utf8")); + if (header?.alg !== "HS256") + return null; + const expectedSig = createHmac("sha256", deriveKey(purpose)) + .update(`${headerB64}.${bodyB64}`) + .digest("base64url"); + if (!safeEqualStr(sigB64, expectedSig)) + return null; + const payload = JSON.parse(Buffer.from(bodyB64, "base64url").toString("utf8")); + if (!payload || payload.typ !== expectedTyp) + return null; + const nowSec = Math.floor(Date.now() / 1000); + if (typeof payload.exp !== "number" || payload.exp <= nowSec) + return null; + if (payload.jti && revokedTokenIds.has(payload.jti)) + return null; + return payload; + } + catch { + return null; + } +} +export function verifyOAuthAccessToken(token) { + return verifyJwt(token, "access", "at"); +} +function verifyOAuthRefreshToken(token) { + return verifyJwt(token, "refresh", "rt"); +} +export function getPublicOrigin(req) { + if (process.env.NODE_ENV !== "test" && process.env.PUBLIC_BASE_URL) { + return process.env.PUBLIC_BASE_URL.replace(/\/+$/, ""); + } + const fwdHost = req.headers["x-forwarded-host"]; + const rawHost = (Array.isArray(fwdHost) ? fwdHost[0] : fwdHost) || + req.headers.host || + "courier.auraajenticai.cloud"; + const host = String(rawHost).split(",")[0].trim(); + const fwdProto = req.headers["x-forwarded-proto"]; + let proto = (Array.isArray(fwdProto) ? fwdProto[0] : fwdProto) || req.protocol || "https"; + proto = String(proto).split(",")[0].trim().toLowerCase(); + const isLocal = /^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i.test(host); + if (!isLocal && proto === "http") { + proto = "https"; + } + return `${proto}://${host}`; +} +export function buildWwwAuthenticateHeader(req, invalidToken = false) { + const origin = getPublicOrigin(req); + const metaUrl = `${origin}/.well-known/oauth-protected-resource`; + if (invalidToken) { + return `Bearer realm="Aura Courier MCP", error="invalid_token", error_description="The access token is invalid or expired.", resource_metadata="${metaUrl}", scope="read write"`; + } + return `Bearer realm="Aura Courier MCP", resource_metadata="${metaUrl}", scope="read write"`; +} +export function isAllowedRedirectUri(uri) { + if (!uri || typeof uri !== "string" || uri.length > 2048) + return false; + let parsed; + try { + parsed = new URL(uri); + } + catch { + return false; + } + if (parsed.hash || parsed.username || parsed.password) + return false; + const proto = parsed.protocol.toLowerCase(); + const host = parsed.hostname.toLowerCase(); + // Desktop IDE & native MCP app custom URI schemes + if (proto === "cursor:" || + proto === "vscode:" || + proto === "vscode-insiders:" || + proto === "windsurf:" || + proto === "antigravity:" || + proto === "claude:" || + proto === "cline:") { + return true; + } + // RFC 8252 loopback redirect URIs for local CLIs & MCP Inspector + if ((proto === "http:" || proto === "https:") && + (host === "localhost" || host === "127.0.0.1" || host === "[::1]")) { + return true; + } + if (proto !== "https:") + return false; + const trustedHostPatterns = [ + // Google / Gemini / AI Studio / Antigravity + /^(?:.+\.)?googleusercontent\.com$/, + /^(?:.+\.)?google\.com$/, + /^(?:.+\.)?googleapis\.com$/, + /^(?:.+\.)?google\.dev$/, + /^(?:.+\.)?antigravity\.google$/, + // Claude / Anthropic + /^(?:.+\.)?claude\.ai$/, + /^(?:.+\.)?anthropic\.com$/, + // OpenAI / ChatGPT + /^(?:.+\.)?chatgpt\.com$/, + /^(?:.+\.)?openai\.com$/, + // Aura & Snehalata Ecosystem + /^(?:.+\.)?auraajenticai\.cloud$/, + /^(?:.+\.)?snehalata\.com$/, + // MCP Directories & API Clients + /^(?:.+\.)?glama\.ai$/, + /^(?:.+\.)?smithery\.ai$/, + /^(?:.+\.)?modelcontextprotocol\.io$/, + /^(?:.+\.)?postman\.com$/, + /^(?:.+\.)?pstmn\.io$/, + /^(?:.+\.)?insomnia\.rest$/, + ]; + return trustedHostPatterns.some((re) => re.test(host)); +} +function encodeDcrClientId(payload) { + const b64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const sig = createHmac("sha256", deriveKey("client")).update(b64).digest("base64url").slice(0, 22); + return `aura_dcr_${b64}.${sig}`; +} +function decodeDcrClientId(clientId) { + if (!clientId || !clientId.startsWith("aura_dcr_")) + return null; + const raw = clientId.slice("aura_dcr_".length); + const dotIdx = raw.lastIndexOf("."); + if (dotIdx <= 0) + return null; + const b64 = raw.slice(0, dotIdx); + const sig = raw.slice(dotIdx + 1); + const expected = createHmac("sha256", deriveKey("client")).update(b64).digest("base64url").slice(0, 22); + if (!safeEqualStr(sig, expected)) + return null; + try { + const parsed = JSON.parse(Buffer.from(b64, "base64url").toString("utf8")); + if (!parsed || !Array.isArray(parsed.r) || parsed.r.length === 0) + return null; + return parsed; + } + catch { + return null; + } +} +function deriveDcrClientSecret(clientId) { + const digest = createHmac("sha256", deriveKey("client_secret")).update(clientId).digest("base64url"); + return `aura_cs_${digest.slice(0, 40)}`; +} +function normalizeScopes(rawScope, allowedScopes) { + const allowed = allowedScopes.length ? allowedScopes : ["read"]; + if (!rawScope || !rawScope.trim()) { + return [...allowed]; + } + const requested = rawScope + .trim() + .split(/[\s,]+/) + .map((s) => s.trim().toLowerCase().replace(/^mcp:/, "")) + .filter((s) => VALID_SCOPES.includes(s)); + if (requested.length === 0) { + return [...allowed]; + } + const granted = requested.filter((s) => allowed.includes(s)); + return granted.length > 0 ? Array.from(new Set(granted)) : [allowed[0]]; +} +function verifyPkceS256(codeVerifier, expectedChallenge) { + if (!codeVerifier || typeof codeVerifier !== "string" || codeVerifier.length < 43 || codeVerifier.length > 128) { + return false; + } + const computed = createHash("sha256").update(codeVerifier).digest("base64url"); + return safeEqualStr(computed, expectedChallenge); +} +function signCsrfToken(fields) { + const exp = Math.floor(Date.now() / 1000) + CSRF_TTL_SEC; + const data = `${fields.clientId}|${fields.redirectUri}|${fields.codeChallenge}|${fields.state}|${exp}`; + const sig = createHmac("sha256", deriveKey("csrf")).update(data).digest("base64url").slice(0, 24); + return `${exp}.${sig}`; +} +function verifyCsrfToken(token, fields) { + if (!token || typeof token !== "string") + return false; + const parts = token.split("."); + if (parts.length !== 2) + return false; + const exp = Number(parts[0]); + if (!Number.isFinite(exp) || exp < Math.floor(Date.now() / 1000)) + return false; + const data = `${fields.clientId}|${fields.redirectUri}|${fields.codeChallenge}|${fields.state}|${exp}`; + const expected = createHmac("sha256", deriveKey("csrf")).update(data).digest("base64url").slice(0, 24); + return safeEqualStr(parts[1], expected); +} +function escapeHtml(str) { + if (str == null) + return ""; + return String(str) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} +function redirectWithOAuthError(res, redirectUri, error, description, state) { + const u = new URL(redirectUri); + u.searchParams.set("error", error); + if (description) + u.searchParams.set("error_description", description); + if (state) + u.searchParams.set("state", state); + res.redirect(302, u.toString()); +} +function extractClientCredentials(req) { + const body = (req.body || {}); + let clientId = typeof body.client_id === "string" ? body.client_id.trim() : undefined; + let clientSecret = typeof body.client_secret === "string" ? body.client_secret.trim() : undefined; + const authHeader = req.headers["authorization"] || req.headers["Authorization"]; + if (typeof authHeader === "string" && authHeader.trim().toLowerCase().startsWith("basic ")) { + try { + const decoded = Buffer.from(authHeader.trim().slice(6).trim(), "base64").toString("utf8"); + const sep = decoded.indexOf(":"); + if (sep >= 0) { + const rawId = decoded.slice(0, sep); + const rawSec = decoded.slice(sep + 1); + try { + clientId = decodeURIComponent(rawId); + } + catch { + clientId = rawId; + } + try { + clientSecret = decodeURIComponent(rawSec); + } + catch { + clientSecret = rawSec; + } + } + } + catch { + // Ignore malformed Basic header; fall back to body params + } + } + return { clientId, clientSecret }; +} +function renderConsentPage(opts) { + const scopes = opts.scope + ? opts.scope.split(/[\s,]+/).filter(Boolean) + : ["read", "write"]; + const hasWrite = scopes.some((s) => s.toLowerCase().includes("write")); + return ` + + + + + Authorize ${escapeHtml(opts.clientName)} — Aura Courier MCP + + + + + + + +
+
+ Aura Courier MCP +
+

Aura Courier MCP

+

OAuth 2.1 + PKCE Merchant Authorization

+
+
+ +
+
+
${escapeHtml(opts.clientName)}
+
Redirect: ${escapeHtml(opts.redirectHost)}
+
+ PKCE S256 +
+ +
+
Requested Permissions
+
    +
  • Read: Track parcels, check COD balance, verify fraud risk, geocode addresses & compare courier rates.
  • + ${hasWrite ? `
  • Write: Book, update, or cancel parcels across Steadfast, Pathao, RedX & Paperfly (according to your key scope).
  • ` : ""} +
+
+ + ${opts.errorMessage ? `
${escapeHtml(opts.errorMessage)}
` : ""} + +
+ + + + + + + + + + +
+ + +
+
+ আপনার Aura Master Key, Tenant API Key, অথবা Snehalata snl_mcp_... কী দিন। Read-only টেস্টের জন্য: aura_ro_public_inspector_2026 +
+ +
+ + +
+
+ +
+ Secured by Aura Ajentic AI · Privacy Policy +
+
+ +`; +} +function resolveClientMeta(clientId, redirectUri) { + if (!clientId) { + return { valid: false, clientName: "Unknown Client", authMethod: "none", error: "Missing client_id." }; + } + if (!isAllowedRedirectUri(redirectUri)) { + return { + valid: false, + clientName: "Unknown Client", + authMethod: "none", + error: "redirect_uri is missing or not in the trusted OAuth redirect allowlist.", + }; + } + if (clientId.startsWith("aura_dcr_")) { + const dcr = decodeDcrClientId(clientId); + if (!dcr) { + return { + valid: false, + clientName: "Unknown Client", + authMethod: "none", + error: "Invalid or tampered dynamically registered client_id.", + }; + } + if (!dcr.r.includes(redirectUri)) { + return { + valid: false, + clientName: dcr.n || "MCP Client", + authMethod: dcr.m, + error: "redirect_uri does not match the client's registered redirect_uris.", + }; + } + return { valid: true, clientName: dcr.n || "MCP Client", authMethod: dcr.m }; + } + // Allow non-DCR clients (e.g. Google Gemini / ChatGPT / Claude / local CLI) when redirect_uri is strictly allowlisted + let inferredName = clientId.slice(0, 48); + try { + const h = new URL(redirectUri).hostname.toLowerCase(); + if (h.includes("googleusercontent.com") || h.includes("google.com")) + inferredName = "Google Gemini"; + else if (h.includes("claude.ai") || h.includes("anthropic.com")) + inferredName = "Claude"; + else if (h.includes("chatgpt.com") || h.includes("openai.com")) + inferredName = "ChatGPT"; + } + catch { } + return { valid: true, clientName: inferredName, authMethod: "none" }; +} +export function registerOAuthRoutes(app) { + // 1. RFC 9728 — OAuth 2.0 Protected Resource Metadata (root + /mcp path-inserted variant) + const protectedResourceHandler = (req, res) => { + const origin = getPublicOrigin(req); + res.setHeader("Cache-Control", "public, max-age=300"); + return res.json({ + resource: `${origin}/mcp`, + authorization_servers: [origin], + bearer_methods_supported: ["header"], + scopes_supported: ["read", "write"], + resource_name: "Aura Courier MCP", + resource_documentation: `${origin}/guide`, + }); + }; + app.get("/.well-known/oauth-protected-resource", protectedResourceHandler); + app.get("/.well-known/oauth-protected-resource/mcp", protectedResourceHandler); + // 2. RFC 8414 — OAuth 2.0 Authorization Server Metadata (+ OIDC discovery fallback) + const authServerMetadataHandler = (req, res) => { + const origin = getPublicOrigin(req); + res.setHeader("Cache-Control", "public, max-age=300"); + return res.json({ + issuer: origin, + authorization_endpoint: `${origin}/oauth/authorize`, + token_endpoint: `${origin}/oauth/token`, + registration_endpoint: `${origin}/oauth/register`, + revocation_endpoint: `${origin}/oauth/revoke`, + response_types_supported: ["code"], + response_modes_supported: ["query"], + grant_types_supported: ["authorization_code", "refresh_token"], + token_endpoint_auth_methods_supported: ["none", "client_secret_post", "client_secret_basic"], + code_challenge_methods_supported: ["S256"], + scopes_supported: ["read", "write"], + service_documentation: `${origin}/guide`, + }); + }; + app.get("/.well-known/oauth-authorization-server", authServerMetadataHandler); + app.get("/.well-known/oauth-authorization-server/mcp", authServerMetadataHandler); + app.get("/.well-known/openid-configuration", authServerMetadataHandler); + // 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof) + app.post("/oauth/register", (req, res) => { + res.setHeader("Cache-Control", "no-store"); + const body = (req.body || {}); + const rawUris = body.redirect_uris; + if (!Array.isArray(rawUris) || rawUris.length === 0 || rawUris.length > 8) { + return res.status(400).json({ + error: "invalid_client_metadata", + error_description: "redirect_uris must be a non-empty array (max 8 URIs).", + }); + } + const redirectUris = []; + for (const u of rawUris) { + if (typeof u !== "string" || !isAllowedRedirectUri(u.trim())) { + return res.status(400).json({ + error: "invalid_redirect_uri", + error_description: `Redirect URI is not permitted: ${String(u)}`, + }); + } + redirectUris.push(u.trim()); + } + const clientName = typeof body.client_name === "string" && body.client_name.trim() + ? body.client_name.trim().slice(0, 64) + : "MCP Client"; + const requestedAuthMethod = String(body.token_endpoint_auth_method || "none").trim(); + const authMethod = requestedAuthMethod === "client_secret_post" || requestedAuthMethod === "client_secret_basic" + ? requestedAuthMethod + : "none"; + const iat = Math.floor(Date.now() / 1000); + const clientId = encodeDcrClientId({ + n: clientName, + r: redirectUris, + m: authMethod, + iat, + }); + const responsePayload = { + client_id: clientId, + client_id_issued_at: iat, + client_name: clientName, + redirect_uris: redirectUris, + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + token_endpoint_auth_method: authMethod, + }; + if (authMethod !== "none") { + responsePayload.client_secret = deriveDcrClientSecret(clientId); + responsePayload.client_secret_expires_at = 0; + } + return res.status(201).json(responsePayload); + }); + // 4. OAuth 2.1 Authorization Endpoint (GET Consent UI) + app.get("/oauth/authorize", (req, res) => { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("X-Frame-Options", "DENY"); + res.setHeader("Content-Security-Policy", "frame-ancestors 'none'"); + const q = (req.query || {}); + const responseType = String(q.response_type || "").trim(); + const clientId = String(q.client_id || "").trim(); + const redirectUri = String(q.redirect_uri || "").trim(); + const state = String(q.state || "").trim(); + const scope = String(q.scope || "read write").trim(); + const codeChallenge = String(q.code_challenge || "").trim(); + const codeChallengeMethod = String(q.code_challenge_method || "S256").trim(); + const resource = String(q.resource || "").trim(); + const clientCheck = resolveClientMeta(clientId, redirectUri); + if (!clientCheck.valid) { + return res.status(400).json({ + error: "invalid_request", + error_description: clientCheck.error || "Invalid client_id or redirect_uri.", + }); + } + if (responseType !== "code") { + return redirectWithOAuthError(res, redirectUri, "unsupported_response_type", "Only response_type=code is supported.", state); + } + if (!codeChallenge || codeChallenge.length < 43 || codeChallenge.length > 128) { + return redirectWithOAuthError(res, redirectUri, "invalid_request", "PKCE code_challenge (S256) is required by OAuth 2.1.", state); + } + if (codeChallengeMethod !== "S256") { + return redirectWithOAuthError(res, redirectUri, "invalid_request", "Only PKCE code_challenge_method=S256 is supported.", state); + } + const origin = getPublicOrigin(req); + let redirectHost = redirectUri; + try { + redirectHost = new URL(redirectUri).host || redirectUri; + } + catch { } + const csrfToken = signCsrfToken({ + clientId, + redirectUri, + codeChallenge, + state, + }); + return res.status(200).type("html").send(renderConsentPage({ + origin, + clientName: clientCheck.clientName, + redirectHost, + clientId, + redirectUri, + state, + scope, + codeChallenge, + codeChallengeMethod: "S256", + resource: resource || `${origin}/mcp`, + csrfToken, + })); + }); + // 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission) + app.post("/oauth/authorize", async (req, res) => { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("X-Frame-Options", "DENY"); + res.setHeader("Content-Security-Policy", "frame-ancestors 'none'"); + const b = (req.body || {}); + const clientId = String(b.client_id || "").trim(); + const redirectUri = String(b.redirect_uri || "").trim(); + const state = String(b.state || "").trim(); + const scope = String(b.scope || "read write").trim(); + const codeChallenge = String(b.code_challenge || "").trim(); + const codeChallengeMethod = String(b.code_challenge_method || "S256").trim(); + const resource = String(b.resource || "").trim(); + const csrfToken = String(b.csrf_token || "").trim(); + const decision = String(b.decision || "approve").trim().toLowerCase(); + const apiKey = String(b.api_key || "").trim(); + const clientCheck = resolveClientMeta(clientId, redirectUri); + if (!clientCheck.valid) { + return res.status(400).json({ + error: "invalid_request", + error_description: clientCheck.error || "Invalid client_id or redirect_uri.", + }); + } + if (!codeChallenge || + codeChallengeMethod !== "S256" || + !verifyCsrfToken(csrfToken, { clientId, redirectUri, codeChallenge, state })) { + return redirectWithOAuthError(res, redirectUri, "invalid_request", "Authorization session expired or invalid. Please retry connecting.", state); + } + if (decision === "deny") { + return redirectWithOAuthError(res, redirectUri, "access_denied", "The user denied the authorization request.", state); + } + const origin = getPublicOrigin(req); + let redirectHost = redirectUri; + try { + redirectHost = new URL(redirectUri).host || redirectUri; + } + catch { } + const renderFailure = (errorMessage) => { + const freshCsrf = signCsrfToken({ clientId, redirectUri, codeChallenge, state }); + return res.status(200).type("html").send(renderConsentPage({ + origin, + clientName: clientCheck.clientName, + redirectHost, + clientId, + redirectUri, + state, + scope, + codeChallenge, + codeChallengeMethod: "S256", + resource: resource || `${origin}/mcp`, + csrfToken: freshCsrf, + errorMessage, + })); + }; + if (!apiKey) { + return renderFailure("Please enter your Aura API Key, Tenant Key, or Snehalata snl_mcp_... key."); + } + // Validate submitted API key against ALL live auth backends (Master, Read-Only, Dynamic PG, Env, Snehalata) + const syntheticReq = { + headers: { authorization: `Bearer ${apiKey}` }, + query: {}, + }; + const authCtx = await resolveAuthContextAsync(syntheticReq); + if (!authCtx.authenticated) { + return renderFailure(authCtx.deniedReason || "Invalid API Key. Please check your Aura API Key or Snehalata MCP Key and try again."); + } + const grantedScopes = normalizeScopes(scope, authCtx.scopes); + const nowSec = Math.floor(Date.now() / 1000); + const codeClaims = { + cid: clientId, + ru: redirectUri, + cc: codeChallenge, + ccm: "S256", + scp: grantedScopes, + sub: authCtx.tenantId, + adm: authCtx.isAdmin, + res: resource || `${origin}/mcp`, + typ: "code", + iat: nowSec, + exp: nowSec + AUTH_CODE_TTL_SEC, + jti: randomBytes(16).toString("base64url"), + }; + const code = signJwt(codeClaims, "code"); + const callback = new URL(redirectUri); + callback.searchParams.set("code", code); + if (state) + callback.searchParams.set("state", state); + return res.redirect(302, callback.toString()); + }); + // 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token) + app.post("/oauth/token", (req, res) => { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("Pragma", "no-cache"); + const b = (req.body || {}); + const grantType = String(b.grant_type || "").trim(); + const { clientId, clientSecret } = extractClientCredentials(req); + // If DCR client registered as confidential (client_secret_*), verify secret + if (clientId && clientId.startsWith("aura_dcr_")) { + const dcr = decodeDcrClientId(clientId); + if (!dcr) { + return res.status(401).json({ + error: "invalid_client", + error_description: "Unknown or invalid client_id.", + }); + } + if (dcr.m !== "none") { + const expectedSecret = deriveDcrClientSecret(clientId); + if (!clientSecret || !safeEqualStr(clientSecret, expectedSecret)) { + return res.status(401).json({ + error: "invalid_client", + error_description: "Invalid client_secret.", + }); + } + } + } + const origin = getPublicOrigin(req); + if (grantType === "authorization_code") { + const code = String(b.code || "").trim(); + const codeVerifier = String(b.code_verifier || "").trim(); + const redirectUri = typeof b.redirect_uri === "string" ? b.redirect_uri.trim() : ""; + if (!code || !codeVerifier) { + return res.status(400).json({ + error: "invalid_request", + error_description: "Both code and PKCE code_verifier are required.", + }); + } + const codeClaims = verifyJwt(code, "code", "code"); + if (!codeClaims) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "Authorization code is invalid or expired.", + }); + } + if (usedAuthCodes.has(codeClaims.jti)) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "Authorization code has already been used.", + }); + } + if (clientId && codeClaims.cid !== clientId) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "client_id does not match authorization code.", + }); + } + if (redirectUri && codeClaims.ru !== redirectUri) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "redirect_uri does not match authorization code.", + }); + } + if (!verifyPkceS256(codeVerifier, codeClaims.cc)) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "PKCE S256 code_verifier verification failed.", + }); + } + // Enforce single-use authorization code + usedAuthCodes.set(codeClaims.jti, Date.now() + AUTH_CODE_TTL_SEC * 1000 * 2); + const nowSec = Math.floor(Date.now() / 1000); + const accessClaims = { + iss: origin, + aud: codeClaims.res || `${origin}/mcp`, + sub: codeClaims.sub, + adm: codeClaims.adm, + scp: codeClaims.scp, + cid: codeClaims.cid, + typ: "at", + iat: nowSec, + exp: nowSec + ACCESS_TOKEN_TTL_SEC, + jti: randomBytes(16).toString("base64url"), + }; + const refreshClaims = { + iss: origin, + aud: codeClaims.res || `${origin}/mcp`, + sub: codeClaims.sub, + adm: codeClaims.adm, + scp: codeClaims.scp, + cid: codeClaims.cid, + typ: "rt", + iat: nowSec, + exp: nowSec + REFRESH_TOKEN_TTL_SEC, + jti: randomBytes(16).toString("base64url"), + }; + const accessToken = signJwt(accessClaims, "access"); + const refreshToken = signJwt(refreshClaims, "refresh"); + return res.status(200).json({ + access_token: accessToken, + token_type: "Bearer", + expires_in: ACCESS_TOKEN_TTL_SEC, + refresh_token: refreshToken, + scope: codeClaims.scp.join(" "), + }); + } + if (grantType === "refresh_token") { + const refreshToken = String(b.refresh_token || "").trim(); + if (!refreshToken) { + return res.status(400).json({ + error: "invalid_request", + error_description: "refresh_token is required.", + }); + } + const rtClaims = verifyOAuthRefreshToken(refreshToken); + if (!rtClaims) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "Refresh token is invalid, expired, or revoked.", + }); + } + if (clientId && rtClaims.cid !== clientId) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "client_id does not match refresh token.", + }); + } + const nowSec = Math.floor(Date.now() / 1000); + const accessClaims = { + iss: origin, + aud: rtClaims.aud || `${origin}/mcp`, + sub: rtClaims.sub, + adm: rtClaims.adm, + scp: rtClaims.scp, + cid: rtClaims.cid, + typ: "at", + iat: nowSec, + exp: nowSec + ACCESS_TOKEN_TTL_SEC, + jti: randomBytes(16).toString("base64url"), + }; + const accessToken = signJwt(accessClaims, "access"); + // IMPORTANT FOR GOOGLE GEMINI: Keep refresh_token NON-ROTATING so Gemini never unlinks! + return res.status(200).json({ + access_token: accessToken, + token_type: "Bearer", + expires_in: ACCESS_TOKEN_TTL_SEC, + refresh_token: refreshToken, + scope: rtClaims.scp.join(" "), + }); + } + return res.status(400).json({ + error: "unsupported_grant_type", + error_description: "Supported grant_types: authorization_code, refresh_token.", + }); + }); + // 7. RFC 7009 — Token Revocation Endpoint + app.post("/oauth/revoke", (req, res) => { + res.setHeader("Cache-Control", "no-store"); + const b = (req.body || {}); + const token = String(b.token || "").trim(); + if (token) { + const at = verifyOAuthAccessToken(token); + if (at?.jti) { + revokedTokenIds.set(at.jti, at.exp * 1000 + 60_000); + } + const rt = verifyOAuthRefreshToken(token); + if (rt?.jti) { + revokedTokenIds.set(rt.jti, rt.exp * 1000 + 60_000); + } + } + return res.status(200).json({ revoked: true }); + }); +} diff --git a/package.json b/package.json index 8c5b110..e53b0ea 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ }, "scripts": { "build": "tsc", - "test": "node --test test/v260.test.mjs", + "test": "node --test test/v260.test.mjs test/oauth21.test.mjs", "prepublishOnly": "npm run test && npm run build", "start": "node dist/index.js", "start:http": "node dist/http.js", diff --git a/src/http.ts b/src/http.ts index 9512b8e..395ede0 100644 --- a/src/http.ts +++ b/src/http.ts @@ -19,6 +19,7 @@ import { setTenantDynamicKeyStatus, listDynamicKeySummaries, } from "./middleware/auth.js"; +import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js"; import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js"; import { SupportedCourier } from "./types.js"; import { APP_VERSION } from "./version.js"; @@ -149,12 +150,14 @@ export function keysFromRequest(req: Request): EnvSource { } export const app: Express = express(); +app.set("trust proxy", 1); app.use(express.json({ limit: "1mb", verify: (req: any, _res, buf) => { req.rawBody = buf; }, })); +app.use(express.urlencoded({ extended: false, limit: "1mb" })); // Robust Malformed JSON Syntax Error Guard app.use((err: any, _req: Request, res: Response, next: any) => { @@ -184,7 +187,7 @@ app.use((req, res, next) => { "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); } @@ -200,6 +203,9 @@ app.get("/favicon.ico", (_req, res) => { }); }); +// Standard MCP OAuth 2.1 + PKCE (S256) + RFC 9728 + RFC 8414 + RFC 7591 Dynamic Client Registration +registerOAuthRoutes(app); + app.use(optionalAuthMiddleware); @@ -420,6 +426,7 @@ app.get("/mcp", mcpLimiter, async (req: Request, res: Response) => { }); } if (!req.auraAuth?.authenticated) { + res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, req.auraAuth?.tenantId === "invalid")); return res.status(401).json( wrapError( new McpToolError({ diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts index e423966..9daf561 100644 --- a/src/middleware/auth.ts +++ b/src/middleware/auth.ts @@ -1,6 +1,7 @@ import { Request, Response, NextFunction } from "express"; import { createHash, createHmac, timingSafeEqual } from "node:crypto"; import { maskPhone, wrapError, McpToolError } from "../envelope.js"; +import { verifyOAuthAccessToken, buildWwwAuthenticateHeader } from "./oauth.js"; export type AuthScope = "read" | "write"; @@ -269,6 +270,21 @@ export function resolveAuthContext(req: Request): AuraAuthContext { }; } + // 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 { @@ -468,13 +484,14 @@ export function requireMcpAuth(req: Request, res: Response, next: NextFunction): 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", }) @@ -483,10 +500,8 @@ export function requireMcpAuth(req: Request, res: Response, next: NextFunction): return; } - // Allow unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping) + // 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 === "initialize" || - method === "notifications/initialized" || method === "tools/list" || method === "ping"; @@ -500,11 +515,12 @@ export function requireMcpAuth(req: Request, res: Response, next: NextFunction): } 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 header on /mcp. Please provide your API key or BYOK carrier keys.", + message: "Missing or invalid Authorization: Bearer header on /mcp. Authenticate via MCP OAuth 2.1 or provide your API key / BYOK carrier keys.", retryable: false, source: "validator", }) diff --git a/src/middleware/oauth.ts b/src/middleware/oauth.ts new file mode 100644 index 0000000..5dc62b1 --- /dev/null +++ b/src/middleware/oauth.ts @@ -0,0 +1,1206 @@ +import type { Express, Request, Response } from "express"; +import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import { resolveAuthContextAsync, type AuthScope } from "./auth.js"; + +const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour +const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability) +const AUTH_CODE_TTL_SEC = 300; // 5 minutes +const CSRF_TTL_SEC = 900; // 15 minutes +const VALID_SCOPES: AuthScope[] = ["read", "write"]; + +// In-memory replay & revocation guards (with periodic TTL pruning) +const usedAuthCodes = new Map(); // jti -> expiresAtMs +const revokedTokenIds = new Map(); // jti -> expiresAtMs + +setInterval(() => { + const now = Date.now(); + for (const [k, exp] of usedAuthCodes.entries()) { + if (now > exp) usedAuthCodes.delete(k); + } + for (const [k, exp] of revokedTokenIds.entries()) { + if (now > exp) revokedTokenIds.delete(k); + } +}, 5 * 60 * 1000).unref(); + +export interface OAuthAccessClaims { + iss: string; + aud: string; + sub: string; + adm: boolean; + scp: AuthScope[]; + cid: string; + typ: "at"; + iat: number; + exp: number; + jti: string; +} + +interface OAuthRefreshClaims { + iss: string; + aud: string; + sub: string; + adm: boolean; + scp: AuthScope[]; + cid: string; + typ: "rt"; + iat: number; + exp: number; + jti: string; +} + +interface OAuthCodeClaims { + cid: string; + ru: string; + cc: string; + ccm: "S256"; + scp: AuthScope[]; + sub: string; + adm: boolean; + res: string; + typ: "code"; + iat: number; + exp: number; + jti: string; +} + +interface DcrClientPayload { + n: string; + r: string[]; + m: "none" | "client_secret_post" | "client_secret_basic"; + iat: number; +} + +function getRootSecret(): string { + return ( + process.env.AURA_OAUTH_SECRET || + process.env.AURA_API_KEY || + process.env.COURIER_AUTH_TOKEN || + "aura_live_mcp_master_key_2026" + ); +} + +function deriveKey(purpose: string): Buffer { + return createHash("sha256") + .update(`aura-courier-mcp-oauth-v1:${purpose}:${getRootSecret()}`) + .digest(); +} + +function safeEqualStr(a: string, b: string): boolean { + const ba = Buffer.from(a); + const bb = Buffer.from(b); + if (ba.length !== bb.length) return false; + return timingSafeEqual(ba, bb); +} + +function signJwt(payload: Record, purpose: string): string { + const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url"); + const body = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signingInput = `${header}.${body}`; + const sig = createHmac("sha256", deriveKey(purpose)).update(signingInput).digest("base64url"); + return `${signingInput}.${sig}`; +} + +function verifyJwt( + token: string, + purpose: string, + expectedTyp: string +): T | null { + if (!token || typeof token !== "string") return null; + const parts = token.split("."); + if (parts.length !== 3) return null; + const [headerB64, bodyB64, sigB64] = parts; + if (!headerB64 || !bodyB64 || !sigB64) return null; + + try { + const header = JSON.parse(Buffer.from(headerB64, "base64url").toString("utf8")); + if (header?.alg !== "HS256") return null; + + const expectedSig = createHmac("sha256", deriveKey(purpose)) + .update(`${headerB64}.${bodyB64}`) + .digest("base64url"); + if (!safeEqualStr(sigB64, expectedSig)) return null; + + const payload = JSON.parse(Buffer.from(bodyB64, "base64url").toString("utf8")) as T; + if (!payload || payload.typ !== expectedTyp) return null; + + const nowSec = Math.floor(Date.now() / 1000); + if (typeof payload.exp !== "number" || payload.exp <= nowSec) return null; + + if (payload.jti && revokedTokenIds.has(payload.jti)) return null; + return payload; + } catch { + return null; + } +} + +export function verifyOAuthAccessToken(token: string): OAuthAccessClaims | null { + return verifyJwt(token, "access", "at"); +} + +function verifyOAuthRefreshToken(token: string): OAuthRefreshClaims | null { + return verifyJwt(token, "refresh", "rt"); +} + +export function getPublicOrigin(req: Request): string { + if (process.env.NODE_ENV !== "test" && process.env.PUBLIC_BASE_URL) { + return process.env.PUBLIC_BASE_URL.replace(/\/+$/, ""); + } + const fwdHost = req.headers["x-forwarded-host"]; + const rawHost = + (Array.isArray(fwdHost) ? fwdHost[0] : fwdHost) || + req.headers.host || + "courier.auraajenticai.cloud"; + const host = String(rawHost).split(",")[0].trim(); + + const fwdProto = req.headers["x-forwarded-proto"]; + let proto = (Array.isArray(fwdProto) ? fwdProto[0] : fwdProto) || req.protocol || "https"; + proto = String(proto).split(",")[0].trim().toLowerCase(); + + const isLocal = /^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i.test(host); + if (!isLocal && proto === "http") { + proto = "https"; + } + return `${proto}://${host}`; +} + +export function buildWwwAuthenticateHeader(req: Request, invalidToken = false): string { + const origin = getPublicOrigin(req); + const metaUrl = `${origin}/.well-known/oauth-protected-resource`; + if (invalidToken) { + return `Bearer realm="Aura Courier MCP", error="invalid_token", error_description="The access token is invalid or expired.", resource_metadata="${metaUrl}", scope="read write"`; + } + return `Bearer realm="Aura Courier MCP", resource_metadata="${metaUrl}", scope="read write"`; +} + +export function isAllowedRedirectUri(uri: string): boolean { + if (!uri || typeof uri !== "string" || uri.length > 2048) return false; + let parsed: URL; + try { + parsed = new URL(uri); + } catch { + return false; + } + if (parsed.hash || parsed.username || parsed.password) return false; + + const proto = parsed.protocol.toLowerCase(); + const host = parsed.hostname.toLowerCase(); + + // Desktop IDE & native MCP app custom URI schemes + if ( + proto === "cursor:" || + proto === "vscode:" || + proto === "vscode-insiders:" || + proto === "windsurf:" || + proto === "antigravity:" || + proto === "claude:" || + proto === "cline:" + ) { + return true; + } + + // RFC 8252 loopback redirect URIs for local CLIs & MCP Inspector + if ( + (proto === "http:" || proto === "https:") && + (host === "localhost" || host === "127.0.0.1" || host === "[::1]") + ) { + return true; + } + + if (proto !== "https:") return false; + + const trustedHostPatterns = [ + // Google / Gemini / AI Studio / Antigravity + /^(?:.+\.)?googleusercontent\.com$/, + /^(?:.+\.)?google\.com$/, + /^(?:.+\.)?googleapis\.com$/, + /^(?:.+\.)?google\.dev$/, + /^(?:.+\.)?antigravity\.google$/, + // Claude / Anthropic + /^(?:.+\.)?claude\.ai$/, + /^(?:.+\.)?anthropic\.com$/, + // OpenAI / ChatGPT + /^(?:.+\.)?chatgpt\.com$/, + /^(?:.+\.)?openai\.com$/, + // Aura & Snehalata Ecosystem + /^(?:.+\.)?auraajenticai\.cloud$/, + /^(?:.+\.)?snehalata\.com$/, + // MCP Directories & API Clients + /^(?:.+\.)?glama\.ai$/, + /^(?:.+\.)?smithery\.ai$/, + /^(?:.+\.)?modelcontextprotocol\.io$/, + /^(?:.+\.)?postman\.com$/, + /^(?:.+\.)?pstmn\.io$/, + /^(?:.+\.)?insomnia\.rest$/, + ]; + + return trustedHostPatterns.some((re) => re.test(host)); +} + +function encodeDcrClientId(payload: DcrClientPayload): string { + const b64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const sig = createHmac("sha256", deriveKey("client")).update(b64).digest("base64url").slice(0, 22); + return `aura_dcr_${b64}.${sig}`; +} + +function decodeDcrClientId(clientId: string): DcrClientPayload | null { + if (!clientId || !clientId.startsWith("aura_dcr_")) return null; + const raw = clientId.slice("aura_dcr_".length); + const dotIdx = raw.lastIndexOf("."); + if (dotIdx <= 0) return null; + const b64 = raw.slice(0, dotIdx); + const sig = raw.slice(dotIdx + 1); + const expected = createHmac("sha256", deriveKey("client")).update(b64).digest("base64url").slice(0, 22); + if (!safeEqualStr(sig, expected)) return null; + try { + const parsed = JSON.parse(Buffer.from(b64, "base64url").toString("utf8")) as DcrClientPayload; + if (!parsed || !Array.isArray(parsed.r) || parsed.r.length === 0) return null; + return parsed; + } catch { + return null; + } +} + +function deriveDcrClientSecret(clientId: string): string { + const digest = createHmac("sha256", deriveKey("client_secret")).update(clientId).digest("base64url"); + return `aura_cs_${digest.slice(0, 40)}`; +} + +function normalizeScopes(rawScope: string | undefined, allowedScopes: AuthScope[]): AuthScope[] { + const allowed = allowedScopes.length ? allowedScopes : (["read"] as AuthScope[]); + if (!rawScope || !rawScope.trim()) { + return [...allowed]; + } + const requested = rawScope + .trim() + .split(/[\s,]+/) + .map((s) => s.trim().toLowerCase().replace(/^mcp:/, "")) + .filter((s): s is AuthScope => VALID_SCOPES.includes(s as AuthScope)); + + if (requested.length === 0) { + return [...allowed]; + } + const granted = requested.filter((s) => allowed.includes(s)); + return granted.length > 0 ? Array.from(new Set(granted)) : [allowed[0]]; +} + +function verifyPkceS256(codeVerifier: string, expectedChallenge: string): boolean { + if (!codeVerifier || typeof codeVerifier !== "string" || codeVerifier.length < 43 || codeVerifier.length > 128) { + return false; + } + const computed = createHash("sha256").update(codeVerifier).digest("base64url"); + return safeEqualStr(computed, expectedChallenge); +} + +function signCsrfToken(fields: { + clientId: string; + redirectUri: string; + codeChallenge: string; + state: string; +}): string { + const exp = Math.floor(Date.now() / 1000) + CSRF_TTL_SEC; + const data = `${fields.clientId}|${fields.redirectUri}|${fields.codeChallenge}|${fields.state}|${exp}`; + const sig = createHmac("sha256", deriveKey("csrf")).update(data).digest("base64url").slice(0, 24); + return `${exp}.${sig}`; +} + +function verifyCsrfToken( + token: string, + fields: { clientId: string; redirectUri: string; codeChallenge: string; state: string } +): boolean { + if (!token || typeof token !== "string") return false; + const parts = token.split("."); + if (parts.length !== 2) return false; + const exp = Number(parts[0]); + if (!Number.isFinite(exp) || exp < Math.floor(Date.now() / 1000)) return false; + const data = `${fields.clientId}|${fields.redirectUri}|${fields.codeChallenge}|${fields.state}|${exp}`; + const expected = createHmac("sha256", deriveKey("csrf")).update(data).digest("base64url").slice(0, 24); + return safeEqualStr(parts[1], expected); +} + +function escapeHtml(str: any): string { + if (str == null) return ""; + return String(str) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function redirectWithOAuthError( + res: Response, + redirectUri: string, + error: string, + description: string, + state?: string +): void { + const u = new URL(redirectUri); + u.searchParams.set("error", error); + if (description) u.searchParams.set("error_description", description); + if (state) u.searchParams.set("state", state); + res.redirect(302, u.toString()); +} + +function extractClientCredentials(req: Request): { clientId?: string; clientSecret?: string } { + const body = (req.body || {}) as Record; + let clientId = typeof body.client_id === "string" ? body.client_id.trim() : undefined; + let clientSecret = typeof body.client_secret === "string" ? body.client_secret.trim() : undefined; + + const authHeader = req.headers["authorization"] || req.headers["Authorization"]; + if (typeof authHeader === "string" && authHeader.trim().toLowerCase().startsWith("basic ")) { + try { + const decoded = Buffer.from(authHeader.trim().slice(6).trim(), "base64").toString("utf8"); + const sep = decoded.indexOf(":"); + if (sep >= 0) { + const rawId = decoded.slice(0, sep); + const rawSec = decoded.slice(sep + 1); + try { + clientId = decodeURIComponent(rawId); + } catch { + clientId = rawId; + } + try { + clientSecret = decodeURIComponent(rawSec); + } catch { + clientSecret = rawSec; + } + } + } catch { + // Ignore malformed Basic header; fall back to body params + } + } + + return { clientId, clientSecret }; +} + +function renderConsentPage(opts: { + origin: string; + clientName: string; + redirectHost: string; + clientId: string; + redirectUri: string; + state: string; + scope: string; + codeChallenge: string; + codeChallengeMethod: string; + resource: string; + csrfToken: string; + errorMessage?: string; +}): string { + const scopes = opts.scope + ? opts.scope.split(/[\s,]+/).filter(Boolean) + : ["read", "write"]; + const hasWrite = scopes.some((s) => s.toLowerCase().includes("write")); + + return ` + + + + + Authorize ${escapeHtml(opts.clientName)} — Aura Courier MCP + + + + + + + +
+
+ Aura Courier MCP +
+

Aura Courier MCP

+

OAuth 2.1 + PKCE Merchant Authorization

+
+
+ +
+
+
${escapeHtml(opts.clientName)}
+
Redirect: ${escapeHtml(opts.redirectHost)}
+
+ PKCE S256 +
+ +
+
Requested Permissions
+
    +
  • Read: Track parcels, check COD balance, verify fraud risk, geocode addresses & compare courier rates.
  • + ${hasWrite ? `
  • Write: Book, update, or cancel parcels across Steadfast, Pathao, RedX & Paperfly (according to your key scope).
  • ` : ""} +
+
+ + ${opts.errorMessage ? `
${escapeHtml(opts.errorMessage)}
` : ""} + +
+ + + + + + + + + + +
+ + +
+
+ আপনার Aura Master Key, Tenant API Key, অথবা Snehalata snl_mcp_... কী দিন। Read-only টেস্টের জন্য: aura_ro_public_inspector_2026 +
+ +
+ + +
+
+ +
+ Secured by Aura Ajentic AI · Privacy Policy +
+
+ +`; +} + +function resolveClientMeta(clientId: string, redirectUri: string): { + valid: boolean; + clientName: string; + authMethod: "none" | "client_secret_post" | "client_secret_basic"; + error?: string; +} { + if (!clientId) { + return { valid: false, clientName: "Unknown Client", authMethod: "none", error: "Missing client_id." }; + } + if (!isAllowedRedirectUri(redirectUri)) { + return { + valid: false, + clientName: "Unknown Client", + authMethod: "none", + error: "redirect_uri is missing or not in the trusted OAuth redirect allowlist.", + }; + } + if (clientId.startsWith("aura_dcr_")) { + const dcr = decodeDcrClientId(clientId); + if (!dcr) { + return { + valid: false, + clientName: "Unknown Client", + authMethod: "none", + error: "Invalid or tampered dynamically registered client_id.", + }; + } + if (!dcr.r.includes(redirectUri)) { + return { + valid: false, + clientName: dcr.n || "MCP Client", + authMethod: dcr.m, + error: "redirect_uri does not match the client's registered redirect_uris.", + }; + } + return { valid: true, clientName: dcr.n || "MCP Client", authMethod: dcr.m }; + } + + // Allow non-DCR clients (e.g. Google Gemini / ChatGPT / Claude / local CLI) when redirect_uri is strictly allowlisted + let inferredName = clientId.slice(0, 48); + try { + const h = new URL(redirectUri).hostname.toLowerCase(); + if (h.includes("googleusercontent.com") || h.includes("google.com")) inferredName = "Google Gemini"; + else if (h.includes("claude.ai") || h.includes("anthropic.com")) inferredName = "Claude"; + else if (h.includes("chatgpt.com") || h.includes("openai.com")) inferredName = "ChatGPT"; + } catch {} + return { valid: true, clientName: inferredName, authMethod: "none" }; +} + +export function registerOAuthRoutes(app: Express): void { + // 1. RFC 9728 — OAuth 2.0 Protected Resource Metadata (root + /mcp path-inserted variant) + const protectedResourceHandler = (req: Request, res: Response) => { + const origin = getPublicOrigin(req); + res.setHeader("Cache-Control", "public, max-age=300"); + return res.json({ + resource: `${origin}/mcp`, + authorization_servers: [origin], + bearer_methods_supported: ["header"], + scopes_supported: ["read", "write"], + resource_name: "Aura Courier MCP", + resource_documentation: `${origin}/guide`, + }); + }; + app.get("/.well-known/oauth-protected-resource", protectedResourceHandler); + app.get("/.well-known/oauth-protected-resource/mcp", protectedResourceHandler); + + // 2. RFC 8414 — OAuth 2.0 Authorization Server Metadata (+ OIDC discovery fallback) + const authServerMetadataHandler = (req: Request, res: Response) => { + const origin = getPublicOrigin(req); + res.setHeader("Cache-Control", "public, max-age=300"); + return res.json({ + issuer: origin, + authorization_endpoint: `${origin}/oauth/authorize`, + token_endpoint: `${origin}/oauth/token`, + registration_endpoint: `${origin}/oauth/register`, + revocation_endpoint: `${origin}/oauth/revoke`, + response_types_supported: ["code"], + response_modes_supported: ["query"], + grant_types_supported: ["authorization_code", "refresh_token"], + token_endpoint_auth_methods_supported: ["none", "client_secret_post", "client_secret_basic"], + code_challenge_methods_supported: ["S256"], + scopes_supported: ["read", "write"], + service_documentation: `${origin}/guide`, + }); + }; + app.get("/.well-known/oauth-authorization-server", authServerMetadataHandler); + app.get("/.well-known/oauth-authorization-server/mcp", authServerMetadataHandler); + app.get("/.well-known/openid-configuration", authServerMetadataHandler); + + // 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof) + app.post("/oauth/register", (req: Request, res: Response) => { + res.setHeader("Cache-Control", "no-store"); + const body = (req.body || {}) as Record; + const rawUris = body.redirect_uris; + if (!Array.isArray(rawUris) || rawUris.length === 0 || rawUris.length > 8) { + return res.status(400).json({ + error: "invalid_client_metadata", + error_description: "redirect_uris must be a non-empty array (max 8 URIs).", + }); + } + + const redirectUris: string[] = []; + for (const u of rawUris) { + if (typeof u !== "string" || !isAllowedRedirectUri(u.trim())) { + return res.status(400).json({ + error: "invalid_redirect_uri", + error_description: `Redirect URI is not permitted: ${String(u)}`, + }); + } + redirectUris.push(u.trim()); + } + + const clientName = + typeof body.client_name === "string" && body.client_name.trim() + ? body.client_name.trim().slice(0, 64) + : "MCP Client"; + + const requestedAuthMethod = String(body.token_endpoint_auth_method || "none").trim(); + const authMethod: "none" | "client_secret_post" | "client_secret_basic" = + requestedAuthMethod === "client_secret_post" || requestedAuthMethod === "client_secret_basic" + ? requestedAuthMethod + : "none"; + + const iat = Math.floor(Date.now() / 1000); + const clientId = encodeDcrClientId({ + n: clientName, + r: redirectUris, + m: authMethod, + iat, + }); + + const responsePayload: Record = { + client_id: clientId, + client_id_issued_at: iat, + client_name: clientName, + redirect_uris: redirectUris, + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + token_endpoint_auth_method: authMethod, + }; + + if (authMethod !== "none") { + responsePayload.client_secret = deriveDcrClientSecret(clientId); + responsePayload.client_secret_expires_at = 0; + } + + return res.status(201).json(responsePayload); + }); + + // 4. OAuth 2.1 Authorization Endpoint (GET Consent UI) + app.get("/oauth/authorize", (req: Request, res: Response) => { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("X-Frame-Options", "DENY"); + res.setHeader("Content-Security-Policy", "frame-ancestors 'none'"); + + const q = (req.query || {}) as Record; + const responseType = String(q.response_type || "").trim(); + const clientId = String(q.client_id || "").trim(); + const redirectUri = String(q.redirect_uri || "").trim(); + const state = String(q.state || "").trim(); + const scope = String(q.scope || "read write").trim(); + const codeChallenge = String(q.code_challenge || "").trim(); + const codeChallengeMethod = String(q.code_challenge_method || "S256").trim(); + const resource = String(q.resource || "").trim(); + + const clientCheck = resolveClientMeta(clientId, redirectUri); + if (!clientCheck.valid) { + return res.status(400).json({ + error: "invalid_request", + error_description: clientCheck.error || "Invalid client_id or redirect_uri.", + }); + } + + if (responseType !== "code") { + return redirectWithOAuthError( + res, + redirectUri, + "unsupported_response_type", + "Only response_type=code is supported.", + state + ); + } + + if (!codeChallenge || codeChallenge.length < 43 || codeChallenge.length > 128) { + return redirectWithOAuthError( + res, + redirectUri, + "invalid_request", + "PKCE code_challenge (S256) is required by OAuth 2.1.", + state + ); + } + + if (codeChallengeMethod !== "S256") { + return redirectWithOAuthError( + res, + redirectUri, + "invalid_request", + "Only PKCE code_challenge_method=S256 is supported.", + state + ); + } + + const origin = getPublicOrigin(req); + let redirectHost = redirectUri; + try { + redirectHost = new URL(redirectUri).host || redirectUri; + } catch {} + + const csrfToken = signCsrfToken({ + clientId, + redirectUri, + codeChallenge, + state, + }); + + return res.status(200).type("html").send( + renderConsentPage({ + origin, + clientName: clientCheck.clientName, + redirectHost, + clientId, + redirectUri, + state, + scope, + codeChallenge, + codeChallengeMethod: "S256", + resource: resource || `${origin}/mcp`, + csrfToken, + }) + ); + }); + + // 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission) + app.post("/oauth/authorize", async (req: Request, res: Response) => { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("X-Frame-Options", "DENY"); + res.setHeader("Content-Security-Policy", "frame-ancestors 'none'"); + + const b = (req.body || {}) as Record; + const clientId = String(b.client_id || "").trim(); + const redirectUri = String(b.redirect_uri || "").trim(); + const state = String(b.state || "").trim(); + const scope = String(b.scope || "read write").trim(); + const codeChallenge = String(b.code_challenge || "").trim(); + const codeChallengeMethod = String(b.code_challenge_method || "S256").trim(); + const resource = String(b.resource || "").trim(); + const csrfToken = String(b.csrf_token || "").trim(); + const decision = String(b.decision || "approve").trim().toLowerCase(); + const apiKey = String(b.api_key || "").trim(); + + const clientCheck = resolveClientMeta(clientId, redirectUri); + if (!clientCheck.valid) { + return res.status(400).json({ + error: "invalid_request", + error_description: clientCheck.error || "Invalid client_id or redirect_uri.", + }); + } + + if ( + !codeChallenge || + codeChallengeMethod !== "S256" || + !verifyCsrfToken(csrfToken, { clientId, redirectUri, codeChallenge, state }) + ) { + return redirectWithOAuthError( + res, + redirectUri, + "invalid_request", + "Authorization session expired or invalid. Please retry connecting.", + state + ); + } + + if (decision === "deny") { + return redirectWithOAuthError( + res, + redirectUri, + "access_denied", + "The user denied the authorization request.", + state + ); + } + + const origin = getPublicOrigin(req); + let redirectHost = redirectUri; + try { + redirectHost = new URL(redirectUri).host || redirectUri; + } catch {} + + const renderFailure = (errorMessage: string) => { + const freshCsrf = signCsrfToken({ clientId, redirectUri, codeChallenge, state }); + return res.status(200).type("html").send( + renderConsentPage({ + origin, + clientName: clientCheck.clientName, + redirectHost, + clientId, + redirectUri, + state, + scope, + codeChallenge, + codeChallengeMethod: "S256", + resource: resource || `${origin}/mcp`, + csrfToken: freshCsrf, + errorMessage, + }) + ); + }; + + if (!apiKey) { + return renderFailure("Please enter your Aura API Key, Tenant Key, or Snehalata snl_mcp_... key."); + } + + // Validate submitted API key against ALL live auth backends (Master, Read-Only, Dynamic PG, Env, Snehalata) + const syntheticReq = { + headers: { authorization: `Bearer ${apiKey}` }, + query: {}, + } as unknown as Request; + + const authCtx = await resolveAuthContextAsync(syntheticReq); + if (!authCtx.authenticated) { + return renderFailure( + authCtx.deniedReason || "Invalid API Key. Please check your Aura API Key or Snehalata MCP Key and try again." + ); + } + + const grantedScopes = normalizeScopes(scope, authCtx.scopes); + const nowSec = Math.floor(Date.now() / 1000); + const codeClaims: OAuthCodeClaims = { + cid: clientId, + ru: redirectUri, + cc: codeChallenge, + ccm: "S256", + scp: grantedScopes, + sub: authCtx.tenantId, + adm: authCtx.isAdmin, + res: resource || `${origin}/mcp`, + typ: "code", + iat: nowSec, + exp: nowSec + AUTH_CODE_TTL_SEC, + jti: randomBytes(16).toString("base64url"), + }; + + const code = signJwt(codeClaims, "code"); + const callback = new URL(redirectUri); + callback.searchParams.set("code", code); + if (state) callback.searchParams.set("state", state); + + return res.redirect(302, callback.toString()); + }); + + // 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token) + app.post("/oauth/token", (req: Request, res: Response) => { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("Pragma", "no-cache"); + + const b = (req.body || {}) as Record; + const grantType = String(b.grant_type || "").trim(); + const { clientId, clientSecret } = extractClientCredentials(req); + + // If DCR client registered as confidential (client_secret_*), verify secret + if (clientId && clientId.startsWith("aura_dcr_")) { + const dcr = decodeDcrClientId(clientId); + if (!dcr) { + return res.status(401).json({ + error: "invalid_client", + error_description: "Unknown or invalid client_id.", + }); + } + if (dcr.m !== "none") { + const expectedSecret = deriveDcrClientSecret(clientId); + if (!clientSecret || !safeEqualStr(clientSecret, expectedSecret)) { + return res.status(401).json({ + error: "invalid_client", + error_description: "Invalid client_secret.", + }); + } + } + } + + const origin = getPublicOrigin(req); + + if (grantType === "authorization_code") { + const code = String(b.code || "").trim(); + const codeVerifier = String(b.code_verifier || "").trim(); + const redirectUri = typeof b.redirect_uri === "string" ? b.redirect_uri.trim() : ""; + + if (!code || !codeVerifier) { + return res.status(400).json({ + error: "invalid_request", + error_description: "Both code and PKCE code_verifier are required.", + }); + } + + const codeClaims = verifyJwt(code, "code", "code"); + if (!codeClaims) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "Authorization code is invalid or expired.", + }); + } + + if (usedAuthCodes.has(codeClaims.jti)) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "Authorization code has already been used.", + }); + } + + if (clientId && codeClaims.cid !== clientId) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "client_id does not match authorization code.", + }); + } + + if (redirectUri && codeClaims.ru !== redirectUri) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "redirect_uri does not match authorization code.", + }); + } + + if (!verifyPkceS256(codeVerifier, codeClaims.cc)) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "PKCE S256 code_verifier verification failed.", + }); + } + + // Enforce single-use authorization code + usedAuthCodes.set(codeClaims.jti, Date.now() + AUTH_CODE_TTL_SEC * 1000 * 2); + + const nowSec = Math.floor(Date.now() / 1000); + const accessClaims: OAuthAccessClaims = { + iss: origin, + aud: codeClaims.res || `${origin}/mcp`, + sub: codeClaims.sub, + adm: codeClaims.adm, + scp: codeClaims.scp, + cid: codeClaims.cid, + typ: "at", + iat: nowSec, + exp: nowSec + ACCESS_TOKEN_TTL_SEC, + jti: randomBytes(16).toString("base64url"), + }; + const refreshClaims: OAuthRefreshClaims = { + iss: origin, + aud: codeClaims.res || `${origin}/mcp`, + sub: codeClaims.sub, + adm: codeClaims.adm, + scp: codeClaims.scp, + cid: codeClaims.cid, + typ: "rt", + iat: nowSec, + exp: nowSec + REFRESH_TOKEN_TTL_SEC, + jti: randomBytes(16).toString("base64url"), + }; + + const accessToken = signJwt(accessClaims, "access"); + const refreshToken = signJwt(refreshClaims, "refresh"); + + return res.status(200).json({ + access_token: accessToken, + token_type: "Bearer", + expires_in: ACCESS_TOKEN_TTL_SEC, + refresh_token: refreshToken, + scope: codeClaims.scp.join(" "), + }); + } + + if (grantType === "refresh_token") { + const refreshToken = String(b.refresh_token || "").trim(); + if (!refreshToken) { + return res.status(400).json({ + error: "invalid_request", + error_description: "refresh_token is required.", + }); + } + + const rtClaims = verifyOAuthRefreshToken(refreshToken); + if (!rtClaims) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "Refresh token is invalid, expired, or revoked.", + }); + } + + if (clientId && rtClaims.cid !== clientId) { + return res.status(400).json({ + error: "invalid_grant", + error_description: "client_id does not match refresh token.", + }); + } + + const nowSec = Math.floor(Date.now() / 1000); + const accessClaims: OAuthAccessClaims = { + iss: origin, + aud: rtClaims.aud || `${origin}/mcp`, + sub: rtClaims.sub, + adm: rtClaims.adm, + scp: rtClaims.scp, + cid: rtClaims.cid, + typ: "at", + iat: nowSec, + exp: nowSec + ACCESS_TOKEN_TTL_SEC, + jti: randomBytes(16).toString("base64url"), + }; + + const accessToken = signJwt(accessClaims, "access"); + + // IMPORTANT FOR GOOGLE GEMINI: Keep refresh_token NON-ROTATING so Gemini never unlinks! + return res.status(200).json({ + access_token: accessToken, + token_type: "Bearer", + expires_in: ACCESS_TOKEN_TTL_SEC, + refresh_token: refreshToken, + scope: rtClaims.scp.join(" "), + }); + } + + return res.status(400).json({ + error: "unsupported_grant_type", + error_description: "Supported grant_types: authorization_code, refresh_token.", + }); + }); + + // 7. RFC 7009 — Token Revocation Endpoint + app.post("/oauth/revoke", (req: Request, res: Response) => { + res.setHeader("Cache-Control", "no-store"); + const b = (req.body || {}) as Record; + const token = String(b.token || "").trim(); + if (token) { + const at = verifyOAuthAccessToken(token); + if (at?.jti) { + revokedTokenIds.set(at.jti, at.exp * 1000 + 60_000); + } + const rt = verifyOAuthRefreshToken(token); + if (rt?.jti) { + revokedTokenIds.set(rt.jti, rt.exp * 1000 + 60_000); + } + } + return res.status(200).json({ revoked: true }); + }); +} diff --git a/test/oauth21.test.mjs b/test/oauth21.test.mjs new file mode 100644 index 0000000..e977524 --- /dev/null +++ b/test/oauth21.test.mjs @@ -0,0 +1,444 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { createHash, randomBytes } from "node:crypto"; + +process.env.NODE_ENV = "test"; +process.env.AURA_API_KEY = "aura_test_master_key_oauth21"; +process.env.AURA_READONLY_KEY = "aura_ro_test_reader_oauth21"; +process.env.STEADFAST_API_KEY = "sf_test_key"; +process.env.STEADFAST_SECRET_KEY = "sf_test_secret"; + +const { app } = await import("../dist/http.js"); +const { SteadfastAdapter } = await import("../dist/adapters/steadfast.js"); + +SteadfastAdapter.prototype.getBalance = async function () { + return { + courier: "steadfast", + status: "OK", + amount_bdt: 14250, + raw_response: { status: 200, current_balance: 14250 }, + }; +}; + +let server; +let baseUrl; + +function makePkcePair() { + const verifier = randomBytes(32).toString("base64url"); + const challenge = createHash("sha256").update(verifier).digest("base64url"); + return { verifier, challenge }; +} + +function extractHiddenInput(html, name) { + const re = new RegExp(`name="${name}"\\s+value="([^"]*)"`, "i"); + const m = html.match(re); + return m ? m[1] : ""; +} + +test.before(async () => { + server = http.createServer(app); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const addr = server.address(); + baseUrl = `http://127.0.0.1:${addr.port}`; +}); + +test.after(async () => { + if (server) { + await new Promise((resolve) => server.close(resolve)); + } +}); + +test("OAuth 1: 401 on unauthenticated POST /mcp (initialize & tools/call) and GET /mcp includes RFC 9728 WWW-Authenticate header", async () => { + const initRes = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "Google Gemini", version: "1.0" } }, + }), + }); + assert.equal(initRes.status, 401); + const wwwAuthInit = initRes.headers.get("www-authenticate") || ""; + assert.ok(wwwAuthInit.includes("Bearer")); + assert.ok(wwwAuthInit.includes(`resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"`)); + assert.ok((initRes.headers.get("access-control-expose-headers") || "").includes("WWW-Authenticate")); + + const getRes = await fetch(`${baseUrl}/mcp`, { + method: "GET", + headers: { Accept: "text/event-stream" }, + }); + assert.equal(getRes.status, 401); + assert.ok((getRes.headers.get("www-authenticate") || "").includes(`resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"`)); +}); + +test("OAuth 2: RFC 9728 Protected Resource Metadata & RFC 8414 Authorization Server Metadata endpoints return valid JSON", async () => { + for (const p of ["/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp"]) { + const res = await fetch(`${baseUrl}${p}`); + assert.equal(res.status, 200); + const data = await res.json(); + assert.equal(data.resource, `${baseUrl}/mcp`); + assert.deepEqual(data.authorization_servers, [baseUrl]); + assert.ok(data.bearer_methods_supported.includes("header")); + } + + for (const p of ["/.well-known/oauth-authorization-server", "/.well-known/openid-configuration"]) { + const res = await fetch(`${baseUrl}${p}`); + assert.equal(res.status, 200); + const data = await res.json(); + assert.equal(data.issuer, baseUrl); + assert.equal(data.authorization_endpoint, `${baseUrl}/oauth/authorize`); + assert.equal(data.token_endpoint, `${baseUrl}/oauth/token`); + assert.equal(data.registration_endpoint, `${baseUrl}/oauth/register`); + assert.ok(data.code_challenge_methods_supported.includes("S256")); + assert.ok(data.grant_types_supported.includes("authorization_code")); + assert.ok(data.grant_types_supported.includes("refresh_token")); + } +}); + +test("OAuth 3: RFC 7591 Dynamic Client Registration allows Google googleusercontent.com redirect URIs & blocks untrusted hosts", async () => { + const goodRes = await fetch(`${baseUrl}/oauth/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + client_name: "Google Gemini MCP", + redirect_uris: ["https://oauth-redirect.googleusercontent.com/r/gemini-aura-test"], + token_endpoint_auth_method: "none", + }), + }); + assert.equal(goodRes.status, 201); + const client = await goodRes.json(); + assert.ok(client.client_id.startsWith("aura_dcr_")); + assert.deepEqual(client.redirect_uris, ["https://oauth-redirect.googleusercontent.com/r/gemini-aura-test"]); + + const badRes = await fetch(`${baseUrl}/oauth/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + client_name: "Untrusted Phish", + redirect_uris: ["https://evil.example.com/steal-code"], + }), + }); + assert.equal(badRes.status, 400); + const badBody = await badRes.json(); + assert.equal(badBody.error, "invalid_redirect_uri"); +}); + +test("OAuth 4: End-to-End Gemini PKCE S256 flow -> OAuth Bearer /mcp -> Non-Rotating Refresh -> Static Dual-Auth -> Revocation", async () => { + const redirectUri = "https://oauth-redirect.googleusercontent.com/r/gemini-live-flow"; + const regRes = await fetch(`${baseUrl}/oauth/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + client_name: "Google Gemini", + redirect_uris: [redirectUri], + token_endpoint_auth_method: "none", + }), + }); + assert.equal(regRes.status, 201); + const { client_id: clientId } = await regRes.json(); + + const { verifier, challenge } = makePkcePair(); + const state = "gemini_state_xyz_991"; + + // Step 4a: GET /oauth/authorize consent screen + const authUrl = new URL(`${baseUrl}/oauth/authorize`); + authUrl.searchParams.set("response_type", "code"); + authUrl.searchParams.set("client_id", clientId); + authUrl.searchParams.set("redirect_uri", redirectUri); + authUrl.searchParams.set("scope", "read write"); + authUrl.searchParams.set("state", state); + authUrl.searchParams.set("code_challenge", challenge); + authUrl.searchParams.set("code_challenge_method", "S256"); + + const consentRes = await fetch(authUrl.toString()); + assert.equal(consentRes.status, 200); + const consentHtml = await consentRes.text(); + assert.ok(consentHtml.includes("Google Gemini")); + assert.ok(consentHtml.includes("oauth-redirect.googleusercontent.com")); + const csrfToken = extractHiddenInput(consentHtml, "csrf_token"); + assert.ok(csrfToken.length > 10); + + // Step 4b: Deny redirects with error=access_denied + const denyForm = new URLSearchParams({ + client_id: clientId, + redirect_uri: redirectUri, + state, + scope: "read write", + code_challenge: challenge, + code_challenge_method: "S256", + csrf_token: csrfToken, + decision: "deny", + }); + const denyRes = await fetch(`${baseUrl}/oauth/authorize`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: denyForm.toString(), + redirect: "manual", + }); + assert.equal(denyRes.status, 302); + const denyLoc = new URL(denyRes.headers.get("location")); + assert.equal(denyLoc.searchParams.get("error"), "access_denied"); + assert.equal(denyLoc.searchParams.get("state"), state); + + // Step 4c: Invalid API key stays on consent form with error message + const badKeyForm = new URLSearchParams({ + client_id: clientId, + redirect_uri: redirectUri, + state, + scope: "read write", + code_challenge: challenge, + code_challenge_method: "S256", + csrf_token: csrfToken, + decision: "approve", + api_key: "totally_wrong_key_123", + }); + const badKeyRes = await fetch(`${baseUrl}/oauth/authorize`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: badKeyForm.toString(), + redirect: "manual", + }); + assert.equal(badKeyRes.status, 200); + const badKeyHtml = await badKeyRes.text(); + assert.ok(badKeyHtml.includes("Invalid API Key")); + + // Step 4d: Valid Master Key redirects 302 with single-use authorization code + const okForm = new URLSearchParams({ + client_id: clientId, + redirect_uri: redirectUri, + state, + scope: "read write", + code_challenge: challenge, + code_challenge_method: "S256", + csrf_token: csrfToken, + decision: "approve", + api_key: process.env.AURA_API_KEY, + }); + const approveRes = await fetch(`${baseUrl}/oauth/authorize`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: okForm.toString(), + redirect: "manual", + }); + assert.equal(approveRes.status, 302); + const cbUrl = new URL(approveRes.headers.get("location")); + assert.equal(cbUrl.origin + cbUrl.pathname, redirectUri); + assert.equal(cbUrl.searchParams.get("state"), state); + const authCode = cbUrl.searchParams.get("code"); + assert.ok(authCode && authCode.split(".").length === 3); + + // Step 4e: Wrong PKCE code_verifier is rejected + const wrongPkceRes = await fetch(`${baseUrl}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: authCode, + client_id: clientId, + redirect_uri: redirectUri, + code_verifier: "wrong_verifier_abcdefghijklmnopqrstuvwxyz_0123456789", + }).toString(), + }); + assert.equal(wrongPkceRes.status, 400); + assert.equal((await wrongPkceRes.json()).error, "invalid_grant"); + + // Step 4f: Correct PKCE code_verifier issues access_token + refresh_token + const tokRes = await fetch(`${baseUrl}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: authCode, + client_id: clientId, + redirect_uri: redirectUri, + code_verifier: verifier, + }).toString(), + }); + assert.equal(tokRes.status, 200); + const tokens = await tokRes.json(); + assert.equal(tokens.token_type, "Bearer"); + assert.equal(tokens.expires_in, 3600); + assert.ok(tokens.access_token && tokens.access_token.startsWith("eyJ")); + assert.ok(tokens.refresh_token && tokens.refresh_token.startsWith("eyJ")); + assert.equal(tokens.scope, "read write"); + + // Step 4g: Authorization code replay is rejected + const replayRes = await fetch(`${baseUrl}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: authCode, + client_id: clientId, + redirect_uri: redirectUri, + code_verifier: verifier, + }).toString(), + }); + assert.equal(replayRes.status, 400); + assert.equal((await replayRes.json()).error, "invalid_grant"); + + // Step 4h: Call /mcp initialize & tools/call with OAuth Bearer token + const mcpInit = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + Authorization: `Bearer ${tokens.access_token}`, + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 10, + method: "initialize", + params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "Google Gemini", version: "1.0" } }, + }), + }); + assert.equal(mcpInit.status, 200); + assert.ok(mcpInit.headers.get("mcp-session-id")); + + const mcpCall = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + Authorization: `Bearer ${tokens.access_token}`, + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 11, + method: "tools/call", + params: { name: "get_balance", arguments: { courier: "steadfast" } }, + }), + }); + assert.equal(mcpCall.status, 200); + const mcpBody = await mcpCall.json(); + assert.equal(mcpBody.result.isError, false); + const env = JSON.parse(mcpBody.result.content[0].text); + assert.equal(env.data.amount_bdt, 14250); + + // Step 4i: Refresh token returns fresh access_token AND keeps refresh_token NON-ROTATING for Gemini + const refreshRes = await fetch(`${baseUrl}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: tokens.refresh_token, + client_id: clientId, + }).toString(), + }); + assert.equal(refreshRes.status, 200); + const refreshed = await refreshRes.json(); + assert.ok(refreshed.access_token && refreshed.access_token !== tokens.access_token); + assert.equal(refreshed.refresh_token, tokens.refresh_token); + + // Step 4j: Existing static Bearer API Key still works identically (Dual-Auth) + const staticRes = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${process.env.AURA_API_KEY}`, + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 12, + method: "tools/call", + params: { name: "get_balance", arguments: { courier: "steadfast" } }, + }), + }); + assert.equal(staticRes.status, 200); + + // Step 4k: Revoke OAuth access_token -> subsequent /mcp returns 401 with error="invalid_token" + const revRes = await fetch(`${baseUrl}/oauth/revoke`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ token: tokens.access_token }).toString(), + }); + assert.equal(revRes.status, 200); + + const afterRev = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${tokens.access_token}`, + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 13, + method: "tools/call", + params: { name: "get_balance", arguments: { courier: "steadfast" } }, + }), + }); + assert.equal(afterRev.status, 401); + assert.ok((afterRev.headers.get("www-authenticate") || "").includes('error="invalid_token"')); +}); + +test("OAuth 5: Read-Only key authorization strictly limits OAuth JWT to read scope", async () => { + const redirectUri = "https://oauth-redirect.googleusercontent.com/r/gemini-ro-check"; + const { verifier, challenge } = makePkcePair(); + + const authUrl = new URL(`${baseUrl}/oauth/authorize`); + authUrl.searchParams.set("response_type", "code"); + authUrl.searchParams.set("client_id", "gemini-ro-client"); + authUrl.searchParams.set("redirect_uri", redirectUri); + authUrl.searchParams.set("scope", "read write"); + authUrl.searchParams.set("state", "st_ro"); + authUrl.searchParams.set("code_challenge", challenge); + authUrl.searchParams.set("code_challenge_method", "S256"); + + const consentHtml = await (await fetch(authUrl.toString())).text(); + const csrfToken = extractHiddenInput(consentHtml, "csrf_token"); + + const approveRes = await fetch(`${baseUrl}/oauth/authorize`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + client_id: "gemini-ro-client", + redirect_uri: redirectUri, + state: "st_ro", + scope: "read write", + code_challenge: challenge, + code_challenge_method: "S256", + csrf_token: csrfToken, + decision: "approve", + api_key: process.env.AURA_READONLY_KEY, + }).toString(), + redirect: "manual", + }); + assert.equal(approveRes.status, 302); + const code = new URL(approveRes.headers.get("location")).searchParams.get("code"); + + const tokRes = await fetch(`${baseUrl}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code, + client_id: "gemini-ro-client", + redirect_uri: redirectUri, + code_verifier: verifier, + }).toString(), + }); + assert.equal(tokRes.status, 200); + const tokens = await tokRes.json(); + assert.equal(tokens.scope, "read"); + + const writeAttempt = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${tokens.access_token}`, + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 14, + method: "tools/call", + params: { name: "create_parcel", arguments: { courier: "steadfast" } }, + }), + }); + assert.equal(writeAttempt.status, 200); + const writeBody = await writeAttempt.json(); + assert.equal(writeBody.result.isError, true); + assert.ok(writeBody.result.content[0].text.includes("Insufficient scope")); +}); diff --git a/test/v260.test.mjs b/test/v260.test.mjs index f8b56d4..8223352 100644 --- a/test/v260.test.mjs +++ b/test/v260.test.mjs @@ -439,7 +439,7 @@ test("11. GET /health unauthenticated returns only { ok, version }; with admin t const adminBody = await adminRes.json(); assert.equal(adminBody.ok, true); assert.equal(adminBody.version, expectedVersion); - assert.equal(adminBody.tools_count, 12); + assert.equal(adminBody.tools_count, 13); assert.ok(adminBody.performance); }); @@ -811,7 +811,7 @@ test("24. Upstream Cancellation: Steadfast cancelParcel handles already-cancelle } }); -test("25. AI Connector: Unauthenticated tools/list discovery succeeds and lists 12 tools", async () => { +test("25. AI Connector: Unauthenticated tools/list discovery succeeds and lists 13 tools", async () => { const res = await fetch(`${baseUrl}/mcp`, { method: "POST", headers: { "Content-Type": "application/json" }, @@ -821,5 +821,5 @@ test("25. AI Connector: Unauthenticated tools/list discovery succeeds and lists const body = await res.json(); assert.equal(body.jsonrpc, "2.0"); assert.ok(Array.isArray(body.result.tools)); - assert.equal(body.result.tools.length, 12); + assert.equal(body.result.tools.length, 13); });