@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.
Files changed (68) hide show
  1. package/README.md +5 -1
  2. package/dist/cjs/auth/capability-discovery.js +18 -8
  3. package/dist/cjs/auth/capability-discovery.js.map +1 -1
  4. package/dist/cjs/auth/discovery-fetch.d.cts +35 -0
  5. package/dist/cjs/auth/discovery-fetch.d.ts +35 -0
  6. package/dist/cjs/auth/discovery-fetch.js +658 -0
  7. package/dist/cjs/auth/discovery-fetch.js.map +1 -0
  8. package/dist/cjs/auth/index.d.cts +1 -0
  9. package/dist/cjs/auth/index.d.ts +1 -0
  10. package/dist/cjs/auth/index.js +7 -0
  11. package/dist/cjs/auth/index.js.map +1 -1
  12. package/dist/cjs/auth/interactive-oauth-flow.d.cts +20 -13
  13. package/dist/cjs/auth/interactive-oauth-flow.d.ts +20 -13
  14. package/dist/cjs/auth/interactive-oauth-flow.js +48 -24
  15. package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
  16. package/dist/cjs/auth/oauth-callback-listener.js +4 -0
  17. package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
  18. package/dist/cjs/auth/rfc9728-discovery.d.cts +12 -25
  19. package/dist/cjs/auth/rfc9728-discovery.d.ts +12 -25
  20. package/dist/cjs/auth/rfc9728-discovery.js +59 -48
  21. package/dist/cjs/auth/rfc9728-discovery.js.map +1 -1
  22. package/dist/cjs/auth/types.d.cts +34 -4
  23. package/dist/cjs/auth/types.d.ts +34 -4
  24. package/dist/cjs/auth/types.js.map +1 -1
  25. package/dist/cjs/dcr/dcr-authenticator.d.cts +9 -5
  26. package/dist/cjs/dcr/dcr-authenticator.d.ts +9 -5
  27. package/dist/cjs/dcr/dcr-authenticator.js +436 -43
  28. package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
  29. package/dist/cjs/dcr/dynamic-client-registrar.d.cts +7 -18
  30. package/dist/cjs/dcr/dynamic-client-registrar.d.ts +7 -18
  31. package/dist/cjs/dcr/dynamic-client-registrar.js +18 -25
  32. package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
  33. package/dist/cjs/index.d.cts +1 -0
  34. package/dist/cjs/index.d.ts +1 -0
  35. package/dist/cjs/index.js +7 -0
  36. package/dist/cjs/index.js.map +1 -1
  37. package/dist/cjs/lib/url-utils.js +2 -2
  38. package/dist/cjs/lib/url-utils.js.map +1 -1
  39. package/dist/esm/auth/capability-discovery.js +17 -7
  40. package/dist/esm/auth/capability-discovery.js.map +1 -1
  41. package/dist/esm/auth/discovery-fetch.d.ts +35 -0
  42. package/dist/esm/auth/discovery-fetch.js +184 -0
  43. package/dist/esm/auth/discovery-fetch.js.map +1 -0
  44. package/dist/esm/auth/index.d.ts +1 -0
  45. package/dist/esm/auth/index.js +1 -0
  46. package/dist/esm/auth/index.js.map +1 -1
  47. package/dist/esm/auth/interactive-oauth-flow.d.ts +20 -13
  48. package/dist/esm/auth/interactive-oauth-flow.js +50 -23
  49. package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
  50. package/dist/esm/auth/oauth-callback-listener.js +4 -0
  51. package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
  52. package/dist/esm/auth/rfc9728-discovery.d.ts +12 -25
  53. package/dist/esm/auth/rfc9728-discovery.js +49 -56
  54. package/dist/esm/auth/rfc9728-discovery.js.map +1 -1
  55. package/dist/esm/auth/types.d.ts +34 -4
  56. package/dist/esm/auth/types.js.map +1 -1
  57. package/dist/esm/dcr/dcr-authenticator.d.ts +9 -5
  58. package/dist/esm/dcr/dcr-authenticator.js +92 -39
  59. package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
  60. package/dist/esm/dcr/dynamic-client-registrar.d.ts +7 -18
  61. package/dist/esm/dcr/dynamic-client-registrar.js +19 -23
  62. package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
  63. package/dist/esm/index.d.ts +1 -0
  64. package/dist/esm/index.js +1 -0
  65. package/dist/esm/index.js.map +1 -1
  66. package/dist/esm/lib/url-utils.js +2 -2
  67. package/dist/esm/lib/url-utils.js.map +1 -1
  68. package/package.json +3 -8
@@ -5,12 +5,29 @@
5
5
  import * as fs from 'fs';
6
6
  import Keyv from 'keyv';
7
7
  import { KeyvFile } from 'keyv-file';
8
+ import { isLoopbackUrl } from '../auth/discovery-fetch.js';
8
9
  import { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.js';
10
+ import { normalizeUrl } from '../lib/url-utils.js';
9
11
  import { logger as defaultLogger } from '../utils/logger.js';
10
12
  import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
11
13
  /**
12
14
  * Buffer time before token expiry to trigger proactive refresh (5 minutes)
13
15
  */ const REFRESH_BUFFER_MS = 5 * 60 * 1000;
16
+ /** Raised when a credential cannot be bound to, or looked up by, an issuer. */ let CredentialBindingError = class CredentialBindingError extends Error {
17
+ constructor(message){
18
+ super(message);
19
+ this.name = 'CredentialBindingError';
20
+ }
21
+ };
22
+ /**
23
+ * The issuer credentials are keyed by, so they can never be presented to a
24
+ * different authorization server even when the resource keeps its URL (SEP-2352).
25
+ */ function requireIssuer(capabilities) {
26
+ if (!capabilities.issuer) {
27
+ throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');
28
+ }
29
+ return capabilities.issuer;
30
+ }
14
31
  /**
15
32
  * DcrAuthenticator manages authentication for MCP HTTP servers
16
33
  * Handles DCR registration, OAuth flows, and token management
@@ -57,9 +74,14 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
57
74
  * Handle authentication for self-hosted DCR servers
58
75
  * Self-hosted servers manage their own token storage via /oauth/verify
59
76
  */ async ensureAuthenticatedSelfHosted(baseUrl, capabilities) {
60
- const dcrTokenKey = `dcr-tokens:${baseUrl}`;
77
+ // Loopback trust for every discovery-derived fetch below, computed from
78
+ // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).
79
+ const allowLoopback = isLoopbackUrl(baseUrl);
80
+ const issuer = requireIssuer(capabilities);
81
+ const resource = normalizeUrl(baseUrl);
82
+ const dcrTokenKey = `dcr-tokens:${issuer}:${resource}`;
61
83
  // 1. Check for existing DCR tokens (different from external tokens)
62
- let tokens = await this.tokenStore.get(dcrTokenKey);
84
+ let tokens = await this.loadTokens(dcrTokenKey, issuer);
63
85
  if (tokens) {
64
86
  // 2. Verify token is still valid by calling /oauth/verify
65
87
  try {
@@ -94,19 +116,11 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
94
116
  // Register OAuth client via DCR
95
117
  this.logger.debug('📝 Registering OAuth client with self-hosted server...');
96
118
  const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {
97
- redirectUri: this.redirectUri
119
+ redirectUri: this.redirectUri,
120
+ allowLoopback
98
121
  });
99
122
  // Perform OAuth authorization flow with PKCE (RFC 7636)
100
- const flowOptions = {
101
- port,
102
- headless: this.headless,
103
- redirectUri: this.redirectUri,
104
- pkce: true,
105
- logger: this.logger
106
- };
107
- if (capabilities.scopes) {
108
- flowOptions.scopes = capabilities.scopes;
109
- }
123
+ const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
110
124
  tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);
111
125
  // For self-hosted mode, verify the token works with /oauth/verify immediately
112
126
  try {
@@ -130,23 +144,31 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
130
144
  throw new Error('Self-hosted DCR authentication completed but token verification failed');
131
145
  }
132
146
  // Save tokens for future use
133
- await this.tokenStore.set(dcrTokenKey, tokens);
147
+ await this.tokenStore.set(dcrTokenKey, {
148
+ ...tokens,
149
+ issuer
150
+ });
134
151
  this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');
135
152
  return tokens;
136
153
  }
137
- /**
138
- * Handle authentication for external OAuth providers (original implementation)
139
- */ async ensureAuthenticatedExternal(baseUrl, capabilities) {
140
- const tokenKey = `tokens:${baseUrl}`;
154
+ /** Handles authentication for external (non-self-hosted) OAuth providers. */ async ensureAuthenticatedExternal(baseUrl, capabilities) {
155
+ // See ensureAuthenticatedSelfHosted - same loopback trust rule.
156
+ const allowLoopback = isLoopbackUrl(baseUrl);
157
+ const issuer = requireIssuer(capabilities);
158
+ const resource = normalizeUrl(baseUrl);
159
+ const tokenKey = `tokens:${issuer}:${resource}`;
141
160
  // 1. Check for existing tokens
142
- let tokens = await this.tokenStore.get(tokenKey);
161
+ let tokens = await this.loadTokens(tokenKey, issuer);
143
162
  if (tokens) {
144
163
  // 2. Proactive refresh if token expires within 5 minutes
145
164
  if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {
146
165
  this.logger.debug('🔄 Refreshing access token...');
147
166
  try {
148
- tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint);
149
- await this.tokenStore.set(tokenKey, tokens);
167
+ tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback);
168
+ await this.tokenStore.set(tokenKey, {
169
+ ...tokens,
170
+ issuer
171
+ });
150
172
  this.logger.debug('✅ Token refreshed successfully');
151
173
  } catch (_error) {
152
174
  // Refresh failed - clear tokens and re-authenticate
@@ -169,28 +191,25 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
169
191
  // Register OAuth client via DCR
170
192
  this.logger.debug('📝 Registering OAuth client...');
171
193
  const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {
172
- redirectUri: this.redirectUri
194
+ redirectUri: this.redirectUri,
195
+ allowLoopback
173
196
  });
174
197
  // Perform OAuth authorization flow with PKCE (RFC 7636)
175
- const flowOptions = {
176
- port,
177
- headless: this.headless,
178
- redirectUri: this.redirectUri,
179
- pkce: true,
180
- logger: this.logger
181
- };
182
- if (capabilities.scopes) {
183
- flowOptions.scopes = capabilities.scopes;
184
- }
198
+ const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
185
199
  tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);
186
200
  // Save tokens for future use
187
- await this.tokenStore.set(tokenKey, tokens);
201
+ await this.tokenStore.set(tokenKey, {
202
+ ...tokens,
203
+ issuer
204
+ });
188
205
  this.logger.debug('✅ Authentication successful, tokens saved');
189
206
  return tokens;
190
207
  }
191
208
  /**
192
- * Refresh access token using refresh token
193
- */ async refreshTokens(tokens, tokenEndpoint) {
209
+ * Refreshes an access token using a refresh token.
210
+ * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).
211
+ * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.
212
+ */ async refreshTokens(tokens, tokenEndpoint, resource, allowLoopback = false) {
194
213
  if (!tokenEndpoint) {
195
214
  throw new Error('Token endpoint not available for refresh');
196
215
  }
@@ -200,15 +219,49 @@ import { DynamicClientRegistrar } from './dynamic-client-registrar.js';
200
219
  if (!tokens.clientId || !tokens.clientSecret) {
201
220
  throw new Error('Client credentials not available for refresh');
202
221
  }
203
- return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret);
222
+ return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback);
204
223
  }
205
224
  /**
206
- * Delete stored tokens for a server
225
+ * Deletes both stored token families for a server, across every issuer they were bound to.
226
+ * @throws CredentialBindingError if the configured store cannot enumerate keys.
207
227
  */ async deleteTokens(baseUrl) {
208
- const tokenKey = `tokens:${baseUrl}`;
209
- await this.tokenStore.delete(tokenKey);
228
+ const suffix = `:${normalizeUrl(baseUrl)}`;
229
+ if (!this.tokenStore.iterator) {
230
+ throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');
231
+ }
232
+ for await (const [key] of this.tokenStore.iterator(this.tokenStore.namespace)){
233
+ if (typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix)) {
234
+ await this.tokenStore.delete(key);
235
+ }
236
+ }
210
237
  this.logger.debug(`🗑️ Deleted tokens for ${baseUrl}`);
211
238
  }
239
+ /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */ async loadTokens(key, issuer) {
240
+ const tokens = await this.tokenStore.get(key);
241
+ if (!tokens) return undefined;
242
+ if (tokens.issuer === issuer) return tokens;
243
+ this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');
244
+ await this.tokenStore.delete(key);
245
+ return undefined;
246
+ }
247
+ buildFlowOptions(port, capabilities, issuer, resource, allowLoopback) {
248
+ var _capabilities_authorizationResponseIssSupported;
249
+ const flowOptions = {
250
+ port,
251
+ issuer,
252
+ resource,
253
+ headless: this.headless,
254
+ redirectUri: this.redirectUri,
255
+ pkce: true,
256
+ logger: this.logger,
257
+ allowLoopback,
258
+ authorizationResponseIssSupported: (_capabilities_authorizationResponseIssSupported = capabilities.authorizationResponseIssSupported) !== null && _capabilities_authorizationResponseIssSupported !== void 0 ? _capabilities_authorizationResponseIssSupported : false
259
+ };
260
+ if (capabilities.scopes) {
261
+ flowOptions.scopes = capabilities.scopes;
262
+ }
263
+ return flowOptions;
264
+ }
212
265
  constructor(options){
213
266
  var _options_logger;
214
267
  if (options.tokenStore) {
@@ -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":["path","fs","Keyv","KeyvFile","InteractiveOAuthFlow","logger","defaultLogger","DynamicClientRegistrar","REFRESH_BUFFER_MS","DcrAuthenticator","detectSelfHostedMode","baseUrl","includes","_error","ensureAuthenticated","capabilities","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","dcrTokenKey","tokens","tokenStore","get","verifyUrl","verifyResponse","fetch","headers","Authorization","accessToken","Connection","ok","verifyData","json","token","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","Error","debug","port","parseInt","URL","redirectUri","startsWith","client","dcrClient","registerClient","flowOptions","headless","pkce","scopes","oauthFlow","performAuthFlow","clientId","clientSecret","status","error","message","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","options","storePath","join","process","cwd","mkdirSync","dirname","recursive","store","filename"],"mappings":"AAAA;;;CAGC,GAED,OAAOA,UAAU,YAAY;AAC7B,YAAYC,QAAQ,KAAK;AACzB,OAAOC,UAAU,OAAO;AACxB,SAASC,QAAQ,QAAQ,YAAY;AACrC,SAASC,oBAAoB,QAAQ,oCAAoC;AAEzE,SAASC,UAAUC,aAAa,QAAqB,qBAAqB;AAC1E,SAASC,sBAAsB,QAAQ,gCAAgC;AAgBvE;;CAEC,GACD,MAAMC,oBAAoB,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F"}
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":["path","fs","Keyv","KeyvFile","isLoopbackUrl","InteractiveOAuthFlow","normalizeUrl","logger","defaultLogger","DynamicClientRegistrar","REFRESH_BUFFER_MS","CredentialBindingError","Error","message","name","requireIssuer","capabilities","issuer","DcrAuthenticator","detectSelfHostedMode","baseUrl","includes","_error","ensureAuthenticated","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","allowLoopback","resource","dcrTokenKey","tokens","loadTokens","verifyUrl","verifyResponse","fetch","headers","Authorization","accessToken","Connection","ok","verifyData","json","token","tokenStore","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","debug","port","parseInt","URL","redirectUri","startsWith","client","dcrClient","registerClient","flowOptions","buildFlowOptions","oauthFlow","performAuthFlow","clientId","clientSecret","status","error","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","suffix","iterator","key","namespace","endsWith","get","headless","pkce","authorizationResponseIssSupported","scopes","options","storePath","join","process","cwd","mkdirSync","dirname","recursive","store","filename"],"mappings":"AAAA;;;CAGC,GAED,OAAOA,UAAU,YAAY;AAC7B,YAAYC,QAAQ,KAAK;AACzB,OAAOC,UAAU,OAAO;AACxB,SAASC,QAAQ,QAAQ,YAAY;AACrC,SAASC,aAAa,QAAQ,6BAA6B;AAC3D,SAASC,oBAAoB,QAAQ,oCAAoC;AAEzE,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,UAAUC,aAAa,QAAqB,qBAAqB;AAC1E,SAASC,sBAAsB,QAAQ,gCAAgC;AAgBvE;;CAEC,GACD,MAAMC,oBAAoB,IAAI,KAAK;AAEnC,6EAA6E,GAC7E,IAAA,AAAMC,yBAAN,MAAMA,+BAA+BC;IACnC,YAAYC,OAAe,CAAE;QAC3B,KAAK,CAACA;QACN,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA;;;CAGC,GACD,SAASC,cAAcC,YAA8B;IACnD,IAAI,CAACA,aAAaC,MAAM,EAAE;QACxB,MAAM,IAAIN,uBAAuB;IACnC;IACA,OAAOK,aAAaC,MAAM;AAC5B;AAEA;;;CAGC,GACD,OAAO,MAAMC;IA6BX;;;GAGC,GACD,MAAcC,qBAAqBC,OAAe,EAAoB;QACpE,IAAI;YACF,+DAA+D;YAC/D,oEAAoE;YACpE,2EAA2E;YAC3E,qDAAqD;YACrD,OAAOA,QAAQC,QAAQ,CAAC,gBAAgB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B,EAAEC,MAAc,EAAEW,QAAgB,EAAED,aAAsB,EAAoB;YAU5GX;QATrC,MAAM0C,cAAgC;YACpCR;YACAjC;YACAW;YACAsD,UAAU,IAAI,CAACA,QAAQ;YACvB7B,aAAa,IAAI,CAACA,WAAW;YAC7B8B,MAAM;YACN5E,QAAQ,IAAI,CAACA,MAAM;YACnBoB;YACAyD,iCAAiC,GAAEpE,kDAAAA,aAAaoE,iCAAiC,cAA9CpE,6DAAAA,kDAAkD;QACvF;QACA,IAAIA,aAAaqE,MAAM,EAAE;YACvB3B,YAAY2B,MAAM,GAAGrE,aAAaqE,MAAM;QAC1C;QACA,OAAO3B;IACT;IA1RA,YAAY4B,OAAgC,CAAE;YAkB9BA;QAjBd,IAAIA,QAAQ3C,UAAU,EAAE;YACtB,IAAI,CAACA,UAAU,GAAG2C,QAAQ3C,UAAU;QACtC,OAAO;YACL,sDAAsD;YACtD,MAAM4C,YAAYvF,KAAKwF,IAAI,CAACC,QAAQC,GAAG,IAAI,UAAU;YAErD,gDAAgD;YAChDzF,GAAG0F,SAAS,CAAC3F,KAAK4F,OAAO,CAACL,YAAY;gBAAEM,WAAW;YAAK;YAExD,IAAI,CAAClD,UAAU,GAAG,IAAIzC,KAAK;gBACzB4F,OAAO,IAAI3F,SAAS;oBAAE4F,UAAUR;gBAAU;YAC5C;QACF;QACA,IAAI,CAAC/B,SAAS,GAAG,IAAI/C;QACrB,IAAI,CAACmD,SAAS,GAAG,IAAIvD;QACrB,IAAI,CAAC6E,QAAQ,GAAGI,QAAQJ,QAAQ,IAAI;QACpC,IAAI,CAAC7B,WAAW,GAAGiC,QAAQjC,WAAW;QACtC,IAAI,CAAC9C,MAAM,IAAG+E,kBAAAA,QAAQ/E,MAAM,cAAd+E,6BAAAA,kBAAkB9E;IAClC;AAwQF"}
@@ -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
- * Register a new OAuth client with the authorization server
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
- * @example
20
- * const registrar = new DynamicClientRegistrar();
21
- * const creds = await registrar.registerClient(
22
- * 'https://example.com/oauth/register',
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?: DcrRegistrationOptions): Promise<ClientCredentials>;
16
+ registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials>;
28
17
  }
@@ -1,32 +1,21 @@
1
1
  /**
2
2
  * Dynamic Client Registration (DCR) Client
3
3
  * Implements RFC 7591 for OAuth client registration
4
- */ /**
5
- * DynamicClientRegistrar handles Dynamic Client Registration with OAuth servers
6
- */ export class DynamicClientRegistrar {
4
+ */ import { discoveryFetch } from '../auth/discovery-fetch.js';
5
+ /** Handles Dynamic Client Registration with OAuth servers. */ export class DynamicClientRegistrar {
7
6
  /**
8
- * Register a new OAuth client with the authorization server
7
+ * Registers a new OAuth client with the authorization server (RFC 7591).
9
8
  *
10
- * @param registrationEndpoint - DCR registration endpoint URL
11
- * @param options - Registration options (client name, redirect URI)
12
- * @returns Client credentials (client ID and secret)
13
- *
14
- * @throws Error if registration fails or server returns error
15
- *
16
- * @example
17
- * const registrar = new DynamicClientRegistrar();
18
- * const creds = await registrar.registerClient(
19
- * 'https://example.com/oauth/register',
20
- * { clientName: '@mcp-z/client', redirectUri: 'http://localhost:3000/callback' }
21
- * );
22
- * console.log('Client ID:', creds.clientId);
23
- */ async registerClient(registrationEndpoint, options = {}) {
9
+ * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.
10
+ * @param options - Registration options (redirect URI, client name, loopback trust).
11
+ * @returns Client credentials (client ID and secret).
12
+ * @throws Error if registration fails or the server returns an error.
13
+ */ async registerClient(registrationEndpoint, options) {
14
+ var _options_allowLoopback;
24
15
  const requestBody = {
25
16
  client_name: options.clientName || '@mcp-z/client',
26
- redirect_uris: options.redirectUri ? [
17
+ redirect_uris: [
27
18
  options.redirectUri
28
- ] : [
29
- 'http://localhost:3000/callback'
30
19
  ],
31
20
  grant_types: [
32
21
  'authorization_code',
@@ -35,9 +24,14 @@
35
24
  response_types: [
36
25
  'code'
37
26
  ],
38
- token_endpoint_auth_method: 'client_secret_basic'
27
+ token_endpoint_auth_method: 'client_secret_basic',
28
+ // The callback listener always binds an OS-assigned loopback port, so the
29
+ // redirect URI is one an authorization server rejects for a web client (SEP-837, RFC 8252).
30
+ application_type: 'native'
39
31
  };
40
- const response = await fetch(registrationEndpoint, {
32
+ // registrationEndpoint is remote-controlled discovery data; allowLoopback
33
+ // must come from the caller's own trust, never from registrationEndpoint.
34
+ const response = await discoveryFetch(registrationEndpoint, {
41
35
  method: 'POST',
42
36
  headers: {
43
37
  'Content-Type': 'application/json',
@@ -45,6 +39,8 @@
45
39
  Connection: 'close'
46
40
  },
47
41
  body: JSON.stringify(requestBody)
42
+ }, 'registration endpoint', {
43
+ allowLoopback: (_options_allowLoopback = options.allowLoopback) !== null && _options_allowLoopback !== void 0 ? _options_allowLoopback : false
48
44
  });
49
45
  if (!response.ok) {
50
46
  const errorText = await response.text();
@@ -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/**\n * DCR Registration Request (RFC 7591)\n */\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}\n\n/**\n * DCR Registration Response (RFC 7591)\n */\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/**\n * DynamicClientRegistrar handles Dynamic Client Registration with OAuth servers\n */\nexport class DynamicClientRegistrar {\n /**\n * Register a new OAuth client with the authorization server\n *\n * @param registrationEndpoint - DCR registration endpoint URL\n * @param options - Registration options (client name, redirect URI)\n * @returns Client credentials (client ID and secret)\n *\n * @throws Error if registration fails or server returns error\n *\n * @example\n * const registrar = new DynamicClientRegistrar();\n * const creds = await registrar.registerClient(\n * 'https://example.com/oauth/register',\n * { clientName: '@mcp-z/client', redirectUri: 'http://localhost:3000/callback' }\n * );\n * console.log('Client ID:', creds.clientId);\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 ? [options.redirectUri] : ['http://localhost:3000/callback'],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'client_secret_basic',\n };\n\n const response = await fetch(registrationEndpoint, {\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\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","client_name","clientName","redirect_uris","redirectUri","grant_types","response_types","token_endpoint_auth_method","response","fetch","method","headers","Accept","Connection","body","JSON","stringify","ok","errorText","text","Error","status","data","json","client_id","credentials","clientId","clientSecret","client_secret","client_id_issued_at","issuedAt"],"mappings":"AAAA;;;CAGC,GAyBD;;CAEC,GACD,OAAO,MAAMA;IACX;;;;;;;;;;;;;;;;GAgBC,GACD,MAAMC,eAAeC,oBAA4B,EAAEC,UAAkC,CAAC,CAAC,EAA8B;QACnH,MAAMC,cAAsC;YAC1CC,aAAaF,QAAQG,UAAU,IAAI;YACnCC,eAAeJ,QAAQK,WAAW,GAAG;gBAACL,QAAQK,WAAW;aAAC,GAAG;gBAAC;aAAiC;YAC/FC,aAAa;gBAAC;gBAAsB;aAAgB;YACpDC,gBAAgB;gBAAC;aAAO;YACxBC,4BAA4B;QAC9B;QAEA,MAAMC,WAAW,MAAMC,MAAMX,sBAAsB;YACjDY,QAAQ;YACRC,SAAS;gBACP,gBAAgB;gBAChBC,QAAQ;gBACRC,YAAY;YACd;YACAC,MAAMC,KAAKC,SAAS,CAAChB;QACvB;QAEA,IAAI,CAACQ,SAASS,EAAE,EAAE;YAChB,MAAMC,YAAY,MAAMV,SAASW,IAAI;YACrC,MAAM,IAAIC,MAAM,CAAC,yBAAyB,EAAEZ,SAASa,MAAM,CAAC,GAAG,EAAEH,WAAW;QAC9E;QAEA,MAAMI,OAAQ,MAAMd,SAASe,IAAI;QAEjC,IAAI,CAACD,KAAKE,SAAS,EAAE;YACnB,MAAM,IAAIJ,MAAM;QAClB;QAEA,MAAMK,cAAiC;YACrCC,UAAUJ,KAAKE,SAAS;YACxBG,cAAcL,KAAKM,aAAa,IAAI;QACtC;QAEA,IAAIN,KAAKO,mBAAmB,EAAE;YAC5BJ,YAAYK,QAAQ,GAAGR,KAAKO,mBAAmB;QACjD;QAEA,OAAOJ;IACT;AACF"}
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":["discoveryFetch","DynamicClientRegistrar","registerClient","registrationEndpoint","options","requestBody","client_name","clientName","redirect_uris","redirectUri","grant_types","response_types","token_endpoint_auth_method","application_type","response","method","headers","Accept","Connection","body","JSON","stringify","allowLoopback","ok","errorText","text","Error","status","data","json","client_id","credentials","clientId","clientSecret","client_secret","client_id_issued_at","issuedAt"],"mappings":"AAAA;;;CAGC,GAED,SAASA,cAAc,QAAQ,6BAA6B;AAqB5D,4DAA4D,GAC5D,OAAO,MAAMC;IACX;;;;;;;GAOC,GACD,MAAMC,eAAeC,oBAA4B,EAAEC,OAA+B,EAA8B;YA0B3FA;QAzBnB,MAAMC,cAAsC;YAC1CC,aAAaF,QAAQG,UAAU,IAAI;YACnCC,eAAe;gBAACJ,QAAQK,WAAW;aAAC;YACpCC,aAAa;gBAAC;gBAAsB;aAAgB;YACpDC,gBAAgB;gBAAC;aAAO;YACxBC,4BAA4B;YAC5B,0EAA0E;YAC1E,4FAA4F;YAC5FC,kBAAkB;QACpB;QAEA,0EAA0E;QAC1E,0EAA0E;QAC1E,MAAMC,WAAW,MAAMd,eACrBG,sBACA;YACEY,QAAQ;YACRC,SAAS;gBACP,gBAAgB;gBAChBC,QAAQ;gBACRC,YAAY;YACd;YACAC,MAAMC,KAAKC,SAAS,CAAChB;QACvB,GACA,yBACA;YAAEiB,aAAa,GAAElB,yBAAAA,QAAQkB,aAAa,cAArBlB,oCAAAA,yBAAyB;QAAM;QAGlD,IAAI,CAACU,SAASS,EAAE,EAAE;YAChB,MAAMC,YAAY,MAAMV,SAASW,IAAI;YACrC,MAAM,IAAIC,MAAM,CAAC,yBAAyB,EAAEZ,SAASa,MAAM,CAAC,GAAG,EAAEH,WAAW;QAC9E;QAEA,MAAMI,OAAQ,MAAMd,SAASe,IAAI;QAEjC,IAAI,CAACD,KAAKE,SAAS,EAAE;YACnB,MAAM,IAAIJ,MAAM;QAClB;QAEA,MAAMK,cAAiC;YACrCC,UAAUJ,KAAKE,SAAS;YACxBG,cAAcL,KAAKM,aAAa,IAAI;QACtC;QAEA,IAAIN,KAAKO,mBAAmB,EAAE;YAC5BJ,YAAYK,QAAQ,GAAGR,KAAKO,mBAAmB;QACjD;QAEA,OAAOJ;IACT;AACF"}
@@ -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/esm/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  */ // Config types (from schema)
4
4
  // Auth - OAuth utilities
5
5
  export { probeAuthCapabilities } from './auth/capability-discovery.js';
6
+ export { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.js';
6
7
  export { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.js';
7
8
  export { OAuthCallbackListener } from './auth/oauth-callback-listener.js';
8
9
  // Client helpers and lightweight overloads
@@ -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":["probeAuthCapabilities","InteractiveOAuthFlow","OAuthCallbackListener","decorateClient","validateServers","DcrAuthenticator","DynamicClientRegistrar","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","search","searchCapabilities","createServerRegistry","getLogLevel","logger","setLogLevel","resolveArgsPaths","resolvePath"],"mappings":"AAAA;;CAEC,GAED,6BAA6B;AAE7B,yBAAyB;AACzB,SAASA,qBAAqB,QAAQ,iCAAiC;AAEvE,SAASC,oBAAoB,QAAQ,mCAAmC;AACxE,SAASC,qBAAqB,QAAQ,oCAAoC;AAC1E,2CAA2C;AAC3C,SAASC,cAAc,QAA2I,sBAAsB;AACxL,oCAAoC;AACpC,SAAgCC,eAAe,QAAQ,8BAA8B;AAGrF,8CAA8C;AAC9C,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,sBAAsB,QAAQ,oCAAoC;AAE3E,SAKEC,mBAAmB,EACnBC,qBAAqB,EACrBC,qBAAqB,EACrBC,uBAAuB,EACvBC,iBAAiB,EACjBC,mBAAmB,QACd,yBAAyB;AAEhC,gCAAgC;AAChC,SAASC,oBAAoB,EAAEC,MAAM,EAAEC,kBAAkB,QAAQ,oBAAoB;AACrF,mCAAmC;AACnC,SAA6DC,oBAAoB,QAA+D,2BAA2B;AAE3K,2BAA2B;AAC3B,SAASC,WAAW,EAA8BC,MAAM,EAAEC,WAAW,QAAQ,oBAAoB;AACjG,SAASC,gBAAgB,EAAEC,WAAW,QAAQ,wBAAwB"}
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":["probeAuthCapabilities","DiscoveryFetchError","isLoopbackUrl","InteractiveOAuthFlow","OAuthCallbackListener","decorateClient","validateServers","DcrAuthenticator","DynamicClientRegistrar","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","search","searchCapabilities","createServerRegistry","getLogLevel","logger","setLogLevel","resolveArgsPaths","resolvePath"],"mappings":"AAAA;;CAEC,GAED,6BAA6B;AAE7B,yBAAyB;AACzB,SAASA,qBAAqB,QAAQ,iCAAiC;AACvE,SAASC,mBAAmB,EAAEC,aAAa,QAAQ,4BAA4B;AAE/E,SAASC,oBAAoB,QAAQ,mCAAmC;AACxE,SAASC,qBAAqB,QAAQ,oCAAoC;AAC1E,2CAA2C;AAC3C,SAASC,cAAc,QAA2I,sBAAsB;AACxL,oCAAoC;AACpC,SAAgCC,eAAe,QAAQ,8BAA8B;AAGrF,8CAA8C;AAC9C,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,sBAAsB,QAAQ,oCAAoC;AAE3E,SAKEC,mBAAmB,EACnBC,qBAAqB,EACrBC,qBAAqB,EACrBC,uBAAuB,EACvBC,iBAAiB,EACjBC,mBAAmB,QACd,yBAAyB;AAEhC,gCAAgC;AAChC,SAASC,oBAAoB,EAAEC,MAAM,EAAEC,kBAAkB,QAAQ,oBAAoB;AACrF,mCAAmC;AACnC,SAA6DC,oBAAoB,QAA+D,2BAA2B;AAE3K,2BAA2B;AAC3B,SAASC,WAAW,EAA8BC,MAAM,EAAEC,WAAW,QAAQ,oBAAoB;AACjG,SAASC,gBAAgB,EAAEC,WAAW,QAAQ,wBAAwB"}
@@ -3,8 +3,8 @@ export function normalizeUrl(input) {
3
3
  const url = new URL(input);
4
4
  url.search = '';
5
5
  url.hash = '';
6
- url.pathname = url.pathname.replace(/\/+$/, '');
7
- return url.origin + url.pathname;
6
+ // Strip after joining: assigning an empty pathname puts the '/' straight back.
7
+ return (url.origin + url.pathname).replace(/\/+$/, '');
8
8
  } catch {
9
9
  return input.replace(/\/+$/, '');
10
10
  }
@@ -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 url.pathname = url.pathname.replace(/\\/+$/, '');\n return url.origin + url.pathname;\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":["normalizeUrl","input","url","URL","search","hash","pathname","replace","origin","joinWellKnown","baseUrl","suffix"],"mappings":"AAAA,OAAO,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,MAAMC,MAAM,IAAIC,IAAIF;QACpBC,IAAIE,MAAM,GAAG;QACbF,IAAIG,IAAI,GAAG;QACXH,IAAII,QAAQ,GAAGJ,IAAII,QAAQ,CAACC,OAAO,CAAC,QAAQ;QAC5C,OAAOL,IAAIM,MAAM,GAAGN,IAAII,QAAQ;IAClC,EAAE,OAAM;QACN,OAAOL,MAAMM,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEA,OAAO,SAASE,cAAcC,OAAe,EAAEC,MAAc;IAC3D,OAAO,GAAGX,aAAaU,WAAWC,QAAQ;AAC5C"}
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":["normalizeUrl","input","url","URL","search","hash","origin","pathname","replace","joinWellKnown","baseUrl","suffix"],"mappings":"AAAA,OAAO,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,MAAMC,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,OAAM;QACN,OAAOP,MAAMO,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEA,OAAO,SAASC,cAAcC,OAAe,EAAEC,MAAc;IAC3D,OAAO,GAAGX,aAAaU,WAAWC,QAAQ;AAC5C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcp-z/client",
3
- "version": "1.1.1",
3
+ "version": "2.0.0",
4
4
  "description": "Programmatic MCP client library for Node.js - connect, discover, and call tools on Model Context Protocol servers.",
5
5
  "keywords": [
6
6
  "mcp",
@@ -53,7 +53,7 @@
53
53
  "format": "tsds format",
54
54
  "generate:types": "json2ts schemas/servers.schema.json schemas/servers.d.ts --bannerComment \"/* eslint-disable */\n/* Auto-generated from schemas/servers.schema.json - DO NOT EDIT */\"",
55
55
  "prepublish:check": "ncp",
56
- "prepublishOnly": "tsds validate",
56
+ "prepublishOnly": "node scripts/require-dist-tag.cjs && tsds validate",
57
57
  "test": "tsds test:node --no-timeouts",
58
58
  "test:engines": "nvu engines tsds test:node --no-timeouts",
59
59
  "version": "tsds version"
@@ -63,6 +63,7 @@
63
63
  "ajv": "^8.0.0",
64
64
  "ajv-formats": "^3.0.0",
65
65
  "get-port": "5.1.1",
66
+ "ipaddr.js": "^2.5.0",
66
67
  "keyv": "^5.0.0",
67
68
  "keyv-file": "5.3.3",
68
69
  "module-root-sync": "^2.0.0"
@@ -82,12 +83,6 @@
82
83
  "engines": {
83
84
  "node": ">=20"
84
85
  },
85
- "allowScripts": {
86
- "node-filename-to-dist-paths": true,
87
- "node-semvers": true,
88
- "node-version-use": true,
89
- "thread-sleep-compat": true
90
- },
91
86
  "tsds": {
92
87
  "source": "src/index.ts"
93
88
  }