UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

149 lines • 8.11 kB
import { loadMcpSdkAuth } from "../sdk.lazy.js"; import { safeDelay } from "../wrap.js"; import { isInvalidGrant, isTransientTokenError, OAuthFlowError } from "./oauth-errors.js"; import { oauthFetch } from "./oauth-fetch.js"; import { canonicalAuthorizationServerIssuer, credentialsMatchIssuer, validatedAuthorizationServerIssuer, } from "./oauth-issuer.js"; import { mergeTokensIntoStoredAuth, storedAuthToTokens, storedGrantIssuer, validGrantProof, withGrantAuthorization, } from "./oauth-grant.js"; const REFRESH_LEEWAY_MS = 5 * 60 * 1000; export function isTokenStale(record, now) { const token = record?.accessToken; if (token === undefined || token.length === 0) return true; if (record?.expiresAt === undefined) return false; return record.expiresAt - now <= REFRESH_LEEWAY_MS; } export function assertS256Supported(metadata, serverName) { const methods = metadata?.code_challenge_methods_supported; if (methods === undefined || !methods.includes("S256")) { throw new OAuthFlowError("s256_unsupported", `MCP server ${serverName} authorization server does not advertise PKCE S256 (code_challenge_methods_supported); refusing to authorize without proof-key protection.`, { serverName }); } } // Coalesces refresh across in-process callers (single promise) and across // processes (token-store lock). Preemptive at expiry - 5min. export class McpRefreshManager { #provider; #options; #inflight; constructor(provider, options = {}) { this.#provider = provider; this.#options = options; } async ensureFresh() { const record = await this.#provider.store.readAsync(); if (record?.accessToken === undefined) return undefined; if (!isTokenStale(record, Date.now())) return storedAuthToTokens(record); return this.refresh(); } refresh() { if (this.#inflight !== undefined) return this.#inflight; const run = this.#refreshLocked().finally(() => { this.#inflight = undefined; }); this.#inflight = run; return run; } #refreshLocked() { return this.#provider.store.withLock(async () => { const current = this.#provider.store.readUnlocked(); if (current?.accessToken !== undefined && !isTokenStale(current, Date.now())) { const tokens = storedAuthToTokens(current); if (tokens !== undefined) return tokens; } const refreshToken = current?.refreshToken; if (current === undefined || refreshToken === undefined) { throw new OAuthFlowError("needs_auth", `MCP server ${this.#provider.serverName} has no refresh token`, { serverName: this.#provider.serverName, }); } return this.#doRefresh(current, refreshToken); }); } async #doRefresh(current, refreshToken) { const info = await this.#discover(); // senpi#2940: a refresh token is presented only to the authorization server that issued it. A grant bound // elsewhere, or one that cannot be attributed at all, is a continuity break: drop it and require a fresh // sign-in rather than refreshing silently against whatever server discovery now names. const issuer = storedGrantIssuer(current); const authorizationServer = validatedAuthorizationServerIssuer(info, this.#provider.serverName); if (issuer === undefined || !credentialsMatchIssuer(current, authorizationServer)) { this.#provider.store.writeUnlocked(undefined); throw new OAuthFlowError("needs_auth", issuer === undefined ? `MCP server ${this.#provider.serverName} has a saved sign-in with no record of the authorization server that issued it; credentials cleared, re-authentication required.` : `MCP server ${this.#provider.serverName} now uses authorization server ${authorizationServer}, but its saved sign-in was issued by ${issuer}; credentials cleared, re-authentication required.`, { serverName: this.#provider.serverName }); } const clientInformation = this.#provider.clientInformation(); if (clientInformation === undefined) { throw new OAuthFlowError("needs_auth", `MCP server ${this.#provider.serverName} is not registered`, { serverName: this.#provider.serverName, }); } const resource = new URL(current.resource ?? this.#provider.serverUrl); const proof = validGrantProof(current, this.#provider.grantContext); const { refreshAuthorization } = await loadMcpSdkAuth(); const maxRetries = this.#options.maxRetries ?? 2; for (let attempt = 0;; attempt++) { try { const tokens = await refreshAuthorization(info.authorizationServerUrl, { metadata: info.authorizationServerMetadata, clientInformation, refreshToken, resource, fetchFn: oauthFetch(this.#options.fetchFn), }); if (tokens.issuer !== undefined && canonicalAuthorizationServerIssuer(tokens.issuer) !== canonicalAuthorizationServerIssuer(authorizationServer)) { this.#provider.store.writeUnlocked(undefined); throw new OAuthFlowError("needs_auth", "MCP refresh response names a different issuer.", { serverName: this.#provider.serverName, }); } const next = mergeTokensIntoStoredAuth({ ...current, issuer: authorizationServer, resource: resource.href, refreshScope: proof?.refreshScope }, { ...tokens, issuer: authorizationServer, scope: tokens.scope === undefined ? proof?.refreshScope : tokens.scope, }); const committed = withGrantAuthorization(next, this.#provider.grantContext, current); this.#provider.store.writeUnlocked(committed); const result = storedAuthToTokens(committed); if (result === undefined) throw new OAuthFlowError("needs_auth", "MCP refresh returned no access token."); return result; } catch (error) { if (error instanceof OAuthFlowError) throw error; if (isInvalidGrant(error)) { // Terminal: drop credentials so the next use forces a clean re-auth. this.#provider.store.writeUnlocked(undefined); throw new OAuthFlowError("invalid_grant", `MCP server ${this.#provider.serverName} refresh rejected (invalid_grant); credentials cleared, re-authentication required.`, { cause: error, serverName: this.#provider.serverName, }); } if (isTransientTokenError(error) && attempt < maxRetries) { await safeDelay(this.#options.retryDelayMs ?? 50); continue; } // Transient but exhausted: surface without clearing credentials (needs_auth NOT set). throw new OAuthFlowError("transient", `MCP server ${this.#provider.serverName} token refresh failed transiently; will retry on next use.`, { cause: error, retriable: true, serverName: this.#provider.serverName, }); } } } async #discover() { if (this.#options.discover !== undefined) return this.#options.discover(this.#provider.serverUrl); const { discoverOAuthServerInfo } = await loadMcpSdkAuth(); return discoverOAuthServerInfo(this.#provider.serverUrl, { fetchFn: oauthFetch(this.#options.fetchFn) }); } } //# sourceMappingURL=oauth-refresh.js.map