/** * MCP Auth Flow * * High-level OAuth flow management using the MCP SDK's built-in auth functions. */ import { auth as runSdkAuth, UnauthorizedError, } from "@modelcontextprotocol/sdk/client/auth.js" import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js" import open from "open" import { McpOAuthProvider, type McpOAuthConfig } from "./mcp-oauth-provider.ts" import { ensureCallbackServer, waitForCallback, cancelPendingCallback, stopCallbackServerIfIdle, releaseCallbackServer, } from "./mcp-callback-server.ts" import { createMcpAuth, fileMcpAuthStorage, type McpAuthStorage, type StoredTokens } from "./mcp-auth.ts" import type { ServerEntry } from "./types.ts" /** Auth status for a server */ export type AuthStatus = "authenticated" | "expired" | "not_authenticated" export interface AuthenticateOptions { onAuthorizationUrl?: (authorizationUrl: string) => void | Promise } interface PendingOAuth { owner: object; state: string; active: boolean; transport?: StreamableHTTPClientTransport; timer?: ReturnType; start?: Promise<{ authorizationUrl: string }>; authentication?: Promise; } interface AuthContext { pending: Map; authentications: Map>; } // Credential identity and per-server deduplication are shared; lifecycle owners are not. const contexts = new WeakMap(); export function createMcpAuthFlow(storage: McpAuthStorage): McpAuthFlow { if (!storage) throw new Error("MCP auth storage is required"); let context = contexts.get(storage); if (!context) { context = { pending: new Map(), authentications: new Map() }; contexts.set(storage, context); } return buildMcpAuthFlow(storage, context); } export type McpAuthFlow = ReturnType; function buildMcpAuthFlow(storage: McpAuthStorage, context: AuthContext) { const owner = {}; const { getAuthForUrl, isTokenExpired, hasStoredTokens, clearAllCredentials, resetRegistration, updateOAuthState, getOAuthState, clearOAuthState } = createMcpAuth(storage); const pendingAuthentications = context.authentications; /** Timeout for manual auth completion (5 minutes) */ const MANUAL_AUTH_TIMEOUT_MS = 5 * 60 * 1000 /** * Generate a cryptographically secure random state parameter. */ function generateState(): string { return Array.from(crypto.getRandomValues(new Uint8Array(32))) .map((b) => b.toString(16).padStart(2, "0")) .join("") } /** * Extract OAuth configuration from a ServerEntry. */ function extractOAuthConfig(definition: ServerEntry): McpOAuthConfig { if (definition.oauth === false) { return {} } const config: McpOAuthConfig = {} if (definition.oauth?.grantType !== undefined) config.grantType = definition.oauth.grantType if (definition.oauth?.clientId !== undefined) config.clientId = definition.oauth.clientId if (definition.oauth?.clientSecret !== undefined) config.clientSecret = definition.oauth.clientSecret if (definition.oauth?.scope !== undefined) config.scope = definition.oauth.scope if (definition.oauth?.redirectUri !== undefined) { if (typeof definition.oauth.redirectUri !== "string") { throw new Error("OAuth redirectUri must be a string") } const redirectUri = definition.oauth.redirectUri.trim() if (!redirectUri) { throw new Error("OAuth redirectUri must not be empty") } config.redirectUri = redirectUri } if (definition.oauth?.clientName !== undefined) { if (typeof definition.oauth.clientName !== "string") { throw new Error("OAuth clientName must be a string") } const clientName = definition.oauth.clientName.trim() if (!clientName) { throw new Error("OAuth clientName must not be empty") } config.clientName = clientName } if (definition.oauth?.clientUri !== undefined) { if (typeof definition.oauth.clientUri !== "string") { throw new Error("OAuth clientUri must be a string") } const clientUri = definition.oauth.clientUri.trim() if (!clientUri) { throw new Error("OAuth clientUri must not be empty") } config.clientUri = clientUri } return config } function parseOAuthRedirectUri(redirectUri: string): { port: number; callbackHost: string; callbackPath: string } { let url: URL try { url = new URL(redirectUri) } catch (error) { throw new Error(`Invalid OAuth redirectUri: ${redirectUri}`, { cause: error }) } const hostname = url.hostname.toLowerCase() const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1" if (url.protocol !== "http:" || !isLocalhost) { throw new Error("OAuth redirectUri must be an http:// localhost or loopback URI") } if (url.username || url.password) { throw new Error("OAuth redirectUri must not include username or password") } if (url.hash) { throw new Error("OAuth redirectUri must not include a fragment") } if (!url.port) { throw new Error("OAuth redirectUri must include an explicit numeric port") } const port = Number.parseInt(url.port, 10) if (!Number.isInteger(port) || port <= 0 || port > 65535) { throw new Error("OAuth redirectUri must include an explicit numeric port") } const callbackHost = hostname === "[::1]" ? "::1" : hostname return { port, callbackHost, callbackPath: url.pathname } } /** * Start OAuth authentication flow for a server. * Returns the authorization URL when browser authorization is required. */ async function startAuth( serverName: string, serverUrl: string, definition?: ServerEntry ): Promise<{ authorizationUrl: string }> { const existing = context.pending.get(serverName); if (existing?.start) return existing.start; const pending: PendingOAuth = { owner, state: generateState(), active: true }; context.pending.set(serverName, pending); pending.start = beginAuth(serverName, serverUrl, definition, pending); return pending.start; } function assertActive(pending: PendingOAuth): void { if (!pending.active) throw new Error("Authorization cancelled"); } async function beginAuth(serverName: string, serverUrl: string, definition: ServerEntry | undefined, pending: PendingOAuth): Promise<{ authorizationUrl: string }> { try { return await beginAuthActive(serverName, serverUrl, definition, pending); } catch (error) { try { await clearPendingAuth(serverName, pending); } catch (cleanupError) { throw new AggregateError([error, cleanupError], "OAuth authorization and cleanup failed"); } throw error; } } async function beginAuthActive(serverName: string, serverUrl: string, definition: ServerEntry | undefined, pending: PendingOAuth): Promise<{ authorizationUrl: string }> { const config = definition ? extractOAuthConfig(definition) : {} if (config.grantType === "client_credentials") { const storedAuth = getAuthForUrl(serverName, serverUrl) if (storedAuth?.clientInfo && !storedAuth.tokens && !config.clientId) { resetRegistration(serverName) } const authProvider = new McpOAuthProvider(serverName, serverUrl, config, { onRedirect: async () => { throw new Error("Browser redirect is not used for client_credentials flow") }, }, storage) assertActive(pending) const result = await runSdkAuth(authProvider, { serverUrl }) assertActive(pending) if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize") } await clearPendingAuth(serverName, pending) return { authorizationUrl: "" } } const redirectCallback = config.redirectUri !== undefined ? parseOAuthRedirectUri(config.redirectUri) : undefined const oauthState = pending.state await ensureCallbackServer({ strictPort: Boolean(config.clientId) || config.redirectUri !== undefined, oauthState, reserveState: true, ...(redirectCallback ? { port: redirectCallback.port, callbackHost: redirectCallback.callbackHost, callbackPath: redirectCallback.callbackPath } : {}), }) assertActive(pending) let capturedUrl: URL | undefined const authProvider = new McpOAuthProvider(serverName, serverUrl, config, { onRedirect: async (url) => { capturedUrl = url }, }, storage) { const storedAuth = getAuthForUrl(serverName, serverUrl) if (storedAuth?.clientInfo && !config.clientId) { if (!storedAuth.tokens) { resetRegistration(serverName) } else { const redirectUris = storedAuth.clientInfo.redirectUris if (!Array.isArray(redirectUris) || !redirectUris.includes(authProvider.redirectUrl ?? "")) { resetRegistration(serverName) } } } assertActive(pending) updateOAuthState(serverName, oauthState, serverUrl) const result = await runSdkAuth(authProvider, { serverUrl }) assertActive(pending) if (result === "AUTHORIZED") { await clearPendingAuth(serverName, pending) return { authorizationUrl: "" } } if (!capturedUrl) { throw new UnauthorizedError("OAuth authorization URL was not provided") } const pendingTransport = new StreamableHTTPClientTransport(new URL(serverUrl), { authProvider }) pending.transport = pendingTransport pending.timer = setTimeout(() => { void clearPendingAuth(serverName, pending).catch((error) => { console.error("MCP OAuth timeout cleanup failed", error) }) }, MANUAL_AUTH_TIMEOUT_MS) pending.timer.unref?.() return { authorizationUrl: capturedUrl.toString() } } } async function clearPendingAuth(serverName: string, pending: PendingOAuth): Promise { pending.active = false if (pendingAuthentications.get(serverName) === pending.authentication) pendingAuthentications.delete(serverName) if (context.pending.get(serverName) === pending) context.pending.delete(serverName) if (pending.timer) clearTimeout(pending.timer) pending.timer = undefined const transport = pending.transport pending.transport = undefined // Do not let storage or one transport's failure skip any owned resource. const results = await Promise.allSettled([ (async () => { try { storage.transaction(() => { if (getOAuthState(serverName) === pending.state) clearOAuthState(serverName) }) } finally { cancelPendingCallback(pending.state) releaseCallbackServer(pending.state) await stopCallbackServerIfIdle() } })(), (async () => { await transport?.close() })(), ]) const errors = results.filter((result): result is PromiseRejectedResult => result.status === "rejected").map((result) => result.reason) if (errors.length) throw new AggregateError(errors, "OAuth cleanup failed") } function getSearchParamsFromInput(input: string): URLSearchParams | undefined { try { const url = new URL(input) const params = new URLSearchParams(url.search) if (url.hash) { const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash const hashParams = new URLSearchParams(hash) for (const [key, value] of hashParams) { if (!params.has(key)) params.set(key, value) } } return params } catch { const query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input const params = new URLSearchParams(query.startsWith("#") ? query.slice(1) : query) return params.has("code") || params.has("state") || params.has("error") ? params : undefined } } /** * Extract an OAuth authorization code from either a raw code, a query string, * or the full localhost redirect URL copied from the browser address bar. */ function parseAuthorizationCodeInput(input: string, expectedState?: string): string { const trimmed = input.trim() if (!trimmed) { throw new Error("Authorization code or redirect URL is required") } const params = getSearchParamsFromInput(trimmed) if (params) { const error = params.get("error") if (error) { const description = params.get("error_description") throw new Error(description ? `${error}: ${description}` : error) } const state = params.get("state") if (expectedState && !state) { throw new Error("OAuth state missing from redirect URL") } if (expectedState && state !== expectedState) { throw new Error("OAuth state mismatch - potential CSRF attack") } const code = params.get("code") if (code) return code } if (/^[A-Za-z0-9._~+/=-]+$/.test(trimmed)) { return trimmed } throw new Error("Could not find an OAuth authorization code in the provided input") } /** * Complete OAuth authentication from manual user input. */ async function completeAuthFromInput( serverName: string, input: string, ): Promise { const oauthState = await getOAuthState(serverName) const code = parseAuthorizationCodeInput(input, oauthState) return completeAuth(serverName, code) } /** * Complete OAuth authentication with the authorization code. */ async function completeAuth( serverName: string, authorizationCode: string ): Promise { const pending = context.pending.get(serverName) if (!pending?.transport) { throw new Error(`No pending OAuth flow for server: ${serverName}`) } try { await pending.transport.finishAuth(authorizationCode) return "authenticated" } finally { await clearPendingAuth(serverName, pending) } } /** * Perform the complete OAuth authentication flow for a server. * * @param serverName - The name of the MCP server * @param serverUrl - The URL of the MCP server * @param definition - The server definition (optional) * @returns The final auth status */ async function authenticate( serverName: string, serverUrl: string, definition?: ServerEntry, options: AuthenticateOptions = {}, ): Promise { const inFlight = pendingAuthentications.get(serverName) if (inFlight) { return inFlight } const operation = (async (): Promise => { // Start auth flow const started = startAuth(serverName, serverUrl, definition) const pending = context.pending.get(serverName)! const { authorizationUrl } = await started // If no auth URL needed, already authenticated if (!authorizationUrl) { return "authenticated" } const oauthState = pending.state try { assertActive(pending) // Attach a rejection handler immediately, even while URL notification/open awaits. const callbackPromise = waitForCallback(oauthState) void callbackPromise.catch(() => {}) // Open browser. Always surface the URL first so remote/headless users can copy it // even when the OS browser handoff is unavailable or invisible. if (options.onAuthorizationUrl) { await options.onAuthorizationUrl(authorizationUrl) } else { console.log(`MCP Auth: Open this URL to authenticate ${serverName}:\n${authorizationUrl}`) } assertActive(pending) try { await open(authorizationUrl) } catch (error) { console.warn(`MCP Auth: Failed to open browser for ${serverName}; waiting for manual callback`, { error }) } // Wait for callback const code = await callbackPromise // Validate/clear atomically, without clearing a replacement flow's state. assertActive(pending) storage.transaction(() => { if (getOAuthState(serverName) !== oauthState) { throw new Error("OAuth state mismatch - potential CSRF attack") } clearOAuthState(serverName) }) // Complete the auth return await completeAuth(serverName, code) } catch (error) { cancelPendingCallback(oauthState) await clearPendingAuth(serverName, pending) throw error } })() const pending = context.pending.get(serverName) if (pending) pending.authentication = operation pendingAuthentications.set(serverName, operation) try { return await operation } finally { if (pendingAuthentications.get(serverName) === operation) { pendingAuthentications.delete(serverName) } } } /** * Get a valid access token for a server, refreshing if necessary. * * @param serverName - The name of the MCP server * @param serverUrl - The URL of the MCP server * @returns The valid tokens or null if not authenticated */ async function getValidToken( serverName: string, serverUrl: string, ): Promise { // Check if we have valid tokens const entry = await getAuthForUrl(serverName, serverUrl) if (!entry?.tokens) { return null } // Check expiration const expired = await isTokenExpired(serverName) if (expired === false) { return entry.tokens } if (expired === true && entry.tokens.refreshToken) { // Token is expired, try to refresh console.log(`MCP Auth: Token expired for ${serverName}, attempting refresh`) try { // Create auth provider for token refresh const authProvider = new McpOAuthProvider(serverName, serverUrl, {}, { onRedirect: async () => {}, }, storage) const clientInfo = await authProvider.clientInformation() if (!clientInfo) { console.log(`MCP Auth: No client info for refresh for ${serverName}`) return null } const result = await runSdkAuth(authProvider, { serverUrl }) if (result !== "AUTHORIZED") { return null } const refreshed = await getAuthForUrl(serverName, serverUrl) return refreshed?.tokens ?? null } catch (error) { console.error(`MCP Auth: Token refresh failed for ${serverName}`, { error }) return null } } // No expiration info or no refresh token, assume valid return entry.tokens } /** * Check the authentication status for a server. * * @param serverName - The name of the MCP server * @returns The current auth status */ async function getAuthStatus(serverName: string): Promise { const hasTokens = await hasStoredTokens(serverName) if (!hasTokens) return "not_authenticated" const expired = await isTokenExpired(serverName) return expired ? "expired" : "authenticated" } /** * Remove all OAuth credentials for a server. * * @param serverName - The name of the MCP server */ async function removeAuth(serverName: string): Promise { const pending = context.pending.get(serverName) if (pending) { await clearPendingAuth(serverName, pending) } else { // Logout is an explicit credential-wide action, unlike instance shutdown. const state = getOAuthState(serverName) if (state) { cancelPendingCallback(state) releaseCallbackServer(state) await stopCallbackServerIfIdle() } } clearAllCredentials(serverName) await clearOAuthState(serverName) console.log(`MCP Auth: Removed credentials for ${serverName}`) } /** * Check if OAuth is supported for a server configuration. * OAuth is supported for HTTP servers unless explicitly disabled. * * @param definition - The server definition * @returns True if OAuth is supported */ function supportsOAuth(definition: ServerEntry): boolean { // OAuth requires a URL if (!definition.url) return false // Explicitly disabled via auth: false or oauth: false if (definition.auth === false) return false if (definition.oauth === false) return false if (definition.auth === "oauth") return true // Configured custom headers take precedence over implicit OAuth auto-detection. if (definition.headers && Object.keys(definition.headers).length > 0) return false // OAuth is enabled when auth is not specified (auto-detect) return definition.auth === undefined } /** * Initialize the OAuth system on startup. * OAuth callback binding is lazy and starts from startAuth() only. */ async function initializeOAuth(): Promise {} /** * Shutdown the OAuth system. * Cancels only this instance’s pending auths; releases the listener when idle. */ async function shutdownOAuth(): Promise { const results = await Promise.allSettled( Array.from(context.pending.entries()) .filter(([, pending]) => pending.owner === owner) .map(([serverName, pending]) => clearPendingAuth(serverName, pending)), ) const errors = results.filter((result): result is PromiseRejectedResult => result.status === "rejected").map((result) => result.reason) if (errors.length) throw new AggregateError(errors, "OAuth shutdown cleanup failed") } return { extractOAuthConfig, startAuth, parseAuthorizationCodeInput, completeAuthFromInput, completeAuth, authenticate, getValidToken, getAuthStatus, removeAuth, supportsOAuth, initializeOAuth, shutdownOAuth }; } export const { extractOAuthConfig, startAuth, parseAuthorizationCodeInput, completeAuthFromInput, completeAuth, authenticate, getValidToken, getAuthStatus, removeAuth, supportsOAuth, initializeOAuth, shutdownOAuth } = createMcpAuthFlow(fileMcpAuthStorage);