/** * OAuth sign-in for MCP servers (MCP authorization, 2025-06-18), so a server that wants an account * works without copying tokens around. * * The flow, as the spec describes it: * 1. Ask the server without credentials. A 401 names its protected-resource metadata * (RFC 9728) in WWW-Authenticate; otherwise the well-known locations are tried. * 2. The metadata names an authorization server, whose metadata (RFC 8414 or OpenID * discovery) gives the authorize, token and registration endpoints. * 3. This app registers itself with dynamic client registration (RFC 7591), unless the owner * entered a client id for servers that need a pre-registered app. * 4. Authorization code with PKCE (S256) and the resource indicator (RFC 8707). The browser * goes to the authorize page and comes back to /api/ai/mcp/oauth/callback. * 5. Tokens are stored encrypted on the server entry and refreshed when they expire. */ import crypto from 'node:crypto'; export interface OAuthClient { clientId: string; clientSecret?: string; authMethod: 'none' | 'client_secret_post' | 'client_secret_basic'; /** The redirect URI and authorization server the registration belongs to. */ redirectUri: string; issuer: string; } export interface OAuthTokens { accessToken: string; refreshToken?: string; /** Epoch ms; null when the server did not say. */ expiresAt: number | null; scope?: string; tokenEndpoint: string; clientId: string; clientSecret?: string; authMethod: OAuthClient['authMethod']; resource?: string; connectedAt: number; } export interface OAuthDiscovery { /** The resource the token is for (from the protected-resource metadata). */ resource: string; issuer: string; authorizationEndpoint: string; tokenEndpoint: string; registrationEndpoint?: string; scopes: string[]; authMethods: string[]; } export class OAuthError extends Error { constructor(message: string) { super(message); this.name = 'OAuthError'; } } const TIMEOUT_MS = 12_000; const PENDING_TTL_MS = 15 * 60_000; async function getJson(url: string, signal?: AbortSignal): Promise | null> { try { const res = await fetch(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]), redirect: 'follow' }); if (!res.ok) { await res.body?.cancel().catch(() => undefined); return null; } const data = (await res.json().catch(() => null)) as unknown; return data && typeof data === 'object' && !Array.isArray(data) ? (data as Record) : null; } catch { return null; } } /** Reads `key="value"` pairs from a WWW-Authenticate Bearer challenge. */ export function parseChallenge(header: string | null): Record { const out: Record = {}; if (!header) return out; for (const m of header.matchAll(/([a-zA-Z_]+)\s*=\s*(?:"([^"]*)"|([^\s,]+))/g)) out[m[1].toLowerCase()] = m[2] ?? m[3] ?? ''; return out; } /** Sends an unauthenticated initialize so the server can answer with its 401 challenge. */ async function probe(url: string, signal?: AbortSignal): Promise<{ status: number; challenge: Record }> { try { const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-06-18' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'study-desk', version: '2' } } }), signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]), }); await res.body?.cancel().catch(() => undefined); return { status: res.status, challenge: parseChallenge(res.headers.get('www-authenticate')) }; } catch (err) { throw new OAuthError(`Could not reach the server: ${err instanceof Error ? err.message : 'network error'}`); } } const trimSlash = (p: string) => p.replace(/\/+$/, ''); export async function discoverOAuth(serverUrl: string, signal?: AbortSignal): Promise { const target = new URL(serverUrl); const { challenge } = await probe(serverUrl, signal); const path = trimSlash(target.pathname); const prmCandidates = [challenge.resource_metadata, `${target.origin}/.well-known/oauth-protected-resource${path}${target.search}`, `${target.origin}/.well-known/oauth-protected-resource${path}`, `${target.origin}/.well-known/oauth-protected-resource`].filter( (u, i, all): u is string => Boolean(u) && all.indexOf(u) === i, ); let prm: Record | null = null; for (const u of prmCandidates) { prm = await getJson(u, signal); if (prm && Array.isArray(prm.authorization_servers) && prm.authorization_servers.length) break; prm = null; } const issuer = trimSlash(String(prm?.authorization_servers?.[0] ?? target.origin)); const as = new URL(issuer); const asPath = trimSlash(as.pathname); const asCandidates = asPath ? [`${as.origin}/.well-known/oauth-authorization-server${asPath}`, `${as.origin}/.well-known/openid-configuration${asPath}`, `${as.origin}${asPath}/.well-known/openid-configuration`, `${as.origin}${asPath}/.well-known/oauth-authorization-server`] : [`${as.origin}/.well-known/oauth-authorization-server`, `${as.origin}/.well-known/openid-configuration`]; let meta: Record | null = null; for (const u of asCandidates) { meta = await getJson(u, signal); if (meta?.authorization_endpoint && meta?.token_endpoint) break; meta = null; } if (!meta && !prm) { // Servers from before the 2025-06-18 spec: endpoints at fixed paths on the server's origin. const probeAuth = await getJson(`${target.origin}/.well-known/oauth-authorization-server`, signal); if (!probeAuth) throw new OAuthError('This server does not offer an OAuth sign-in. If it uses an API key, add it as a header instead.'); meta = probeAuth; } const authorizationEndpoint = String(meta?.authorization_endpoint ?? `${as.origin}/authorize`); const tokenEndpoint = String(meta?.token_endpoint ?? `${as.origin}/token`); const scopes = challenge.scope ? challenge.scope.split(/\s+/).filter(Boolean) : Array.isArray(prm?.scopes_supported) ? prm.scopes_supported.map(String) : []; return { resource: String(prm?.resource ?? serverUrl), issuer, authorizationEndpoint, tokenEndpoint, registrationEndpoint: meta?.registration_endpoint ? String(meta.registration_endpoint) : meta ? undefined : `${as.origin}/register`, scopes, authMethods: Array.isArray(meta?.token_endpoint_auth_methods_supported) ? meta.token_endpoint_auth_methods_supported.map(String) : ['client_secret_basic'], }; } export async function registerClient(d: OAuthDiscovery, redirectUri: string, signal?: AbortSignal): Promise { if (!d.registrationEndpoint) throw new OAuthError('This server needs a pre-registered OAuth app. Enter its client ID in the server settings, then sign in again.'); let res: Response; try { res = await fetch(d.registrationEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ client_name: 'Study Desk', redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', ...(d.scopes.length ? { scope: d.scopes.join(' ') } : {}), }), signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]), }); } catch (err) { throw new OAuthError(`Could not register with the sign-in server: ${err instanceof Error ? err.message : 'network error'}`); } const body = (await res.json().catch(() => null)) as Record | null; if (!res.ok || !body?.client_id) throw new OAuthError(`The sign-in server refused to register this app (HTTP ${res.status}${body?.error_description ? `: ${body.error_description}` : body?.error ? `: ${body.error}` : ''}).`); const secret = typeof body.client_secret === 'string' && body.client_secret ? body.client_secret : undefined; const method = String(body.token_endpoint_auth_method ?? (secret ? 'client_secret_basic' : 'none')); return { clientId: String(body.client_id), clientSecret: secret, authMethod: method === 'client_secret_post' ? 'client_secret_post' : method === 'client_secret_basic' && secret ? 'client_secret_basic' : secret ? 'client_secret_post' : 'none', redirectUri, issuer: d.issuer, }; } const b64url = (buf: Buffer) => buf.toString('base64url'); interface Pending { serverId: string; verifier: string; discovery: OAuthDiscovery; client: OAuthClient; returnTo: string; expires: number; } const pending = new Map(); /** Starts a sign-in: remembers the PKCE verifier under a random state and returns the authorize URL. */ export function beginAuthorization(serverId: string, d: OAuthDiscovery, client: OAuthClient, returnTo: string): string { const at = Date.now(); for (const [k, v] of pending) if (v.expires < at) pending.delete(k); const verifier = b64url(crypto.randomBytes(32)); const challenge = b64url(crypto.createHash('sha256').update(verifier).digest()); const state = b64url(crypto.randomBytes(24)); pending.set(state, { serverId, verifier, discovery: d, client, returnTo, expires: at + PENDING_TTL_MS }); const url = new URL(d.authorizationEndpoint); url.searchParams.set('response_type', 'code'); url.searchParams.set('client_id', client.clientId); url.searchParams.set('redirect_uri', client.redirectUri); url.searchParams.set('code_challenge', challenge); url.searchParams.set('code_challenge_method', 'S256'); url.searchParams.set('state', state); url.searchParams.set('resource', d.resource); if (d.scopes.length) url.searchParams.set('scope', d.scopes.join(' ')); return url.toString(); } /** Looks up (and consumes) a pending sign-in by its state. */ export function takePending(state: string): Pending | null { const p = pending.get(state); pending.delete(state); return p && p.expires > Date.now() ? p : null; } async function tokenRequest(endpoint: string, params: Record, client: Pick): Promise> { const headers: Record = { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }; const body = new URLSearchParams(params); if (client.authMethod === 'client_secret_basic' && client.clientSecret) { headers.Authorization = `Basic ${Buffer.from(`${encodeURIComponent(client.clientId)}:${encodeURIComponent(client.clientSecret)}`).toString('base64')}`; } else { body.set('client_id', client.clientId); if (client.clientSecret) body.set('client_secret', client.clientSecret); } let res: Response; try { res = await fetch(endpoint, { method: 'POST', headers, body, signal: AbortSignal.timeout(TIMEOUT_MS) }); } catch (err) { throw new OAuthError(`Could not reach the sign-in server: ${err instanceof Error ? err.message : 'network error'}`); } const text = await res.text(); let data: Record | null = null; try { data = JSON.parse(text) as Record; } catch { // Some servers answer form-encoded even when asked for JSON. const form = new URLSearchParams(text); if (form.has('access_token') || form.has('error')) data = Object.fromEntries(form); } if (!res.ok || !data?.access_token) throw new OAuthError(`Sign-in failed${data?.error_description ? `: ${data.error_description}` : data?.error ? `: ${data.error}` : ` (HTTP ${res.status})`}.`); return data; } function tokensFrom(data: Record, base: Omit, previous?: OAuthTokens): OAuthTokens { const expiresIn = Number(data.expires_in); return { ...base, accessToken: String(data.access_token), refreshToken: typeof data.refresh_token === 'string' && data.refresh_token ? data.refresh_token : previous?.refreshToken, expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? Date.now() + expiresIn * 1000 : null, scope: typeof data.scope === 'string' ? data.scope : previous?.scope, connectedAt: previous?.connectedAt ?? Date.now(), }; } export async function exchangeCode(p: Pending, code: string): Promise { const data = await tokenRequest( p.discovery.tokenEndpoint, { grant_type: 'authorization_code', code, redirect_uri: p.client.redirectUri, code_verifier: p.verifier, resource: p.discovery.resource }, p.client, ); return tokensFrom(data, { tokenEndpoint: p.discovery.tokenEndpoint, clientId: p.client.clientId, clientSecret: p.client.clientSecret, authMethod: p.client.authMethod, resource: p.discovery.resource }); } export async function refreshTokens(t: OAuthTokens): Promise { if (!t.refreshToken) throw new OAuthError('The sign-in expired. Sign in again in Settings.'); const data = await tokenRequest(t.tokenEndpoint, { grant_type: 'refresh_token', refresh_token: t.refreshToken, ...(t.resource ? { resource: t.resource } : {}) }, t); return tokensFrom(data, { tokenEndpoint: t.tokenEndpoint, clientId: t.clientId, clientSecret: t.clientSecret, authMethod: t.authMethod, resource: t.resource }, t); } /** Exposed for tests. */ export function clearPendingAuthorizations(): void { pending.clear(); }