|
| 1 | +import { createRemoteJWKSet, jwtVerify, JWTPayload } from "jose"; |
| 2 | + |
| 3 | +export interface AuthConfig { |
| 4 | + DISABLE_AUTH: boolean; |
| 5 | + AUTH_TOKEN_MODE: "introspection" | "jwt"; |
| 6 | + OAUTH_INTROSPECT_URL: string; |
| 7 | + JWT_ISSUER?: string; |
| 8 | + JWT_AUDIENCE?: string; |
| 9 | + JWT_JWKS_URL?: string; |
| 10 | +} |
| 11 | + |
| 12 | +export interface AuthResult { |
| 13 | + clientId: string; |
| 14 | + scopes: string[]; |
| 15 | + expiresAt: number; |
| 16 | +} |
| 17 | + |
| 18 | +// Bearer auth supporting either introspection (opaque tokens) or JWT validation (JWKS) |
| 19 | +export async function verifyAccessToken(token: string, config: AuthConfig, expectedResource?: string): Promise<AuthResult> { |
| 20 | + if (!config.DISABLE_AUTH) return { clientId: "dev", scopes: [], expiresAt: Math.floor(Date.now() / 1000) + 3600 }; |
| 21 | + |
| 22 | + if (config.AUTH_TOKEN_MODE === "jwt") { |
| 23 | + if (!config.JWT_JWKS_URL) throw new Error("JWT_JWKS_URL or JWT_ISSUER required for JWT mode"); |
| 24 | + const JWKS = createRemoteJWKSet(new URL(config.JWT_JWKS_URL)); |
| 25 | + const { payload } = await jwtVerify(token, JWKS, { |
| 26 | + issuer: config.JWT_ISSUER, |
| 27 | + audience: config.JWT_AUDIENCE, |
| 28 | + algorithms: ["RS256"] |
| 29 | + }); |
| 30 | + |
| 31 | + const scopes = parseScopes(payload); |
| 32 | + const exp = typeof payload.exp === "number" ? payload.exp : Math.floor(Date.now() / 1000) + 3600; |
| 33 | + if (expectedResource && payload.aud && typeof payload.aud === "string" && payload.aud !== expectedResource) { |
| 34 | + console.warn(`[auth] audience mismatch: token.aud="${payload.aud}" expected="${expectedResource}"`); |
| 35 | + throw new Error("Token not intended for this resource"); |
| 36 | + } |
| 37 | + return { |
| 38 | + clientId: (payload.client_id as string) || (payload.sub as string) || "unknown", |
| 39 | + scopes, |
| 40 | + expiresAt: exp, |
| 41 | + }; |
| 42 | + } else { |
| 43 | + // Use external introspection (opaque tokens) |
| 44 | + const res = await fetch(config.OAUTH_INTROSPECT_URL, { |
| 45 | + method: "POST", |
| 46 | + headers: { "Content-Type": "application/x-www-form-urlencoded" }, |
| 47 | + body: new URLSearchParams({ token }).toString() |
| 48 | + }); |
| 49 | + if (!res.ok) throw new Error(`Introspection failed: ${res.status}`); |
| 50 | + const data = await res.json(); |
| 51 | + if (!data.active) throw new Error("Token inactive"); |
| 52 | + |
| 53 | + if (expectedResource && data.aud && data.aud !== expectedResource) { |
| 54 | + console.warn(`[auth] audience mismatch: token.aud="${data.aud}" expected="${expectedResource}"`); |
| 55 | + throw new Error("Token not intended for this resource"); |
| 56 | + } |
| 57 | + return { |
| 58 | + clientId: data.client_id ?? "unknown", |
| 59 | + scopes: (data.scope ? String(data.scope).split(" ") : []) as string[], |
| 60 | + expiresAt: typeof data.exp === "number" ? data.exp : Math.floor(Date.now() / 1000) + 3600 |
| 61 | + }; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +export function parseScopes(payload: JWTPayload): string[] { |
| 66 | + const raw = (payload.scope as string) || (payload.scp as string) || undefined; |
| 67 | + if (!raw) return []; |
| 68 | + return String(raw).split(" ").filter(Boolean); |
| 69 | +} |
| 70 | + |
| 71 | +export function createAuthMiddleware(config: AuthConfig) { |
| 72 | + return async (req: any, res: any, next: any) => { |
| 73 | + if (config.DISABLE_AUTH) return next(); |
| 74 | + |
| 75 | + const baseUrl = `${req.protocol}://${req.get('host')}`; |
| 76 | + // Prefer configured audience to avoid http/https host-derived mismatches |
| 77 | + const expectedResource = config.JWT_AUDIENCE || `${baseUrl}/mcp`; |
| 78 | + const resourceMetadataUrl = `${baseUrl}/.well-known/oauth-protected-resource`; |
| 79 | + |
| 80 | + try { |
| 81 | + const auth = req.headers.authorization; |
| 82 | + if (!auth) { |
| 83 | + console.warn(`[auth] missing authorization for ${req.method} ${req.originalUrl}`); |
| 84 | + res.set('WWW-Authenticate', `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp:tools"`); |
| 85 | + return res.status(401).json({ error: "missing_authorization" }); |
| 86 | + } |
| 87 | + const [type, token] = auth.split(" "); |
| 88 | + if (!token || type.toLowerCase() !== "bearer") { |
| 89 | + console.warn(`[auth] invalid authorization header for ${req.method} ${req.originalUrl}: ${auth}`); |
| 90 | + res.set('WWW-Authenticate', `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp:tools"`); |
| 91 | + return res.status(401).json({ error: "invalid_authorization" }); |
| 92 | + } |
| 93 | + const info = await verifyAccessToken(token, config, expectedResource); |
| 94 | + if (info.expiresAt < Math.floor(Date.now() / 1000)) { |
| 95 | + console.warn(`[auth] token expired for client ${info.clientId}`); |
| 96 | + res.set('WWW-Authenticate', `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp:tools"`); |
| 97 | + return res.status(401).json({ error: "token_expired" }); |
| 98 | + } |
| 99 | + req.auth = info; |
| 100 | + next(); |
| 101 | + } catch (e: any) { |
| 102 | + console.warn(`[auth] invalid_token on ${req.method} ${req.originalUrl}: ${e?.message || e}`); |
| 103 | + res.set('WWW-Authenticate', `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp:tools"`); |
| 104 | + return res.status(401).json({ error: "invalid_token", message: String(e?.message ?? e) }); |
| 105 | + } |
| 106 | + }; |
| 107 | +} |
| 108 | + |
0 commit comments