@mcp-z/client 1.1.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/cjs/auth/capability-discovery.js +18 -8
- package/dist/cjs/auth/capability-discovery.js.map +1 -1
- package/dist/cjs/auth/discovery-fetch.d.cts +35 -0
- package/dist/cjs/auth/discovery-fetch.d.ts +35 -0
- package/dist/cjs/auth/discovery-fetch.js +658 -0
- package/dist/cjs/auth/discovery-fetch.js.map +1 -0
- package/dist/cjs/auth/index.d.cts +1 -0
- package/dist/cjs/auth/index.d.ts +1 -0
- package/dist/cjs/auth/index.js +7 -0
- package/dist/cjs/auth/index.js.map +1 -1
- package/dist/cjs/auth/interactive-oauth-flow.d.cts +20 -13
- package/dist/cjs/auth/interactive-oauth-flow.d.ts +20 -13
- package/dist/cjs/auth/interactive-oauth-flow.js +48 -24
- package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
- package/dist/cjs/auth/oauth-callback-listener.js +4 -0
- package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
- package/dist/cjs/auth/rfc9728-discovery.d.cts +12 -25
- package/dist/cjs/auth/rfc9728-discovery.d.ts +12 -25
- package/dist/cjs/auth/rfc9728-discovery.js +59 -48
- package/dist/cjs/auth/rfc9728-discovery.js.map +1 -1
- package/dist/cjs/auth/types.d.cts +34 -4
- package/dist/cjs/auth/types.d.ts +34 -4
- package/dist/cjs/auth/types.js.map +1 -1
- package/dist/cjs/dcr/dcr-authenticator.d.cts +9 -5
- package/dist/cjs/dcr/dcr-authenticator.d.ts +9 -5
- package/dist/cjs/dcr/dcr-authenticator.js +436 -43
- package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
- package/dist/cjs/dcr/dynamic-client-registrar.d.cts +7 -18
- package/dist/cjs/dcr/dynamic-client-registrar.d.ts +7 -18
- package/dist/cjs/dcr/dynamic-client-registrar.js +18 -25
- package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
- package/dist/cjs/index.d.cts +1 -0
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.js +7 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/lib/url-utils.js +2 -2
- package/dist/cjs/lib/url-utils.js.map +1 -1
- package/dist/esm/auth/capability-discovery.js +17 -7
- package/dist/esm/auth/capability-discovery.js.map +1 -1
- package/dist/esm/auth/discovery-fetch.d.ts +35 -0
- package/dist/esm/auth/discovery-fetch.js +184 -0
- package/dist/esm/auth/discovery-fetch.js.map +1 -0
- package/dist/esm/auth/index.d.ts +1 -0
- package/dist/esm/auth/index.js +1 -0
- package/dist/esm/auth/index.js.map +1 -1
- package/dist/esm/auth/interactive-oauth-flow.d.ts +20 -13
- package/dist/esm/auth/interactive-oauth-flow.js +50 -23
- package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
- package/dist/esm/auth/oauth-callback-listener.js +4 -0
- package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
- package/dist/esm/auth/rfc9728-discovery.d.ts +12 -25
- package/dist/esm/auth/rfc9728-discovery.js +49 -56
- package/dist/esm/auth/rfc9728-discovery.js.map +1 -1
- package/dist/esm/auth/types.d.ts +34 -4
- package/dist/esm/auth/types.js.map +1 -1
- package/dist/esm/dcr/dcr-authenticator.d.ts +9 -5
- package/dist/esm/dcr/dcr-authenticator.js +92 -39
- package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
- package/dist/esm/dcr/dynamic-client-registrar.d.ts +7 -18
- package/dist/esm/dcr/dynamic-client-registrar.js +19 -23
- package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/lib/url-utils.js +2 -2
- package/dist/esm/lib/url-utils.js.map +1 -1
- package/package.json +3 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dcr-authenticator.ts"],"sourcesContent":["/**\n * DCR Authenticator\n * Consolidates DCR and OAuth flow logic for MCP HTTP servers\n */\n\nimport path from 'node:path';\nimport * as fs from 'fs';\nimport Keyv from 'keyv';\nimport { KeyvFile } from 'keyv-file';\nimport { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.ts';\nimport type { AuthCapabilities, TokenSet } from '../auth/types.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { DynamicClientRegistrar } from './dynamic-client-registrar.ts';\n\n/**\n * DcrAuthenticator configuration options\n */\nexport interface DcrAuthenticatorOptions {\n /** Custom Keyv store (for testing) - if not provided, uses default ~/.mcpeasy/tokens.json */\n tokenStore?: Keyv;\n /** Headless mode (don't open browser) */\n headless?: boolean;\n /** Required redirect URI for OAuth callback */\n redirectUri: string;\n /** Optional logger for debug output (defaults to singleton logger) */\n logger?: Logger;\n}\n\n/**\n * Buffer time before token expiry to trigger proactive refresh (5 minutes)\n */\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\n/**\n * DcrAuthenticator manages authentication for MCP HTTP servers\n * Handles DCR registration, OAuth flows, and token management\n */\nexport class DcrAuthenticator {\n private tokenStore: Keyv;\n private dcrClient: DynamicClientRegistrar;\n private oauthFlow: InteractiveOAuthFlow;\n private headless: boolean;\n private redirectUri: string;\n private logger: Logger;\n\n constructor(options: DcrAuthenticatorOptions) {\n if (options.tokenStore) {\n this.tokenStore = options.tokenStore;\n } else {\n // Default CLI store in .mcp-z directory (per-project)\n const storePath = path.join(process.cwd(), '.mcp-z', 'tokens.json');\n\n // Ensure directory exists before creating store\n fs.mkdirSync(path.dirname(storePath), { recursive: true });\n\n this.tokenStore = new Keyv({\n store: new KeyvFile({ filename: storePath }),\n });\n }\n this.dcrClient = new DynamicClientRegistrar();\n this.oauthFlow = new InteractiveOAuthFlow();\n this.headless = options.headless || false;\n this.redirectUri = options.redirectUri;\n this.logger = options.logger ?? defaultLogger;\n }\n\n /**\n * Detect if server is self-hosted DCR (vs external OAuth provider)\n * Self-hosted servers have their own OAuth endpoints and manage token storage\n */\n private async detectSelfHostedMode(baseUrl: string): Promise<boolean> {\n try {\n // Self-hosted DCR servers typically run their own OAuth server\n // Check if this is a self-hosted instance by testing OAuth metadata\n // For now, assume self-hosted if baseUrl matches common localhost patterns\n // TODO: Implement proper self-hosted detection logic\n return baseUrl.includes('localhost') || baseUrl.includes('127.0.0.1');\n } catch (_error) {\n return false; // Assume external mode if detection fails\n }\n }\n\n /**\n * Ensure server is authenticated, performing DCR and OAuth if needed\n * Proactively refreshes tokens if they're within 5 minutes of expiry\n *\n * @param baseUrl - Base URL of the server (e.g., https://example.com)\n * @param capabilities - Auth capabilities from .well-known endpoint\n * @returns Valid token set ready to use\n *\n * @throws Error if authentication fails\n *\n * @example\n * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });\n * const tokens = await authenticator.ensureAuthenticated(\n * 'https://example.com',\n * capabilities\n * );\n */\n async ensureAuthenticated(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Auto-detect server mode\n const isSelfHosted = await this.detectSelfHostedMode(baseUrl);\n\n if (isSelfHosted) {\n return this.ensureAuthenticatedSelfHosted(baseUrl, capabilities);\n }\n return this.ensureAuthenticatedExternal(baseUrl, capabilities);\n }\n\n /**\n * Handle authentication for self-hosted DCR servers\n * Self-hosted servers manage their own token storage via /oauth/verify\n */\n private async ensureAuthenticatedSelfHosted(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n const dcrTokenKey = `dcr-tokens:${baseUrl}`;\n\n // 1. Check for existing DCR tokens (different from external tokens)\n let tokens = (await this.tokenStore.get(dcrTokenKey)) as TokenSet | undefined;\n\n if (tokens) {\n // 2. Verify token is still valid by calling /oauth/verify\n try {\n const verifyUrl = `${baseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (verifyResponse.ok) {\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token === tokens.accessToken) {\n // Token is still valid with the self-hosted server\n return tokens;\n }\n }\n } catch (_error) {\n // Token verification failed - need to re-authenticate\n }\n\n // Token is expired or invalid\n await this.tokenStore.delete(dcrTokenKey);\n tokens = undefined;\n }\n\n // 3. No valid tokens - perform full DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting self-hosted DCR authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client with self-hosted server...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions: { port: number; headless: boolean; scopes?: string[]; redirectUri: string; pkce: boolean; logger: Logger } = {\n port,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // For self-hosted mode, verify the token works with /oauth/verify immediately\n try {\n const verifyUrl = `${baseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (!verifyResponse.ok) {\n throw new Error(`DCR token verification failed after authentication: ${verifyResponse.status}`);\n }\n\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token !== tokens.accessToken) {\n throw new Error('DCR server returned different token in verification');\n }\n\n this.logger.debug('✅ DCR token verified with self-hosted server');\n } catch (error) {\n this.logger.error('❌ DCR token verification failed:', error instanceof Error ? error.message : String(error));\n throw new Error('Self-hosted DCR authentication completed but token verification failed');\n }\n\n // Save tokens for future use\n await this.tokenStore.set(dcrTokenKey, tokens);\n this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');\n\n return tokens;\n }\n\n /**\n * Handle authentication for external OAuth providers (original implementation)\n */\n private async ensureAuthenticatedExternal(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n const tokenKey = `tokens:${baseUrl}`;\n\n // 1. Check for existing tokens\n let tokens = (await this.tokenStore.get(tokenKey)) as TokenSet | undefined;\n\n if (tokens) {\n // 2. Proactive refresh if token expires within 5 minutes\n if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {\n this.logger.debug('🔄 Refreshing access token...');\n\n try {\n tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint);\n await this.tokenStore.set(tokenKey, tokens);\n this.logger.debug('✅ Token refreshed successfully');\n } catch (_error) {\n // Refresh failed - clear tokens and re-authenticate\n this.logger.warn('⚠️ Token refresh failed, re-authenticating...');\n await this.tokenStore.delete(tokenKey);\n tokens = undefined;\n }\n }\n\n if (tokens) {\n return tokens;\n }\n }\n\n // 3. No valid tokens - perform DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting external OAuth authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions: { port: number; headless: boolean; scopes?: string[]; redirectUri: string; pkce: boolean; logger: Logger } = {\n port,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // Save tokens for future use\n await this.tokenStore.set(tokenKey, tokens);\n this.logger.debug('✅ Authentication successful, tokens saved');\n\n return tokens;\n }\n\n /**\n * Refresh access token using refresh token\n */\n private async refreshTokens(tokens: TokenSet, tokenEndpoint?: string): Promise<TokenSet> {\n if (!tokenEndpoint) {\n throw new Error('Token endpoint not available for refresh');\n }\n\n if (!tokens.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n if (!tokens.clientId || !tokens.clientSecret) {\n throw new Error('Client credentials not available for refresh');\n }\n\n return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret);\n }\n\n /**\n * Delete stored tokens for a server\n */\n async deleteTokens(baseUrl: string): Promise<void> {\n const tokenKey = `tokens:${baseUrl}`;\n await this.tokenStore.delete(tokenKey);\n this.logger.debug(`🗑️ Deleted tokens for ${baseUrl}`);\n }\n}\n"],"names":["DcrAuthenticator","REFRESH_BUFFER_MS","options","tokenStore","storePath","path","join","process","cwd","fs","mkdirSync","dirname","recursive","Keyv","store","KeyvFile","filename","dcrClient","DynamicClientRegistrar","oauthFlow","InteractiveOAuthFlow","headless","redirectUri","logger","defaultLogger","detectSelfHostedMode","baseUrl","includes","_error","ensureAuthenticated","capabilities","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","dcrTokenKey","tokens","verifyUrl","verifyResponse","verifyData","port","client","flowOptions","error","get","fetch","headers","Authorization","accessToken","Connection","ok","json","token","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","Error","debug","parseInt","URL","startsWith","registerClient","pkce","scopes","performAuthFlow","clientId","clientSecret","status","message","String","set","tokenKey","expiresAt","Date","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AAU,CAACoE,GAAG,CAACC,UAAUrC;;;wBAApC;wBACA,IAAI,CAACZ,MAAM,CAACmC,KAAK,CAAC;wBAElB;;4BAAOvB;;;;QACT;;IAEA;;GAEC,GACD,OAAcyC,aAcb,GAdD,SAAcA,cAAczC,MAAgB,EAAEqB,aAAsB;;;;;wBAClE,IAAI,CAACA,eAAe;4BAClB,MAAM,IAAIC,MAAM;wBAClB;wBAEA,IAAI,CAACtB,OAAO2C,YAAY,EAAE;4BACxB,MAAM,IAAIrB,MAAM;wBAClB;wBAEA,IAAI,CAACtB,OAAO+B,QAAQ,IAAI,CAAC/B,OAAOgC,YAAY,EAAE;4BAC5C,MAAM,IAAIV,MAAM;wBAClB;wBAEO;;4BAAM,IAAI,CAACtC,SAAS,CAACyD,aAAa,CAACpB,eAAerB,OAAO2C,YAAY,EAAE3C,OAAO+B,QAAQ,EAAE/B,OAAOgC,YAAY;;;wBAAlH;;4BAAO;;;;QACT;;IAEA;;GAEC,GACD,OAAMY,YAIL,GAJD,SAAMA,aAAarD,OAAe;;gBAC1B8C;;;;wBAAAA,WAAW,AAAC,UAAiB,OAAR9C;wBAC3B;;4BAAM,IAAI,CAACvB,UAAU,CAACiD,MAAM,CAACoB;;;wBAA7B;wBACA,IAAI,CAACjD,MAAM,CAACmC,KAAK,CAAC,AAAC,qCAAkC,OAARhC;;;;;;QAC/C;;WAnQW1B"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dcr-authenticator.ts"],"sourcesContent":["/**\n * DCR Authenticator\n * Consolidates DCR and OAuth flow logic for MCP HTTP servers\n */\n\nimport path from 'node:path';\nimport * as fs from 'fs';\nimport Keyv from 'keyv';\nimport { KeyvFile } from 'keyv-file';\nimport { isLoopbackUrl } from '../auth/discovery-fetch.ts';\nimport { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.ts';\nimport type { AuthCapabilities, OAuthFlowOptions, TokenSet } from '../auth/types.ts';\nimport { normalizeUrl } from '../lib/url-utils.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { DynamicClientRegistrar } from './dynamic-client-registrar.ts';\n\n/**\n * DcrAuthenticator configuration options\n */\nexport interface DcrAuthenticatorOptions {\n /** Custom Keyv store (for testing) - if not provided, uses default ~/.mcpeasy/tokens.json */\n tokenStore?: Keyv;\n /** Headless mode (don't open browser) */\n headless?: boolean;\n /** Required redirect URI for OAuth callback */\n redirectUri: string;\n /** Optional logger for debug output (defaults to singleton logger) */\n logger?: Logger;\n}\n\n/**\n * Buffer time before token expiry to trigger proactive refresh (5 minutes)\n */\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\n/** Raised when a credential cannot be bound to, or looked up by, an issuer. */\nclass CredentialBindingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CredentialBindingError';\n }\n}\n\n/**\n * The issuer credentials are keyed by, so they can never be presented to a\n * different authorization server even when the resource keeps its URL (SEP-2352).\n */\nfunction requireIssuer(capabilities: AuthCapabilities): string {\n if (!capabilities.issuer) {\n throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');\n }\n return capabilities.issuer;\n}\n\n/**\n * DcrAuthenticator manages authentication for MCP HTTP servers\n * Handles DCR registration, OAuth flows, and token management\n */\nexport class DcrAuthenticator {\n private tokenStore: Keyv;\n private dcrClient: DynamicClientRegistrar;\n private oauthFlow: InteractiveOAuthFlow;\n private headless: boolean;\n private redirectUri: string;\n private logger: Logger;\n\n constructor(options: DcrAuthenticatorOptions) {\n if (options.tokenStore) {\n this.tokenStore = options.tokenStore;\n } else {\n // Default CLI store in .mcp-z directory (per-project)\n const storePath = path.join(process.cwd(), '.mcp-z', 'tokens.json');\n\n // Ensure directory exists before creating store\n fs.mkdirSync(path.dirname(storePath), { recursive: true });\n\n this.tokenStore = new Keyv({\n store: new KeyvFile({ filename: storePath }),\n });\n }\n this.dcrClient = new DynamicClientRegistrar();\n this.oauthFlow = new InteractiveOAuthFlow();\n this.headless = options.headless || false;\n this.redirectUri = options.redirectUri;\n this.logger = options.logger ?? defaultLogger;\n }\n\n /**\n * Detect if server is self-hosted DCR (vs external OAuth provider)\n * Self-hosted servers have their own OAuth endpoints and manage token storage\n */\n private async detectSelfHostedMode(baseUrl: string): Promise<boolean> {\n try {\n // Self-hosted DCR servers typically run their own OAuth server\n // Check if this is a self-hosted instance by testing OAuth metadata\n // For now, assume self-hosted if baseUrl matches common localhost patterns\n // TODO: Implement proper self-hosted detection logic\n return baseUrl.includes('localhost') || baseUrl.includes('127.0.0.1');\n } catch (_error) {\n return false; // Assume external mode if detection fails\n }\n }\n\n /**\n * Ensure server is authenticated, performing DCR and OAuth if needed\n * Proactively refreshes tokens if they're within 5 minutes of expiry\n *\n * @param baseUrl - Base URL of the server (e.g., https://example.com)\n * @param capabilities - Auth capabilities from .well-known endpoint\n * @returns Valid token set ready to use\n *\n * @throws Error if authentication fails\n *\n * @example\n * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });\n * const tokens = await authenticator.ensureAuthenticated(\n * 'https://example.com',\n * capabilities\n * );\n */\n async ensureAuthenticated(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Auto-detect server mode\n const isSelfHosted = await this.detectSelfHostedMode(baseUrl);\n\n if (isSelfHosted) {\n return this.ensureAuthenticatedSelfHosted(baseUrl, capabilities);\n }\n return this.ensureAuthenticatedExternal(baseUrl, capabilities);\n }\n\n /**\n * Handle authentication for self-hosted DCR servers\n * Self-hosted servers manage their own token storage via /oauth/verify\n */\n private async ensureAuthenticatedSelfHosted(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Loopback trust for every discovery-derived fetch below, computed from\n // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).\n const allowLoopback = isLoopbackUrl(baseUrl);\n const issuer = requireIssuer(capabilities);\n const resource = normalizeUrl(baseUrl);\n const dcrTokenKey = `dcr-tokens:${issuer}:${resource}`;\n\n // 1. Check for existing DCR tokens (different from external tokens)\n let tokens = await this.loadTokens(dcrTokenKey, issuer);\n\n if (tokens) {\n // 2. Verify token is still valid by calling /oauth/verify\n try {\n const verifyUrl = `${baseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (verifyResponse.ok) {\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token === tokens.accessToken) {\n // Token is still valid with the self-hosted server\n return tokens;\n }\n }\n } catch (_error) {\n // Token verification failed - need to re-authenticate\n }\n\n // Token is expired or invalid\n await this.tokenStore.delete(dcrTokenKey);\n tokens = undefined;\n }\n\n // 3. No valid tokens - perform full DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting self-hosted DCR authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client with self-hosted server...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // For self-hosted mode, verify the token works with /oauth/verify immediately\n try {\n const verifyUrl = `${baseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (!verifyResponse.ok) {\n throw new Error(`DCR token verification failed after authentication: ${verifyResponse.status}`);\n }\n\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token !== tokens.accessToken) {\n throw new Error('DCR server returned different token in verification');\n }\n\n this.logger.debug('✅ DCR token verified with self-hosted server');\n } catch (error) {\n this.logger.error('❌ DCR token verification failed:', error instanceof Error ? error.message : String(error));\n throw new Error('Self-hosted DCR authentication completed but token verification failed');\n }\n\n // Save tokens for future use\n await this.tokenStore.set(dcrTokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');\n\n return tokens;\n }\n\n /** Handles authentication for external (non-self-hosted) OAuth providers. */\n private async ensureAuthenticatedExternal(baseUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // See ensureAuthenticatedSelfHosted - same loopback trust rule.\n const allowLoopback = isLoopbackUrl(baseUrl);\n const issuer = requireIssuer(capabilities);\n const resource = normalizeUrl(baseUrl);\n const tokenKey = `tokens:${issuer}:${resource}`;\n\n // 1. Check for existing tokens\n let tokens = await this.loadTokens(tokenKey, issuer);\n\n if (tokens) {\n // 2. Proactive refresh if token expires within 5 minutes\n if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {\n this.logger.debug('🔄 Refreshing access token...');\n\n try {\n tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback);\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Token refreshed successfully');\n } catch (_error) {\n // Refresh failed - clear tokens and re-authenticate\n this.logger.warn('⚠️ Token refresh failed, re-authenticating...');\n await this.tokenStore.delete(tokenKey);\n tokens = undefined;\n }\n }\n\n if (tokens) {\n return tokens;\n }\n }\n\n // 3. No valid tokens - perform DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting external OAuth authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // Save tokens for future use\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Authentication successful, tokens saved');\n\n return tokens;\n }\n\n /**\n * Refreshes an access token using a refresh token.\n * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).\n * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.\n */\n private async refreshTokens(tokens: TokenSet, tokenEndpoint: string | undefined, resource: string, allowLoopback = false): Promise<TokenSet> {\n if (!tokenEndpoint) {\n throw new Error('Token endpoint not available for refresh');\n }\n\n if (!tokens.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n if (!tokens.clientId || !tokens.clientSecret) {\n throw new Error('Client credentials not available for refresh');\n }\n\n return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback);\n }\n\n /**\n * Deletes both stored token families for a server, across every issuer they were bound to.\n * @throws CredentialBindingError if the configured store cannot enumerate keys.\n */\n async deleteTokens(baseUrl: string): Promise<void> {\n const suffix = `:${normalizeUrl(baseUrl)}`;\n if (!this.tokenStore.iterator) {\n throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');\n }\n\n for await (const [key] of this.tokenStore.iterator(this.tokenStore.namespace)) {\n if (typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix)) {\n await this.tokenStore.delete(key);\n }\n }\n this.logger.debug(`🗑️ Deleted tokens for ${baseUrl}`);\n }\n\n /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */\n private async loadTokens(key: string, issuer: string): Promise<TokenSet | undefined> {\n const tokens = (await this.tokenStore.get(key)) as TokenSet | undefined;\n if (!tokens) return undefined;\n if (tokens.issuer === issuer) return tokens;\n\n this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');\n await this.tokenStore.delete(key);\n return undefined;\n }\n\n private buildFlowOptions(port: number, capabilities: AuthCapabilities, issuer: string, resource: string, allowLoopback: boolean): OAuthFlowOptions {\n const flowOptions: OAuthFlowOptions = {\n port,\n issuer,\n resource,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n allowLoopback,\n authorizationResponseIssSupported: capabilities.authorizationResponseIssSupported ?? false,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\n return flowOptions;\n }\n}\n"],"names":["DcrAuthenticator","REFRESH_BUFFER_MS","CredentialBindingError","message","name","Error","requireIssuer","capabilities","issuer","options","tokenStore","storePath","path","join","process","cwd","fs","mkdirSync","dirname","recursive","Keyv","store","KeyvFile","filename","dcrClient","DynamicClientRegistrar","oauthFlow","InteractiveOAuthFlow","headless","redirectUri","logger","defaultLogger","detectSelfHostedMode","baseUrl","includes","_error","ensureAuthenticated","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","allowLoopback","resource","dcrTokenKey","tokens","verifyUrl","verifyResponse","verifyData","port","client","flowOptions","error","isLoopbackUrl","normalizeUrl","loadTokens","fetch","headers","Authorization","accessToken","Connection","ok","json","token","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","debug","parseInt","URL","startsWith","registerClient","buildFlowOptions","performAuthFlow","clientId","clientSecret","status","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","suffix","key","iterator","namespace","endsWith","get","pkce","authorizationRes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QACT;;IAEA,OAAQS,gBAgBP,GAhBD,SAAQA,iBAAiBzB,IAAY,EAAExC,YAA8B,EAAEC,MAAc,EAAEiC,QAAgB,EAAED,aAAsB;YAUxFjC;QATrC,IAAM0C,cAAgC;YACpCF,MAAAA;YACAvC,QAAAA;YACAiC,UAAAA;YACAb,UAAU,IAAI,CAACA,QAAQ;YACvBC,aAAa,IAAI,CAACA,WAAW;YAC7BgE,MAAM;YACN/D,QAAQ,IAAI,CAACA,MAAM;YACnBU,eAAAA;YACAsD,iCAAiC,GAAEvF,kDAAAA,aAAauF,iCAAiC,cAA9CvF,6DAAAA,kDAAkD;QACvF;QACA,IAAIA,aAAawF,MAAM,EAAE;YACvB9C,YAAY8C,MAAM,GAAGxF,aAAawF,MAAM;QAC1C;QACA,OAAO9C;IACT;WAlSWjD"}
|
|
@@ -3,26 +3,15 @@
|
|
|
3
3
|
* Implements RFC 7591 for OAuth client registration
|
|
4
4
|
*/
|
|
5
5
|
import type { ClientCredentials, DcrRegistrationOptions } from '../auth/types.js';
|
|
6
|
-
/**
|
|
7
|
-
* DynamicClientRegistrar handles Dynamic Client Registration with OAuth servers
|
|
8
|
-
*/
|
|
6
|
+
/** Handles Dynamic Client Registration with OAuth servers. */
|
|
9
7
|
export declare class DynamicClientRegistrar {
|
|
10
8
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* @param registrationEndpoint - DCR registration endpoint URL
|
|
14
|
-
* @param options - Registration options (client name, redirect URI)
|
|
15
|
-
* @returns Client credentials (client ID and secret)
|
|
16
|
-
*
|
|
17
|
-
* @throws Error if registration fails or server returns error
|
|
9
|
+
* Registers a new OAuth client with the authorization server (RFC 7591).
|
|
18
10
|
*
|
|
19
|
-
* @
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* { clientName: '@mcp-z/client', redirectUri: 'http://localhost:3000/callback' }
|
|
24
|
-
* );
|
|
25
|
-
* console.log('Client ID:', creds.clientId);
|
|
11
|
+
* @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.
|
|
12
|
+
* @param options - Registration options (redirect URI, client name, loopback trust).
|
|
13
|
+
* @returns Client credentials (client ID and secret).
|
|
14
|
+
* @throws Error if registration fails or the server returns an error.
|
|
26
15
|
*/
|
|
27
|
-
registerClient(registrationEndpoint: string, options
|
|
16
|
+
registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials>;
|
|
28
17
|
}
|
|
@@ -3,26 +3,15 @@
|
|
|
3
3
|
* Implements RFC 7591 for OAuth client registration
|
|
4
4
|
*/
|
|
5
5
|
import type { ClientCredentials, DcrRegistrationOptions } from '../auth/types.js';
|
|
6
|
-
/**
|
|
7
|
-
* DynamicClientRegistrar handles Dynamic Client Registration with OAuth servers
|
|
8
|
-
*/
|
|
6
|
+
/** Handles Dynamic Client Registration with OAuth servers. */
|
|
9
7
|
export declare class DynamicClientRegistrar {
|
|
10
8
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* @param registrationEndpoint - DCR registration endpoint URL
|
|
14
|
-
* @param options - Registration options (client name, redirect URI)
|
|
15
|
-
* @returns Client credentials (client ID and secret)
|
|
16
|
-
*
|
|
17
|
-
* @throws Error if registration fails or server returns error
|
|
9
|
+
* Registers a new OAuth client with the authorization server (RFC 7591).
|
|
18
10
|
*
|
|
19
|
-
* @
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* { clientName: '@mcp-z/client', redirectUri: 'http://localhost:3000/callback' }
|
|
24
|
-
* );
|
|
25
|
-
* console.log('Client ID:', creds.clientId);
|
|
11
|
+
* @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.
|
|
12
|
+
* @param options - Registration options (redirect URI, client name, loopback trust).
|
|
13
|
+
* @returns Client credentials (client ID and secret).
|
|
14
|
+
* @throws Error if registration fails or the server returns an error.
|
|
26
15
|
*/
|
|
27
|
-
registerClient(registrationEndpoint: string, options
|
|
16
|
+
registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials>;
|
|
28
17
|
}
|
|
@@ -11,6 +11,7 @@ Object.defineProperty(exports, "DynamicClientRegistrar", {
|
|
|
11
11
|
return DynamicClientRegistrar;
|
|
12
12
|
}
|
|
13
13
|
});
|
|
14
|
+
var _discoveryfetchts = require("../auth/discovery-fetch.js");
|
|
14
15
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
15
16
|
try {
|
|
16
17
|
var info = gen[key](arg);
|
|
@@ -146,35 +147,22 @@ var DynamicClientRegistrar = /*#__PURE__*/ function() {
|
|
|
146
147
|
}
|
|
147
148
|
var _proto = DynamicClientRegistrar.prototype;
|
|
148
149
|
/**
|
|
149
|
-
*
|
|
150
|
+
* Registers a new OAuth client with the authorization server (RFC 7591).
|
|
150
151
|
*
|
|
151
|
-
* @param registrationEndpoint -
|
|
152
|
-
* @param options - Registration options (client name,
|
|
153
|
-
* @returns Client credentials (client ID and secret)
|
|
154
|
-
*
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
* const registrar = new DynamicClientRegistrar();
|
|
159
|
-
* const creds = await registrar.registerClient(
|
|
160
|
-
* 'https://example.com/oauth/register',
|
|
161
|
-
* { clientName: '@mcp-z/client', redirectUri: 'http://localhost:3000/callback' }
|
|
162
|
-
* );
|
|
163
|
-
* console.log('Client ID:', creds.clientId);
|
|
164
|
-
*/ _proto.registerClient = function registerClient(_0) {
|
|
165
|
-
return _async_to_generator(function(registrationEndpoint) {
|
|
166
|
-
var options, requestBody, response, errorText, data, credentials;
|
|
167
|
-
var _arguments = arguments;
|
|
152
|
+
* @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.
|
|
153
|
+
* @param options - Registration options (redirect URI, client name, loopback trust).
|
|
154
|
+
* @returns Client credentials (client ID and secret).
|
|
155
|
+
* @throws Error if registration fails or the server returns an error.
|
|
156
|
+
*/ _proto.registerClient = function registerClient(registrationEndpoint, options) {
|
|
157
|
+
return _async_to_generator(function() {
|
|
158
|
+
var _options_allowLoopback, requestBody, response, errorText, data, credentials;
|
|
168
159
|
return _ts_generator(this, function(_state) {
|
|
169
160
|
switch(_state.label){
|
|
170
161
|
case 0:
|
|
171
|
-
options = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : {};
|
|
172
162
|
requestBody = {
|
|
173
163
|
client_name: options.clientName || '@mcp-z/client',
|
|
174
|
-
redirect_uris:
|
|
164
|
+
redirect_uris: [
|
|
175
165
|
options.redirectUri
|
|
176
|
-
] : [
|
|
177
|
-
'http://localhost:3000/callback'
|
|
178
166
|
],
|
|
179
167
|
grant_types: [
|
|
180
168
|
'authorization_code',
|
|
@@ -183,11 +171,14 @@ var DynamicClientRegistrar = /*#__PURE__*/ function() {
|
|
|
183
171
|
response_types: [
|
|
184
172
|
'code'
|
|
185
173
|
],
|
|
186
|
-
token_endpoint_auth_method: 'client_secret_basic'
|
|
174
|
+
token_endpoint_auth_method: 'client_secret_basic',
|
|
175
|
+
// The callback listener always binds an OS-assigned loopback port, so the
|
|
176
|
+
// redirect URI is one an authorization server rejects for a web client (SEP-837, RFC 8252).
|
|
177
|
+
application_type: 'native'
|
|
187
178
|
};
|
|
188
179
|
return [
|
|
189
180
|
4,
|
|
190
|
-
|
|
181
|
+
(0, _discoveryfetchts.discoveryFetch)(registrationEndpoint, {
|
|
191
182
|
method: 'POST',
|
|
192
183
|
headers: {
|
|
193
184
|
'Content-Type': 'application/json',
|
|
@@ -195,6 +186,8 @@ var DynamicClientRegistrar = /*#__PURE__*/ function() {
|
|
|
195
186
|
Connection: 'close'
|
|
196
187
|
},
|
|
197
188
|
body: JSON.stringify(requestBody)
|
|
189
|
+
}, 'registration endpoint', {
|
|
190
|
+
allowLoopback: (_options_allowLoopback = options.allowLoopback) !== null && _options_allowLoopback !== void 0 ? _options_allowLoopback : false
|
|
198
191
|
})
|
|
199
192
|
];
|
|
200
193
|
case 1:
|
|
@@ -233,7 +226,7 @@ var DynamicClientRegistrar = /*#__PURE__*/ function() {
|
|
|
233
226
|
];
|
|
234
227
|
}
|
|
235
228
|
});
|
|
236
|
-
})
|
|
229
|
+
})();
|
|
237
230
|
};
|
|
238
231
|
return DynamicClientRegistrar;
|
|
239
232
|
}();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dynamic-client-registrar.ts"],"sourcesContent":["/**\n * Dynamic Client Registration (DCR) Client\n * Implements RFC 7591 for OAuth client registration\n */\n\nimport type { ClientCredentials, DcrRegistrationOptions } from '../auth/types.ts';\n\n
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dynamic-client-registrar.ts"],"sourcesContent":["/**\n * Dynamic Client Registration (DCR) Client\n * Implements RFC 7591 for OAuth client registration\n */\n\nimport { discoveryFetch } from '../auth/discovery-fetch.ts';\nimport type { ClientCredentials, DcrRegistrationOptions } from '../auth/types.ts';\n\n/** DCR Registration Request (RFC 7591) */\ninterface DcrRegistrationRequest {\n client_name?: string;\n redirect_uris?: string[];\n grant_types?: string[];\n response_types?: string[];\n token_endpoint_auth_method?: string;\n application_type?: string;\n}\n\n/** DCR Registration Response (RFC 7591) */\ninterface DcrRegistrationResponse {\n client_id: string;\n client_secret?: string;\n client_id_issued_at?: number;\n client_secret_expires_at?: number;\n}\n\n/** Handles Dynamic Client Registration with OAuth servers. */\nexport class DynamicClientRegistrar {\n /**\n * Registers a new OAuth client with the authorization server (RFC 7591).\n *\n * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.\n * @param options - Registration options (redirect URI, client name, loopback trust).\n * @returns Client credentials (client ID and secret).\n * @throws Error if registration fails or the server returns an error.\n */\n async registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials> {\n const requestBody: DcrRegistrationRequest = {\n client_name: options.clientName || '@mcp-z/client',\n redirect_uris: [options.redirectUri],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'client_secret_basic',\n // The callback listener always binds an OS-assigned loopback port, so the\n // redirect URI is one an authorization server rejects for a web client (SEP-837, RFC 8252).\n application_type: 'native',\n };\n\n // registrationEndpoint is remote-controlled discovery data; allowLoopback\n // must come from the caller's own trust, never from registrationEndpoint.\n const response = await discoveryFetch(\n registrationEndpoint,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Connection: 'close',\n },\n body: JSON.stringify(requestBody),\n },\n 'registration endpoint',\n { allowLoopback: options.allowLoopback ?? false }\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`DCR registration failed (${response.status}): ${errorText}`);\n }\n\n const data = (await response.json()) as DcrRegistrationResponse;\n\n if (!data.client_id) {\n throw new Error('DCR registration response missing client_id');\n }\n\n const credentials: ClientCredentials = {\n clientId: data.client_id,\n clientSecret: data.client_secret || '',\n };\n\n if (data.client_id_issued_at) {\n credentials.issuedAt = data.client_id_issued_at;\n }\n\n return credentials;\n }\n}\n"],"names":["DynamicClientRegistrar","registerClient","registrationEndpoint","options","requestBody","response","errorText","data","credentials","client_name","clientName","redirect_uris","redirectUri","grant_types","response_types","token_endpoint_auth_method","application_type","discoveryFetch","method","headers","Accept","Connection","body","JSON","stringify","allowLoopback","ok","text","Error","status","json","client_id","clientId","clientSecret","client_secret","client_id_issued_at","issuedAt"],"mappings":"AAAA;;;CAGC;;;;+BAwBYA;;;eAAAA;;;gCAtBkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBxB,IAAA,AAAMA,uCAAN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+3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
export type { McpServerEntry, StartConfig } from '../schemas/servers.d.js';
|
|
5
5
|
export { probeAuthCapabilities } from './auth/capability-discovery.js';
|
|
6
|
+
export { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.js';
|
|
6
7
|
export type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.js';
|
|
7
8
|
export { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.js';
|
|
8
9
|
export { OAuthCallbackListener } from './auth/oauth-callback-listener.js';
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
export type { McpServerEntry, StartConfig } from '../schemas/servers.d.js';
|
|
5
5
|
export { probeAuthCapabilities } from './auth/capability-discovery.js';
|
|
6
|
+
export { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.js';
|
|
6
7
|
export type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.js';
|
|
7
8
|
export { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.js';
|
|
8
9
|
export { OAuthCallbackListener } from './auth/oauth-callback-listener.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -15,6 +15,9 @@ _export(exports, {
|
|
|
15
15
|
get DcrAuthenticator () {
|
|
16
16
|
return _dcrauthenticatorts.DcrAuthenticator;
|
|
17
17
|
},
|
|
18
|
+
get DiscoveryFetchError () {
|
|
19
|
+
return _discoveryfetchts.DiscoveryFetchError;
|
|
20
|
+
},
|
|
18
21
|
get DynamicClientRegistrar () {
|
|
19
22
|
return _dynamicclientregistrarts.DynamicClientRegistrar;
|
|
20
23
|
},
|
|
@@ -54,6 +57,9 @@ _export(exports, {
|
|
|
54
57
|
get getLogLevel () {
|
|
55
58
|
return _loggerts.getLogLevel;
|
|
56
59
|
},
|
|
60
|
+
get isLoopbackUrl () {
|
|
61
|
+
return _discoveryfetchts.isLoopbackUrl;
|
|
62
|
+
},
|
|
57
63
|
get logger () {
|
|
58
64
|
return _loggerts.logger;
|
|
59
65
|
},
|
|
@@ -80,6 +86,7 @@ _export(exports, {
|
|
|
80
86
|
}
|
|
81
87
|
});
|
|
82
88
|
var _capabilitydiscoveryts = require("./auth/capability-discovery.js");
|
|
89
|
+
var _discoveryfetchts = require("./auth/discovery-fetch.js");
|
|
83
90
|
var _interactiveoauthflowts = require("./auth/interactive-oauth-flow.js");
|
|
84
91
|
var _oauthcallbacklistenerts = require("./auth/oauth-callback-listener.js");
|
|
85
92
|
var _clienthelpersts = require("./client-helpers.js");
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/index.ts"],"sourcesContent":["/**\n * @mcp-z/client - MCP Client Library\n */\n\n// Config types (from schema)\nexport type { McpServerEntry, StartConfig } from '../schemas/servers.d.ts';\n// Auth - OAuth utilities\nexport { probeAuthCapabilities } from './auth/capability-discovery.ts';\nexport type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.ts';\nexport { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.ts';\nexport { OAuthCallbackListener } from './auth/oauth-callback-listener.ts';\n// Client helpers and lightweight overloads\nexport { decorateClient, type ManagedClient, type PromptArguments, type WrappedCallToolReturn, type WrappedGetPromptReturn, type WrappedReadResourceReturn } from './client-helpers.ts';\n// Config - Configuration validation\nexport { type ValidationResult, validateServers } from './config/validate-config.ts';\n// Connection - MCP client connection utilities (internal helpers exposed for advanced use)\nexport type { JsonValue, PromptArgument, ToolArguments } from './connection/types.ts';\n// DCR - Dynamic Client Registration utilities\nexport { DcrAuthenticator } from './dcr/dcr-authenticator.ts';\nexport { DynamicClientRegistrar } from './dcr/dynamic-client-registrar.ts';\nexport type { ClientCredentials, DcrAuthenticatorOptions, DcrRegistrationOptions } from './dcr/index.ts';\nexport {\n type JsonValidator,\n type NativeCallToolResponse,\n type NativeGetPromptResponse,\n type NativeReadResourceResponse,\n PromptResponseError,\n PromptResponseWrapper,\n ResourceResponseError,\n ResourceResponseWrapper,\n ToolResponseError,\n ToolResponseWrapper,\n} from './response-wrappers.ts';\nexport type { CapabilityClient, CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './search/index.ts';\n// Search - Capability discovery\nexport { buildCapabilityIndex, search, searchCapabilities } from './search/index.ts';\n// Spawn - Server registry (v3 API)\nexport { type CloseResult, type CreateServerRegistryOptions, createServerRegistry, type Dialect, type ServerRegistry, type ServersConfig } from './spawn/spawn-servers.ts';\nexport type { TransportType } from './types.ts';\n// Utils - Shared utilities\nexport { getLogLevel, type Logger, type LogLevel, logger, setLogLevel } from './utils/logger.ts';\nexport { resolveArgsPaths, resolvePath } from './utils/path-utils.ts';\n"],"names":["DcrAuthenticator","DynamicClientRegistrar","InteractiveOAuthFlow","OAuthCallbackListener","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","createServerRegistry","decorateClient","getLogLevel","logger","probeAuthCapabilities","resolveArgsPaths","resolvePath","search","searchCapabilities","setLogLevel","validateServers"],"mappings":"AAAA;;CAEC,GAED,6BAA6B;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/index.ts"],"sourcesContent":["/**\n * @mcp-z/client - MCP Client Library\n */\n\n// Config types (from schema)\nexport type { McpServerEntry, StartConfig } from '../schemas/servers.d.ts';\n// Auth - OAuth utilities\nexport { probeAuthCapabilities } from './auth/capability-discovery.ts';\nexport { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.ts';\nexport type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.ts';\nexport { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.ts';\nexport { OAuthCallbackListener } from './auth/oauth-callback-listener.ts';\n// Client helpers and lightweight overloads\nexport { decorateClient, type ManagedClient, type PromptArguments, type WrappedCallToolReturn, type WrappedGetPromptReturn, type WrappedReadResourceReturn } from './client-helpers.ts';\n// Config - Configuration validation\nexport { type ValidationResult, validateServers } from './config/validate-config.ts';\n// Connection - MCP client connection utilities (internal helpers exposed for advanced use)\nexport type { JsonValue, PromptArgument, ToolArguments } from './connection/types.ts';\n// DCR - Dynamic Client Registration utilities\nexport { DcrAuthenticator } from './dcr/dcr-authenticator.ts';\nexport { DynamicClientRegistrar } from './dcr/dynamic-client-registrar.ts';\nexport type { ClientCredentials, DcrAuthenticatorOptions, DcrRegistrationOptions } from './dcr/index.ts';\nexport {\n type JsonValidator,\n type NativeCallToolResponse,\n type NativeGetPromptResponse,\n type NativeReadResourceResponse,\n PromptResponseError,\n PromptResponseWrapper,\n ResourceResponseError,\n ResourceResponseWrapper,\n ToolResponseError,\n ToolResponseWrapper,\n} from './response-wrappers.ts';\nexport type { CapabilityClient, CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './search/index.ts';\n// Search - Capability discovery\nexport { buildCapabilityIndex, search, searchCapabilities } from './search/index.ts';\n// Spawn - Server registry (v3 API)\nexport { type CloseResult, type CreateServerRegistryOptions, createServerRegistry, type Dialect, type ServerRegistry, type ServersConfig } from './spawn/spawn-servers.ts';\nexport type { TransportType } from './types.ts';\n// Utils - Shared utilities\nexport { getLogLevel, type Logger, type LogLevel, logger, setLogLevel } from './utils/logger.ts';\nexport { resolveArgsPaths, resolvePath } from './utils/path-utils.ts';\n"],"names":["DcrAuthenticator","DiscoveryFetchError","DynamicClientRegistrar","InteractiveOAuthFlow","OAuthCallbackListener","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","createServerRegistry","decorateClient","getLogLevel","isLoopbackUrl","logger","probeAuthCapabilities","resolveArgsPaths","resolvePath","search","searchCapabilities","setLogLevel","validateServers"],"mappings":"AAAA;;CAEC,GAED,6BAA6B;;;;;;;;;;;;QAepBA;eAAAA,oCAAgB;;QAXhBC;eAAAA,qCAAmB;;QAYnBC;eAAAA,gDAAsB;;QAVtBC;eAAAA,4CAAoB;;QACpBC;eAAAA,8CAAqB;;QAgB5BC;eAAAA,uCAAmB;;QACnBC;eAAAA,yCAAqB;;QACrBC;eAAAA,yCAAqB;;QACrBC;eAAAA,2CAAuB;;QACvBC;eAAAA,qCAAiB;;QACjBC;eAAAA,uCAAmB;;QAIZC;eAAAA,6BAAoB;;QAEgCC;eAAAA,oCAAoB;;QAzBxEC;eAAAA,+BAAc;;QA4BdC;eAAAA,qBAAW;;QAjCUC;eAAAA,+BAAa;;QAiCOC;eAAAA,gBAAM;;QAlC/CC;eAAAA,4CAAqB;;QAmCrBC;eAAAA,6BAAgB;;QAAEC;eAAAA,wBAAW;;QANPC;eAAAA,eAAM;;QAAEC;eAAAA,2BAAkB;;QAKCC;eAAAA,qBAAW;;QA1BrCC;eAAAA,iCAAe;;;qCART;gCACa;sCAEd;uCACC;+BAE4H;gCAE3G;kCAItB;wCACM;kCAahC;uBAG0D;8BAE+E;wBAGnE;2BAC/B"}
|
|
@@ -21,8 +21,8 @@ function normalizeUrl(input) {
|
|
|
21
21
|
var url = new URL(input);
|
|
22
22
|
url.search = '';
|
|
23
23
|
url.hash = '';
|
|
24
|
-
|
|
25
|
-
return url.origin + url.pathname;
|
|
24
|
+
// Strip after joining: assigning an empty pathname puts the '/' straight back.
|
|
25
|
+
return (url.origin + url.pathname).replace(/\/+$/, '');
|
|
26
26
|
} catch (unused) {
|
|
27
27
|
return input.replace(/\/+$/, '');
|
|
28
28
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/lib/url-utils.ts"],"sourcesContent":["export function normalizeUrl(input: string): string {\n try {\n const url = new URL(input);\n url.search = '';\n url.hash = '';\n
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/lib/url-utils.ts"],"sourcesContent":["export function normalizeUrl(input: string): string {\n try {\n const url = new URL(input);\n url.search = '';\n url.hash = '';\n // Strip after joining: assigning an empty pathname puts the '/' straight back.\n return (url.origin + url.pathname).replace(/\\/+$/, '');\n } catch {\n return input.replace(/\\/+$/, '');\n }\n}\n\nexport function joinWellKnown(baseUrl: string, suffix: string): string {\n return `${normalizeUrl(baseUrl)}${suffix}`;\n}\n"],"names":["joinWellKnown","normalizeUrl","input","url","URL","search","hash","origin","pathname","replace","baseUrl","suffix"],"mappings":";;;;;;;;;;;QAYgBA;eAAAA;;QAZAC;eAAAA;;;AAAT,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,IAAMC,MAAM,IAAIC,IAAIF;QACpBC,IAAIE,MAAM,GAAG;QACbF,IAAIG,IAAI,GAAG;QACX,+EAA+E;QAC/E,OAAO,AAACH,CAAAA,IAAII,MAAM,GAAGJ,IAAIK,QAAQ,AAAD,EAAGC,OAAO,CAAC,QAAQ;IACrD,EAAE,eAAM;QACN,OAAOP,MAAMO,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEO,SAAST,cAAcU,OAAe,EAAEC,MAAc;IAC3D,OAAO,AAAC,GAA0BA,OAAxBV,aAAaS,UAAkB,OAAPC;AACpC"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* OAuth Server Capability Discovery
|
|
3
3
|
* Probes RFC 9728 (Protected Resource) and RFC 8414 (Authorization Server) metadata
|
|
4
4
|
*/ import { normalizeUrl } from '../lib/url-utils.js';
|
|
5
|
+
import { isLoopbackUrl } from './discovery-fetch.js';
|
|
5
6
|
import { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata, discoverProtectedResourceMetadata } from './rfc9728-discovery.js';
|
|
6
7
|
/**
|
|
7
8
|
* Extract origin (protocol + host) from a URL
|
|
@@ -40,8 +41,12 @@ import { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata,
|
|
|
40
41
|
*/ function buildCapabilities(metadata, scopes) {
|
|
41
42
|
const supportsDcr = !!metadata.registration_endpoint;
|
|
42
43
|
const capabilities = {
|
|
43
|
-
supportsDcr
|
|
44
|
+
supportsDcr,
|
|
45
|
+
authorizationResponseIssSupported: metadata.authorization_response_iss_parameter_supported === true
|
|
44
46
|
};
|
|
47
|
+
if (metadata.issuer) {
|
|
48
|
+
capabilities.issuer = metadata.issuer;
|
|
49
|
+
}
|
|
45
50
|
if (metadata.registration_endpoint) {
|
|
46
51
|
capabilities.registrationEndpoint = metadata.registration_endpoint;
|
|
47
52
|
}
|
|
@@ -59,14 +64,19 @@ import { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata,
|
|
|
59
64
|
}
|
|
60
65
|
return capabilities;
|
|
61
66
|
}
|
|
62
|
-
async function resolveCapabilitiesFromAuthorizationServer(authServerUrl, scopes) {
|
|
63
|
-
const metadata = await discoverAuthorizationServerMetadata(authServerUrl
|
|
67
|
+
async function resolveCapabilitiesFromAuthorizationServer(authServerUrl, scopes, allowLoopback) {
|
|
68
|
+
const metadata = await discoverAuthorizationServerMetadata(authServerUrl, {
|
|
69
|
+
allowLoopback
|
|
70
|
+
});
|
|
64
71
|
if (!metadata) return null;
|
|
65
72
|
return buildCapabilities(metadata, scopes);
|
|
66
73
|
}
|
|
67
74
|
export async function probeAuthCapabilities(baseUrl) {
|
|
68
75
|
try {
|
|
69
76
|
const normalizedBaseUrl = normalizeUrl(baseUrl);
|
|
77
|
+
// Trust signal for every authorization-server fetch below: whether the
|
|
78
|
+
// configured MCP server is itself loopback, never a remote-supplied URL.
|
|
79
|
+
const allowLoopback = isLoopbackUrl(normalizedBaseUrl);
|
|
70
80
|
// Strategy 1: Try RFC 9728 Protected Resource Metadata discovery
|
|
71
81
|
// This handles cross-domain OAuth (e.g., Todoist: ai.todoist.net/mcp → todoist.com)
|
|
72
82
|
const resourceMetadata = await discoverProtectedResourceMetadata(normalizedBaseUrl);
|
|
@@ -80,25 +90,25 @@ export async function probeAuthCapabilities(baseUrl) {
|
|
|
80
90
|
supportsDcr: false
|
|
81
91
|
};
|
|
82
92
|
}
|
|
83
|
-
const capabilities = await resolveCapabilitiesFromAuthorizationServer(authServerUrl, resourceMetadata.scopes_supported);
|
|
93
|
+
const capabilities = await resolveCapabilitiesFromAuthorizationServer(authServerUrl, resourceMetadata.scopes_supported, allowLoopback);
|
|
84
94
|
if (capabilities) {
|
|
85
95
|
return capabilities;
|
|
86
96
|
}
|
|
87
97
|
const issuer = await discoverAuthorizationServerIssuer(baseUrl);
|
|
88
98
|
if (issuer) {
|
|
89
|
-
const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, resourceMetadata.scopes_supported);
|
|
99
|
+
const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, resourceMetadata.scopes_supported, allowLoopback);
|
|
90
100
|
if (issuerCapabilities) return issuerCapabilities;
|
|
91
101
|
}
|
|
92
102
|
}
|
|
93
103
|
const issuer = await discoverAuthorizationServerIssuer(normalizedBaseUrl);
|
|
94
104
|
if (issuer) {
|
|
95
|
-
const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer);
|
|
105
|
+
const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, undefined, allowLoopback);
|
|
96
106
|
if (issuerCapabilities) return issuerCapabilities;
|
|
97
107
|
}
|
|
98
108
|
// Strategy 2: Fall back to direct RFC 8414 discovery at resource origin
|
|
99
109
|
// This handles same-domain OAuth (traditional setup)
|
|
100
110
|
const origin = getOrigin(normalizedBaseUrl);
|
|
101
|
-
const originCapabilities = await resolveCapabilitiesFromAuthorizationServer(origin);
|
|
111
|
+
const originCapabilities = await resolveCapabilitiesFromAuthorizationServer(origin, undefined, allowLoopback);
|
|
102
112
|
if (originCapabilities) return originCapabilities;
|
|
103
113
|
// No OAuth metadata found
|
|
104
114
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/auth/capability-discovery.ts"],"sourcesContent":["/**\n * OAuth Server Capability Discovery\n * Probes RFC 9728 (Protected Resource) and RFC 8414 (Authorization Server) metadata\n */\n\nimport { normalizeUrl } from '../lib/url-utils.ts';\nimport { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata, discoverProtectedResourceMetadata } from './rfc9728-discovery.ts';\nimport type { AuthCapabilities, AuthorizationServerMetadata } from './types.ts';\n\n/**\n * Extract origin (protocol + host) from a URL\n * @param url - Full URL that may include a path\n * @returns Origin (e.g., \"https://example.com\") or original string if invalid URL\n *\n * @example\n * getOrigin('https://example.com/mcp') // → 'https://example.com'\n * getOrigin('http://localhost:9999/api/v1/mcp') // → 'http://localhost:9999'\n */\nfunction getOrigin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n // Invalid URL - return as-is for graceful degradation\n return url;\n }\n}\n\n/**\n * Probe OAuth server capabilities using RFC 9728 → RFC 8414 discovery chain\n * Returns capabilities including DCR support detection\n *\n * Discovery Strategy:\n * 1. Try RFC 9728 Protected Resource Metadata (supports cross-domain OAuth)\n * 2. If found, use first authorization_server to discover RFC 8414 Authorization Server Metadata\n * 3. Fall back to direct RFC 8414 discovery at resource origin\n *\n * @param baseUrl - Base URL of the protected resource (e.g., https://ai.todoist.net/mcp)\n * @returns AuthCapabilities object with discovered endpoints and features\n *\n * @example\n * // Todoist case: MCP at ai.todoist.net/mcp, OAuth at todoist.com\n * const caps = await probeAuthCapabilities('https://ai.todoist.net/mcp');\n * if (caps.supportsDcr) {\n * console.log('Registration endpoint:', caps.registrationEndpoint);\n * }\n */\nfunction buildCapabilities(metadata: AuthorizationServerMetadata, scopes?: string[]): AuthCapabilities {\n const supportsDcr = !!metadata.registration_endpoint;\n const capabilities: AuthCapabilities = { supportsDcr };\n\n if (metadata.registration_endpoint) {\n capabilities.registrationEndpoint = metadata.registration_endpoint;\n }\n if (metadata.authorization_endpoint) {\n capabilities.authorizationEndpoint = metadata.authorization_endpoint;\n }\n if (metadata.token_endpoint) capabilities.tokenEndpoint = metadata.token_endpoint;\n if (metadata.introspection_endpoint) {\n capabilities.introspectionEndpoint = metadata.introspection_endpoint;\n }\n\n if (scopes && scopes.length > 0) {\n capabilities.scopes = scopes;\n } else if (metadata.scopes_supported) {\n capabilities.scopes = metadata.scopes_supported;\n }\n\n return capabilities;\n}\n\nasync function resolveCapabilitiesFromAuthorizationServer(authServerUrl: string, scopes
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/auth/capability-discovery.ts"],"sourcesContent":["/**\n * OAuth Server Capability Discovery\n * Probes RFC 9728 (Protected Resource) and RFC 8414 (Authorization Server) metadata\n */\n\nimport { normalizeUrl } from '../lib/url-utils.ts';\nimport { isLoopbackUrl } from './discovery-fetch.ts';\nimport { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata, discoverProtectedResourceMetadata } from './rfc9728-discovery.ts';\nimport type { AuthCapabilities, AuthorizationServerMetadata } from './types.ts';\n\n/**\n * Extract origin (protocol + host) from a URL\n * @param url - Full URL that may include a path\n * @returns Origin (e.g., \"https://example.com\") or original string if invalid URL\n *\n * @example\n * getOrigin('https://example.com/mcp') // → 'https://example.com'\n * getOrigin('http://localhost:9999/api/v1/mcp') // → 'http://localhost:9999'\n */\nfunction getOrigin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n // Invalid URL - return as-is for graceful degradation\n return url;\n }\n}\n\n/**\n * Probe OAuth server capabilities using RFC 9728 → RFC 8414 discovery chain\n * Returns capabilities including DCR support detection\n *\n * Discovery Strategy:\n * 1. Try RFC 9728 Protected Resource Metadata (supports cross-domain OAuth)\n * 2. If found, use first authorization_server to discover RFC 8414 Authorization Server Metadata\n * 3. Fall back to direct RFC 8414 discovery at resource origin\n *\n * @param baseUrl - Base URL of the protected resource (e.g., https://ai.todoist.net/mcp)\n * @returns AuthCapabilities object with discovered endpoints and features\n *\n * @example\n * // Todoist case: MCP at ai.todoist.net/mcp, OAuth at todoist.com\n * const caps = await probeAuthCapabilities('https://ai.todoist.net/mcp');\n * if (caps.supportsDcr) {\n * console.log('Registration endpoint:', caps.registrationEndpoint);\n * }\n */\nfunction buildCapabilities(metadata: AuthorizationServerMetadata, scopes?: string[]): AuthCapabilities {\n const supportsDcr = !!metadata.registration_endpoint;\n const capabilities: AuthCapabilities = { supportsDcr, authorizationResponseIssSupported: metadata.authorization_response_iss_parameter_supported === true };\n\n if (metadata.issuer) {\n capabilities.issuer = metadata.issuer;\n }\n\n if (metadata.registration_endpoint) {\n capabilities.registrationEndpoint = metadata.registration_endpoint;\n }\n if (metadata.authorization_endpoint) {\n capabilities.authorizationEndpoint = metadata.authorization_endpoint;\n }\n if (metadata.token_endpoint) capabilities.tokenEndpoint = metadata.token_endpoint;\n if (metadata.introspection_endpoint) {\n capabilities.introspectionEndpoint = metadata.introspection_endpoint;\n }\n\n if (scopes && scopes.length > 0) {\n capabilities.scopes = scopes;\n } else if (metadata.scopes_supported) {\n capabilities.scopes = metadata.scopes_supported;\n }\n\n return capabilities;\n}\n\nasync function resolveCapabilitiesFromAuthorizationServer(authServerUrl: string, scopes: string[] | undefined, allowLoopback: boolean): Promise<AuthCapabilities | null> {\n const metadata = await discoverAuthorizationServerMetadata(authServerUrl, { allowLoopback });\n if (!metadata) return null;\n return buildCapabilities(metadata, scopes);\n}\n\nexport async function probeAuthCapabilities(baseUrl: string): Promise<AuthCapabilities> {\n try {\n const normalizedBaseUrl = normalizeUrl(baseUrl);\n // Trust signal for every authorization-server fetch below: whether the\n // configured MCP server is itself loopback, never a remote-supplied URL.\n const allowLoopback = isLoopbackUrl(normalizedBaseUrl);\n // Strategy 1: Try RFC 9728 Protected Resource Metadata discovery\n // This handles cross-domain OAuth (e.g., Todoist: ai.todoist.net/mcp → todoist.com)\n const resourceMetadata = await discoverProtectedResourceMetadata(normalizedBaseUrl);\n\n if (resourceMetadata && resourceMetadata.authorization_servers.length > 0) {\n // Found protected resource metadata with authorization servers\n // Discover the authorization server's metadata (RFC 8414)\n const authServerUrl = resourceMetadata.authorization_servers[0];\n if (!authServerUrl) {\n // Array has length > 0 but first element is undefined/null - skip this path\n return { supportsDcr: false };\n }\n const capabilities = await resolveCapabilitiesFromAuthorizationServer(authServerUrl, resourceMetadata.scopes_supported, allowLoopback);\n if (capabilities) {\n return capabilities;\n }\n\n const issuer = await discoverAuthorizationServerIssuer(baseUrl);\n if (issuer) {\n const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, resourceMetadata.scopes_supported, allowLoopback);\n if (issuerCapabilities) return issuerCapabilities;\n }\n }\n\n const issuer = await discoverAuthorizationServerIssuer(normalizedBaseUrl);\n if (issuer) {\n const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, undefined, allowLoopback);\n if (issuerCapabilities) return issuerCapabilities;\n }\n\n // Strategy 2: Fall back to direct RFC 8414 discovery at resource origin\n // This handles same-domain OAuth (traditional setup)\n const origin = getOrigin(normalizedBaseUrl);\n const originCapabilities = await resolveCapabilitiesFromAuthorizationServer(origin, undefined, allowLoopback);\n if (originCapabilities) return originCapabilities;\n\n // No OAuth metadata found\n return { supportsDcr: false };\n } catch (_error) {\n // Network error, invalid JSON, or other fetch failure\n // Gracefully degrade - assume no DCR support\n return { supportsDcr: false };\n }\n}\n"],"names":["normalizeUrl","isLoopbackUrl","discoverAuthorizationServerIssuer","discoverAuthorizationServerMetadata","discoverProtectedResourceMetadata","getOrigin","url","URL","origin","buildCapabilities","metadata","scopes","supportsDcr","registration_endpoint","capabilities","authorizationResponseIssSupported","authorization_response_iss_parameter_supported","issuer","registrationEndpoint","authorization_endpoint","authorizationEndpoint","token_endpoint","tokenEndpoint","introspection_endpoint","introspectionEndpoint","length","scopes_supported","resolveCapabilitiesFromAuthorizationServer","authServerUrl","allowLoopback","probeAuthCapabilities","baseUrl","normalizedBaseUrl","resourceMetadata","authorization_servers","issuerCapabilities","undefined","originCapabilities","_error"],"mappings":"AAAA;;;CAGC,GAED,SAASA,YAAY,QAAQ,sBAAsB;AACnD,SAASC,aAAa,QAAQ,uBAAuB;AACrD,SAASC,iCAAiC,EAAEC,mCAAmC,EAAEC,iCAAiC,QAAQ,yBAAyB;AAGnJ;;;;;;;;CAQC,GACD,SAASC,UAAUC,GAAW;IAC5B,IAAI;QACF,OAAO,IAAIC,IAAID,KAAKE,MAAM;IAC5B,EAAE,OAAM;QACN,sDAAsD;QACtD,OAAOF;IACT;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,SAASG,kBAAkBC,QAAqC,EAAEC,MAAiB;IACjF,MAAMC,cAAc,CAAC,CAACF,SAASG,qBAAqB;IACpD,MAAMC,eAAiC;QAAEF;QAAaG,mCAAmCL,SAASM,8CAA8C,KAAK;IAAK;IAE1J,IAAIN,SAASO,MAAM,EAAE;QACnBH,aAAaG,MAAM,GAAGP,SAASO,MAAM;IACvC;IAEA,IAAIP,SAASG,qBAAqB,EAAE;QAClCC,aAAaI,oBAAoB,GAAGR,SAASG,qBAAqB;IACpE;IACA,IAAIH,SAASS,sBAAsB,EAAE;QACnCL,aAAaM,qBAAqB,GAAGV,SAASS,sBAAsB;IACtE;IACA,IAAIT,SAASW,cAAc,EAAEP,aAAaQ,aAAa,GAAGZ,SAASW,cAAc;IACjF,IAAIX,SAASa,sBAAsB,EAAE;QACnCT,aAAaU,qBAAqB,GAAGd,SAASa,sBAAsB;IACtE;IAEA,IAAIZ,UAAUA,OAAOc,MAAM,GAAG,GAAG;QAC/BX,aAAaH,MAAM,GAAGA;IACxB,OAAO,IAAID,SAASgB,gBAAgB,EAAE;QACpCZ,aAAaH,MAAM,GAAGD,SAASgB,gBAAgB;IACjD;IAEA,OAAOZ;AACT;AAEA,eAAea,2CAA2CC,aAAqB,EAAEjB,MAA4B,EAA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QACf,sDAAsD;QACtD,6CAA6C;QAC7C,OAAO;YAAE1B,aAAa;QAAM;IAC9B;AACF"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export declare class DiscoveryFetchError extends Error {
|
|
2
|
+
constructor(message: string);
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* True if `rawUrl`'s host is loopback, used to decide `allowLoopback` grants
|
|
6
|
+
* from the URL the caller configured, not remote-supplied data. Fails closed on an unparseable URL.
|
|
7
|
+
*/
|
|
8
|
+
export declare function isLoopbackUrl(rawUrl: string): boolean;
|
|
9
|
+
export interface DiscoveryFetchOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Loopback trust grant for this fetch, computed from the server the caller
|
|
12
|
+
* is actually talking to - never from the URL being fetched. Defaults to `false`.
|
|
13
|
+
*/
|
|
14
|
+
allowLoopback?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Per-request connect/read timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`;
|
|
17
|
+
* overridable so tests can bound slow-failure cases.
|
|
18
|
+
*/
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Fetches an OAuth-discovery URL with SSRF mitigations applied to the
|
|
23
|
+
* initial URL and every redirect hop; redirects are validated, not auto-followed.
|
|
24
|
+
*
|
|
25
|
+
* @param rawUrl - URL to fetch; may be remote-server-supplied (the threat this guards against).
|
|
26
|
+
* @param init - Standard fetch options; `redirect` is always forced to `'manual'`.
|
|
27
|
+
* @param context - Short label used only in error messages, never echoing the URL.
|
|
28
|
+
* @param options - See `DiscoveryFetchOptions`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function discoveryFetch(rawUrl: string, init?: RequestInit, context?: string, options?: DiscoveryFetchOptions): Promise<Response>;
|
|
31
|
+
/**
|
|
32
|
+
* Parse a `discoveryFetch` response body as JSON, enforcing `MAX_BODY_BYTES`
|
|
33
|
+
* while reading (not after buffering the whole thing).
|
|
34
|
+
*/
|
|
35
|
+
export declare function readDiscoveryJson<T>(response: Response, context: string): Promise<T>;
|