@nest-mcp/client 1.0.2 → 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 (54) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +845 -69
  3. package/dist/ai-sdk/index.d.mts +14 -0
  4. package/dist/ai-sdk/index.d.mts.map +1 -0
  5. package/dist/ai-sdk/index.mjs +27 -0
  6. package/dist/ai-sdk/index.mjs.map +1 -0
  7. package/dist/bootstrap-BIAcDnHp.d.mts +394 -0
  8. package/dist/bootstrap-BIAcDnHp.d.mts.map +1 -0
  9. package/dist/index.d.mts +480 -0
  10. package/dist/index.d.mts.map +1 -0
  11. package/dist/index.mjs +1960 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/oauth/dynamic-registration.d.mts +92 -0
  14. package/dist/oauth/dynamic-registration.d.mts.map +1 -0
  15. package/dist/oauth/dynamic-registration.mjs +392 -0
  16. package/dist/oauth/dynamic-registration.mjs.map +1 -0
  17. package/dist/oauth/index.d.mts +422 -0
  18. package/dist/oauth/index.d.mts.map +1 -0
  19. package/dist/oauth/index.mjs +3349 -0
  20. package/dist/oauth/index.mjs.map +1 -0
  21. package/dist/scope-CxGBCDdr.mjs +22 -0
  22. package/dist/scope-CxGBCDdr.mjs.map +1 -0
  23. package/package.json +76 -50
  24. package/scripts/external-smoke.mjs +693 -0
  25. package/dist/decorators/inject-mcp-client.decorator.d.ts +0 -3
  26. package/dist/decorators/inject-mcp-client.decorator.js +0 -12
  27. package/dist/decorators/on-notification.decorator.d.ts +0 -7
  28. package/dist/decorators/on-notification.decorator.js +0 -13
  29. package/dist/health/mcp-client.health.d.ts +0 -20
  30. package/dist/health/mcp-client.health.js +0 -42
  31. package/dist/index.d.ts +0 -21
  32. package/dist/index.js +0 -64
  33. package/dist/interfaces/client-options.interface.d.ts +0 -139
  34. package/dist/interfaces/client-options.interface.js +0 -3
  35. package/dist/mcp-client.module.d.ts +0 -20
  36. package/dist/mcp-client.module.js +0 -188
  37. package/dist/mcp-client.service.d.ts +0 -558
  38. package/dist/mcp-client.service.js +0 -532
  39. package/dist/mcp-clients.service.d.ts +0 -39
  40. package/dist/mcp-clients.service.js +0 -104
  41. package/dist/testing/mock-client.d.ts +0 -67
  42. package/dist/testing/mock-client.js +0 -154
  43. package/dist/transport/apply-auth-headers.d.ts +0 -3
  44. package/dist/transport/apply-auth-headers.js +0 -13
  45. package/dist/transport/client-transport.factory.d.ts +0 -4
  46. package/dist/transport/client-transport.factory.js +0 -21
  47. package/dist/transport/sse-client.transport.d.ts +0 -4
  48. package/dist/transport/sse-client.transport.js +0 -15
  49. package/dist/transport/stdio-client.transport.d.ts +0 -4
  50. package/dist/transport/stdio-client.transport.js +0 -14
  51. package/dist/transport/streamable-client.transport.d.ts +0 -4
  52. package/dist/transport/streamable-client.transport.js +0 -17
  53. package/dist/utils/format-error-message.d.ts +0 -2
  54. package/dist/utils/format-error-message.js +0 -7
@@ -0,0 +1,3349 @@
1
+ import { n as isMcpClientOAuthScopeToken, t as MCP_CLIENT_OAUTH_MAX_SCOPE_LENGTH } from "../scope-CxGBCDdr.mjs";
2
+ import { Client, LATEST_PROTOCOL_VERSION, OAuthError, StreamableHTTPClientTransport, discoverAuthorizationServerMetadata, discoverOAuthProtectedResourceMetadata, exchangeAuthorization, refreshAuthorization, resourceUrlFromServerUrl, startAuthorization } from "@modelcontextprotocol/client";
3
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
4
+ import { captureMcpConformanceValue } from "@nest-mcp/conformance";
5
+ //#region src/oauth/credential-store.ts
6
+ /** Stable reasons used for exact-generation invalidation or disappearance notification. */
7
+ const McpClientOAuthCredentialInvalidationReason = {
8
+ Explicit: "explicit",
9
+ InvalidGrant: "invalid-grant",
10
+ /** The exact generation was absent when observed, without a local invalidation mutation. */
11
+ ObservedExternal: "observed-external",
12
+ TerminalRefreshFailure: "terminal-refresh-failure"
13
+ };
14
+ /** Validates and brands an exact positive credential revision. */
15
+ function createMcpClientOAuthCredentialRevision(value) {
16
+ if (!isMcpClientOAuthCredentialRevision(value)) throw new RangeError("An OAuth credential revision must be a positive safe integer.");
17
+ return value;
18
+ }
19
+ /** Runtime predicate for values crossing persistence or serialization boundaries. */
20
+ function isMcpClientOAuthCredentialRevision(value) {
21
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
22
+ }
23
+ /** Returns the only revision valid for a successful exact compare-and-swap. */
24
+ function nextMcpClientOAuthCredentialRevision(revision) {
25
+ return createMcpClientOAuthCredentialRevision(revision + 1);
26
+ }
27
+ /** Creates the frozen wrapper shared by stores and refresh callers. */
28
+ function createMcpClientOAuthCredentialSnapshot(revision, credential) {
29
+ assertCredentialObject(credential);
30
+ return Object.freeze({
31
+ revision: createMcpClientOAuthCredentialRevision(revision),
32
+ credential
33
+ });
34
+ }
35
+ function assertCredentialObject(credential) {
36
+ if (credential === null || typeof credential !== "object" && typeof credential !== "function") throw new TypeError("An OAuth credential snapshot must contain a credential object.");
37
+ }
38
+ //#endregion
39
+ //#region src/oauth/auth-provider.ts
40
+ const MAX_BEARER_TOKEN_LENGTH = 65536;
41
+ const BEARER_TOKEN_PATTERN = /^[-A-Za-z0-9._~+/]+=*$/u;
42
+ /** Stable, identity- and secret-free transport-bridge failures. */
43
+ const McpClientOAuthAuthProviderErrorCode = {
44
+ InvalidOptions: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_INVALID_OPTIONS",
45
+ Closed: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_CLOSED",
46
+ CredentialMissing: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_CREDENTIAL_MISSING",
47
+ CredentialRevisionChanged: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_CREDENTIAL_REVISION_CHANGED",
48
+ StoreFailed: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_STORE_FAILED",
49
+ InvalidStoreResult: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_STORE_RESULT_INVALID",
50
+ TokenMissing: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_TOKEN_MISSING",
51
+ TokenInvalid: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_TOKEN_INVALID",
52
+ TokenAccessorFailed: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_TOKEN_ACCESSOR_FAILED",
53
+ RefreshFailed: "MCP_CLIENT_OAUTH_AUTH_PROVIDER_REFRESH_FAILED"
54
+ };
55
+ /** Error whose public fields and message never contain an identity, token, or upstream response. */
56
+ var McpClientOAuthAuthProviderError = class extends Error {
57
+ code;
58
+ constructor(code) {
59
+ super(authProviderErrorMessage(code));
60
+ this.name = "McpClientOAuthAuthProviderError";
61
+ this.code = code;
62
+ }
63
+ };
64
+ /**
65
+ * Per-binding bridge from revisioned OAuth credentials to the SDK's minimal `AuthProvider`.
66
+ *
67
+ * It intentionally has no `tokens()` or `clientInformation()` members, so the official
68
+ * transport cannot classify it as an `OAuthClientProvider` and cannot start interactive or
69
+ * Dynamic Client Registration flows. The store and coordinator are borrowed; closing this
70
+ * bridge never closes either dependency. It follows successful credential revisions within one
71
+ * stable binding by default. Set expectedCredentialRevision for an operation that must close
72
+ * and be reacquired after rotation; its token and refresh paths both enforce the exact revision.
73
+ */
74
+ var McpClientOAuthAuthProvider = class {
75
+ #identity;
76
+ #expectedCredentialRevision;
77
+ #store;
78
+ #refreshCoordinator;
79
+ #selectBearerToken;
80
+ #lifecycleController = new AbortController();
81
+ #inFlight = /* @__PURE__ */ new Set();
82
+ #closed = false;
83
+ #closeTask;
84
+ constructor(options) {
85
+ const normalized = normalizeOptions(options);
86
+ this.#identity = normalized.identity;
87
+ this.#expectedCredentialRevision = normalized.expectedCredentialRevision;
88
+ this.#store = normalized.store;
89
+ this.#refreshCoordinator = normalized.refreshCoordinator;
90
+ this.#selectBearerToken = normalized.selectBearerToken;
91
+ }
92
+ get closed() {
93
+ return this.#closed;
94
+ }
95
+ /** Loads the authoritative generation on every request; no token is cached in the bridge. */
96
+ token() {
97
+ return this.#start(async () => {
98
+ const snapshot = await this.#loadCurrent();
99
+ return this.#readBearerToken(snapshot);
100
+ });
101
+ }
102
+ /**
103
+ * Refreshes exactly the authoritative revision loaded for this binding. Concurrent 401s join
104
+ * in the coordinator. A process-external claim or winner is accepted only after an authoritative
105
+ * reload; only a strictly newer revision completes this call, and this bridge never retries the
106
+ * stale refresh token. The
107
+ * SDK does not identify the failed request's credential revision in this callback. A delayed 401
108
+ * can therefore arrive after another request published a newer generation and refresh that newer
109
+ * generation. An expectedCredentialRevision fences this reload before refresh: a pinned provider
110
+ * never refreshes or adopts a replacement. Its successful refresh still publishes for a fresh
111
+ * acquisition, while the old operation fails closed. Unpinned hosts need request correlation
112
+ * or conservative close/reacquire; the transport bounds each wire request to one retry.
113
+ */
114
+ onUnauthorized(_context) {
115
+ return this.#start(async () => {
116
+ const current = await this.#loadCurrent();
117
+ let refreshed;
118
+ try {
119
+ refreshed = await this.#refreshCoordinator.refresh(this.#identity, current.revision, { signal: this.#lifecycleController.signal });
120
+ } catch {
121
+ this.#assertActive();
122
+ const winner = await this.#loadOptional();
123
+ if (winner !== void 0 && winner.revision > current.revision) {
124
+ await this.#readBearerToken(winner);
125
+ return;
126
+ }
127
+ throw refreshFailedError$1();
128
+ }
129
+ this.#assertActive();
130
+ const published = await this.#loadCurrent();
131
+ if (published.revision < refreshed.revision) throw invalidStoreResultError$1();
132
+ await this.#readBearerToken(published);
133
+ });
134
+ }
135
+ /** Fences new work, cancels this provider's waits, and drains all accepted bridge calls. */
136
+ close() {
137
+ if (this.#closeTask !== void 0) return this.#closeTask;
138
+ this.#closed = true;
139
+ this.#lifecycleController.abort(providerClosedAbortReason());
140
+ const accepted = [...this.#inFlight];
141
+ this.#closeTask = Promise.allSettled(accepted).then(() => void 0);
142
+ return this.#closeTask;
143
+ }
144
+ async [Symbol.asyncDispose]() {
145
+ await this.close();
146
+ }
147
+ #start(operation) {
148
+ if (this.#closed) return Promise.reject(providerClosedError());
149
+ const task = Promise.resolve().then(operation);
150
+ this.#inFlight.add(task);
151
+ const remove = () => {
152
+ this.#inFlight.delete(task);
153
+ };
154
+ task.then(remove, remove);
155
+ return task;
156
+ }
157
+ async #loadCurrent() {
158
+ const snapshot = await this.#loadOptional();
159
+ if (snapshot === void 0) throw credentialMissingError$1();
160
+ return snapshot;
161
+ }
162
+ async #loadOptional() {
163
+ this.#assertActive();
164
+ let snapshot;
165
+ try {
166
+ snapshot = await this.#store.load(this.#identity, Object.freeze({ signal: this.#lifecycleController.signal }));
167
+ } catch {
168
+ this.#assertActive();
169
+ throw storeFailedError$1();
170
+ }
171
+ this.#assertActive();
172
+ if (snapshot === void 0) return void 0;
173
+ let captured;
174
+ try {
175
+ if (!isMcpClientOAuthCredentialRevision(snapshot.revision) || !isObjectLike$1(snapshot.credential)) throw invalidStoreResultError$1();
176
+ captured = createMcpClientOAuthCredentialSnapshot(snapshot.revision, snapshot.credential);
177
+ } catch {
178
+ throw invalidStoreResultError$1();
179
+ }
180
+ if (this.#expectedCredentialRevision !== void 0 && captured.revision !== this.#expectedCredentialRevision) throw new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.CredentialRevisionChanged);
181
+ return captured;
182
+ }
183
+ async #readBearerToken(snapshot) {
184
+ this.#assertActive();
185
+ let token;
186
+ try {
187
+ token = await this.#selectBearerToken(snapshot, Object.freeze({ signal: this.#lifecycleController.signal }));
188
+ } catch {
189
+ this.#assertActive();
190
+ throw tokenAccessorFailedError();
191
+ }
192
+ this.#assertActive();
193
+ if (token === void 0) throw tokenMissingError();
194
+ if (!isValidBearerToken(token)) throw tokenInvalidError();
195
+ return token;
196
+ }
197
+ #assertActive() {
198
+ if (this.#closed || this.#lifecycleController.signal.aborted) throw providerClosedError();
199
+ }
200
+ };
201
+ function normalizeOptions(options) {
202
+ if (!isObjectLike$1(options)) throw invalidOptionsError$3();
203
+ let identity;
204
+ let expectedCredentialRevision;
205
+ let store;
206
+ let refreshCoordinator;
207
+ let selectBearerToken;
208
+ try {
209
+ identity = options.identity;
210
+ expectedCredentialRevision = options.expectedCredentialRevision;
211
+ store = options.store;
212
+ refreshCoordinator = options.refreshCoordinator;
213
+ selectBearerToken = options.selectBearerToken;
214
+ } catch {
215
+ throw invalidOptionsError$3();
216
+ }
217
+ let valid = false;
218
+ try {
219
+ valid = (expectedCredentialRevision === void 0 || isMcpClientOAuthCredentialRevision(expectedCredentialRevision)) && isObjectLike$1(store) && typeof store.load === "function" && typeof store.claimRefresh === "function" && typeof store.commitRefresh === "function" && typeof store.releaseRefreshClaim === "function" && typeof store.compareAndSwap === "function" && typeof store.invalidate === "function" && isObjectLike$1(refreshCoordinator) && typeof refreshCoordinator.refresh === "function" && typeof selectBearerToken === "function";
220
+ } catch {
221
+ valid = false;
222
+ }
223
+ if (!valid) throw invalidOptionsError$3();
224
+ return Object.freeze({
225
+ identity,
226
+ store,
227
+ refreshCoordinator,
228
+ selectBearerToken,
229
+ ...expectedCredentialRevision === void 0 ? {} : { expectedCredentialRevision }
230
+ });
231
+ }
232
+ function isObjectLike$1(value) {
233
+ return value !== null && (typeof value === "object" || typeof value === "function");
234
+ }
235
+ function isValidBearerToken(value) {
236
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_BEARER_TOKEN_LENGTH && BEARER_TOKEN_PATTERN.test(value);
237
+ }
238
+ function invalidOptionsError$3() {
239
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.InvalidOptions);
240
+ }
241
+ function providerClosedError() {
242
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.Closed);
243
+ }
244
+ function credentialMissingError$1() {
245
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.CredentialMissing);
246
+ }
247
+ function storeFailedError$1() {
248
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.StoreFailed);
249
+ }
250
+ function invalidStoreResultError$1() {
251
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.InvalidStoreResult);
252
+ }
253
+ function tokenMissingError() {
254
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.TokenMissing);
255
+ }
256
+ function tokenInvalidError() {
257
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.TokenInvalid);
258
+ }
259
+ function tokenAccessorFailedError() {
260
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.TokenAccessorFailed);
261
+ }
262
+ function refreshFailedError$1() {
263
+ return new McpClientOAuthAuthProviderError(McpClientOAuthAuthProviderErrorCode.RefreshFailed);
264
+ }
265
+ function authProviderErrorMessage(code) {
266
+ switch (code) {
267
+ case McpClientOAuthAuthProviderErrorCode.InvalidOptions: return "The OAuth auth-provider options are invalid.";
268
+ case McpClientOAuthAuthProviderErrorCode.Closed: return "The OAuth auth provider is closed and cannot accept new work.";
269
+ case McpClientOAuthAuthProviderErrorCode.CredentialMissing: return "The OAuth credential generation is unavailable.";
270
+ case McpClientOAuthAuthProviderErrorCode.CredentialRevisionChanged: return "The OAuth credential revision changed; acquire a new operation.";
271
+ case McpClientOAuthAuthProviderErrorCode.StoreFailed: return "The OAuth credential store operation failed.";
272
+ case McpClientOAuthAuthProviderErrorCode.InvalidStoreResult: return "The OAuth credential store returned an invalid result.";
273
+ case McpClientOAuthAuthProviderErrorCode.TokenMissing: return "The OAuth credential has no bearer token.";
274
+ case McpClientOAuthAuthProviderErrorCode.TokenInvalid: return "The OAuth bearer token is invalid.";
275
+ case McpClientOAuthAuthProviderErrorCode.TokenAccessorFailed: return "The OAuth bearer-token accessor failed.";
276
+ case McpClientOAuthAuthProviderErrorCode.RefreshFailed: return "The OAuth credential could not be refreshed.";
277
+ default: return "The OAuth auth provider failed.";
278
+ }
279
+ }
280
+ function providerClosedAbortReason() {
281
+ return new DOMException("The OAuth auth provider was closed.", "AbortError");
282
+ }
283
+ //#endregion
284
+ //#region src/oauth/state.ts
285
+ const OAUTH_STATE_DIGEST_DOMAIN = "nest-mcp.client.oauth-state.v1\0";
286
+ const SHA_256_BYTES = 32;
287
+ const SHA_256_BASE64URL_LENGTH = 43;
288
+ const DEFAULT_STATE_ENTROPY_BYTES = 32;
289
+ const MIN_STATE_ENTROPY_BYTES = 16;
290
+ const MAX_STATE_ENTROPY_BYTES = 64;
291
+ const DEFAULT_PKCE_ENTROPY_BYTES = 32;
292
+ const MIN_PKCE_ENTROPY_BYTES = 32;
293
+ const MAX_PKCE_ENTROPY_BYTES = 96;
294
+ const MIN_PKCE_VERIFIER_LENGTH = 43;
295
+ const MAX_PKCE_VERIFIER_LENGTH = 128;
296
+ const CALLBACK_PARAMETER_LIMITS = {
297
+ code: 4096,
298
+ state: 512,
299
+ iss: 2048,
300
+ error: 256,
301
+ error_description: 1024,
302
+ error_uri: 2048
303
+ };
304
+ const RESERVED_CALLBACK_PARAMETERS = [
305
+ "code",
306
+ "state",
307
+ "iss",
308
+ "error",
309
+ "error_description",
310
+ "error_uri"
311
+ ];
312
+ const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;
313
+ const PKCE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]+$/u;
314
+ /** Stable, secret-free failure categories for OAuth state and callback handling. */
315
+ const McpOAuthStateErrorCode = {
316
+ InvalidOptions: "MCP_OAUTH_STATE_INVALID_OPTIONS",
317
+ InvalidCallback: "MCP_OAUTH_CALLBACK_INVALID",
318
+ InvalidDigest: "MCP_OAUTH_STATE_DIGEST_INVALID",
319
+ StateMismatch: "MCP_OAUTH_STATE_MISMATCH",
320
+ StateExpired: "MCP_OAUTH_STATE_EXPIRED",
321
+ StateNotYetValid: "MCP_OAUTH_STATE_NOT_YET_VALID",
322
+ InvalidPkceVerifier: "MCP_OAUTH_PKCE_VERIFIER_INVALID"
323
+ };
324
+ /** An OAuth state/protocol error whose message never includes callback or secret material. */
325
+ var McpOAuthStateError = class extends Error {
326
+ code;
327
+ constructor(code) {
328
+ super(stateErrorMessage(code));
329
+ this.name = "McpOAuthStateError";
330
+ this.code = code;
331
+ }
332
+ };
333
+ /** Generates an unpredictable OAuth state value using Node's CSPRNG. */
334
+ function createOAuthState(options = {}) {
335
+ const entropyBytes = options.entropyBytes ?? DEFAULT_STATE_ENTROPY_BYTES;
336
+ assertEntropyBytes(entropyBytes, MIN_STATE_ENTROPY_BYTES, MAX_STATE_ENTROPY_BYTES);
337
+ return randomBytes(entropyBytes).toString("base64url");
338
+ }
339
+ /**
340
+ * Derives the opaque key used to look up an authorization transaction.
341
+ * The domain prefix prevents the digest from being reused as an unscoped SHA-256 identifier.
342
+ */
343
+ function createOAuthStateLookupDigest(state) {
344
+ assertStateValue(state);
345
+ return createHash("sha256").update(OAUTH_STATE_DIGEST_DOMAIN, "utf8").update(state, "utf8").digest("base64url");
346
+ }
347
+ /**
348
+ * Validates a callback state against a digest-only transaction record and its lifetime.
349
+ * Both valid digests are decoded to fixed-size byte arrays before constant-time comparison.
350
+ */
351
+ function validateOAuthState(input) {
352
+ assertStateValue(input.actualState);
353
+ const expectedDigest = decodeStateDigest(input.expectedDigest);
354
+ const actualDigest = Buffer.from(createOAuthStateLookupDigest(input.actualState), "base64url");
355
+ if (!timingSafeEqual(actualDigest, expectedDigest)) throw new McpOAuthStateError(McpOAuthStateErrorCode.StateMismatch);
356
+ const nowMs = input.nowMs ?? Date.now();
357
+ assertEpochMilliseconds(input.createdAtMs);
358
+ assertEpochMilliseconds(nowMs);
359
+ if (!Number.isSafeInteger(input.ttlMs) || input.ttlMs <= 0) throw invalidOptionsError$2();
360
+ if (nowMs < input.createdAtMs) throw new McpOAuthStateError(McpOAuthStateErrorCode.StateNotYetValid);
361
+ if (nowMs - input.createdAtMs >= input.ttlMs) throw new McpOAuthStateError(McpOAuthStateErrorCode.StateExpired);
362
+ }
363
+ /**
364
+ * Parses an authorization callback query without normalizing opaque values.
365
+ * Unknown extension parameters are ignored as required by OAuth; reserved parameters are strict.
366
+ */
367
+ function parseOAuthCallbackParameters(input) {
368
+ if (input instanceof URL && input.hash.length > 0) throw invalidCallbackError();
369
+ const parameters = input instanceof URL ? input.searchParams : input;
370
+ if (!(parameters instanceof URLSearchParams)) throw invalidCallbackError();
371
+ for (const name of RESERVED_CALLBACK_PARAMETERS) {
372
+ const values = parameters.getAll(name);
373
+ if (values.length > 1) throw invalidCallbackError();
374
+ if (values.length === 1) assertCallbackValue(values[0], CALLBACK_PARAMETER_LIMITS[name]);
375
+ }
376
+ const code = parameters.get("code");
377
+ const state = parameters.get("state");
378
+ const issuer = optionalCallbackValue(parameters, "iss");
379
+ const error = parameters.get("error");
380
+ if (state === null) throw invalidCallbackError();
381
+ if (code === null === (error === null)) throw invalidCallbackError();
382
+ if (code !== null) {
383
+ if (parameters.has("error_description") || parameters.has("error_uri")) throw invalidCallbackError();
384
+ return {
385
+ kind: "success",
386
+ code,
387
+ state,
388
+ ...issuer === void 0 ? {} : { issuer }
389
+ };
390
+ }
391
+ if (error === null) throw invalidCallbackError();
392
+ return {
393
+ kind: "error",
394
+ error,
395
+ state,
396
+ ...issuer === void 0 ? {} : { issuer }
397
+ };
398
+ }
399
+ /** Generates an RFC 7636 code verifier using Node's CSPRNG. */
400
+ function createPkceVerifier(options = {}) {
401
+ const entropyBytes = options.entropyBytes ?? DEFAULT_PKCE_ENTROPY_BYTES;
402
+ assertEntropyBytes(entropyBytes, MIN_PKCE_ENTROPY_BYTES, MAX_PKCE_ENTROPY_BYTES);
403
+ return randomBytes(entropyBytes).toString("base64url");
404
+ }
405
+ /** Derives the RFC 7636 `S256` code challenge for a validated verifier. */
406
+ function createPkceS256Challenge(verifier) {
407
+ if (typeof verifier !== "string" || verifier.length < MIN_PKCE_VERIFIER_LENGTH || verifier.length > MAX_PKCE_VERIFIER_LENGTH || !PKCE_VERIFIER_PATTERN.test(verifier)) throw new McpOAuthStateError(McpOAuthStateErrorCode.InvalidPkceVerifier);
408
+ return createHash("sha256").update(verifier, "ascii").digest("base64url");
409
+ }
410
+ function assertEntropyBytes(value, minimum, maximum) {
411
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) throw invalidOptionsError$2();
412
+ }
413
+ function assertEpochMilliseconds(value) {
414
+ if (!Number.isSafeInteger(value) || value < 0) throw invalidOptionsError$2();
415
+ }
416
+ function assertStateValue(state) {
417
+ if (typeof state !== "string" || state.length < base64urlLength(MIN_STATE_ENTROPY_BYTES) || state.length > base64urlLength(MAX_STATE_ENTROPY_BYTES) || !BASE64URL_PATTERN.test(state)) throw new McpOAuthStateError(McpOAuthStateErrorCode.InvalidCallback);
418
+ }
419
+ function decodeStateDigest(value) {
420
+ if (typeof value !== "string" || value.length !== SHA_256_BASE64URL_LENGTH || !BASE64URL_PATTERN.test(value)) throw invalidDigestError();
421
+ const decoded = Buffer.from(value, "base64url");
422
+ if (decoded.length !== SHA_256_BYTES || decoded.toString("base64url") !== value) throw invalidDigestError();
423
+ return decoded;
424
+ }
425
+ function assertCallbackValue(value, maximumLength) {
426
+ if (value === void 0 || value.length === 0 || value.length > maximumLength || containsControlCharacter$2(value)) throw invalidCallbackError();
427
+ }
428
+ function containsControlCharacter$2(value) {
429
+ for (const character of value) {
430
+ const codePoint = character.codePointAt(0);
431
+ if (codePoint !== void 0 && (codePoint <= 31 || codePoint >= 127 && codePoint <= 159)) return true;
432
+ }
433
+ return false;
434
+ }
435
+ function optionalCallbackValue(parameters, name) {
436
+ const value = parameters.get(name);
437
+ return value === null ? void 0 : value;
438
+ }
439
+ function base64urlLength(bytes) {
440
+ return Math.ceil(bytes * 8 / 6);
441
+ }
442
+ function invalidOptionsError$2() {
443
+ return new McpOAuthStateError(McpOAuthStateErrorCode.InvalidOptions);
444
+ }
445
+ function invalidCallbackError() {
446
+ return new McpOAuthStateError(McpOAuthStateErrorCode.InvalidCallback);
447
+ }
448
+ function invalidDigestError() {
449
+ return new McpOAuthStateError(McpOAuthStateErrorCode.InvalidDigest);
450
+ }
451
+ function stateErrorMessage(code) {
452
+ switch (code) {
453
+ case McpOAuthStateErrorCode.InvalidOptions: return "The OAuth state operation options are invalid.";
454
+ case McpOAuthStateErrorCode.InvalidCallback: return "The OAuth callback parameters are invalid.";
455
+ case McpOAuthStateErrorCode.InvalidDigest: return "The stored OAuth state digest is invalid.";
456
+ case McpOAuthStateErrorCode.StateMismatch: return "The OAuth callback state does not match the authorization transaction.";
457
+ case McpOAuthStateErrorCode.StateExpired: return "The OAuth authorization transaction has expired.";
458
+ case McpOAuthStateErrorCode.StateNotYetValid: return "The OAuth authorization transaction is not yet valid.";
459
+ case McpOAuthStateErrorCode.InvalidPkceVerifier: return "The PKCE verifier is invalid.";
460
+ default: return "The OAuth state operation failed.";
461
+ }
462
+ }
463
+ //#endregion
464
+ //#region src/oauth/protocol-error-brand.ts
465
+ const internalProtocolErrors = /* @__PURE__ */ new WeakSet();
466
+ /** Package-internal authenticity marker; intentionally not exported from the OAuth entry point. */
467
+ function markInternalMcpClientOAuthProtocolError(error) {
468
+ internalProtocolErrors.add(error);
469
+ return error;
470
+ }
471
+ /** Distinguishes fixed, library-origin failures from public-constructor lookalikes. */
472
+ function isInternalMcpClientOAuthProtocolError(error) {
473
+ return error !== null && (typeof error === "object" || typeof error === "function") && internalProtocolErrors.has(error);
474
+ }
475
+ //#endregion
476
+ //#region src/oauth/snapshot-data.ts
477
+ /** Never retains the decoded value, a validation cause, URLs, or secret material. */
478
+ var McpClientOAuthSnapshotError = class extends Error {
479
+ code = "MCP_CLIENT_OAUTH_SNAPSHOT_INVALID";
480
+ constructor() {
481
+ super("The MCP OAuth snapshot is invalid or exceeds its bounds.");
482
+ this.name = "McpClientOAuthSnapshotError";
483
+ }
484
+ };
485
+ function parseOAuthSnapshot(value, options, parse) {
486
+ try {
487
+ const maxBytes = bound(options.maxBytes, 2097152);
488
+ const maxUrlLength = bound(options.maxUrlLength, 4096);
489
+ return parse(oauthSnapshotRecord(captureMcpConformanceValue(value, {
490
+ maxBytes,
491
+ maxDepth: 8,
492
+ maxItems: 8192,
493
+ maxProperties: 4096,
494
+ maxStringBytes: 65536
495
+ }, { undefinedPolicy: "reject" })), maxUrlLength);
496
+ } catch {
497
+ throw new McpClientOAuthSnapshotError();
498
+ }
499
+ }
500
+ function oauthSnapshotRecord(value) {
501
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new McpClientOAuthSnapshotError();
502
+ return value;
503
+ }
504
+ function assertOAuthSnapshotKeys(value, keys) {
505
+ const allowed = new Set(keys);
506
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new McpClientOAuthSnapshotError();
507
+ }
508
+ function oauthSnapshotString(value, maximum) {
509
+ if (typeof value !== "string" || value.length === 0 || value.length > maximum) throw new McpClientOAuthSnapshotError();
510
+ return value;
511
+ }
512
+ function oauthSnapshotStrings(value, maximum) {
513
+ if (!Array.isArray(value) || value.length > maximum) throw new McpClientOAuthSnapshotError();
514
+ const entries = value;
515
+ if (!entries.every((entry) => typeof entry === "string")) throw new McpClientOAuthSnapshotError();
516
+ return entries;
517
+ }
518
+ function oauthSnapshotBoolean(value) {
519
+ if (typeof value !== "boolean") throw new McpClientOAuthSnapshotError();
520
+ return value;
521
+ }
522
+ function bound(value, maximum) {
523
+ const result = value ?? maximum;
524
+ if (!Number.isSafeInteger(result) || result < 1 || result > maximum) throw new McpClientOAuthSnapshotError();
525
+ return result;
526
+ }
527
+ //#endregion
528
+ //#region src/oauth/protocol.ts
529
+ const DEFAULT_AUTHORIZATION_TRANSACTION_TTL_MS = 6e5;
530
+ const MAX_AUTHORIZATION_TRANSACTION_TTL_MS = 36e5;
531
+ const MAX_URL_LENGTH$1 = 4096;
532
+ const MAX_CLIENT_ID_LENGTH = 2048;
533
+ const MAX_CLIENT_SECRET_LENGTH = 8192;
534
+ const MAX_TOKEN_LENGTH = 65536;
535
+ const MAX_SCOPE_COUNT$1 = 128;
536
+ const MAX_SCOPE_STRING_LENGTH$1 = 4096;
537
+ const MAX_METADATA_LIST_LENGTH$1 = 256;
538
+ const MAX_METADATA_VALUE_LENGTH$1 = 2048;
539
+ const AUTHORITY_DIGEST_DOMAIN = "nest-mcp.client.oauth-authority.v1\0";
540
+ const PRIVATE_KEY_JWT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
541
+ const PRIVATE_KEY_JWT_PARAMETER_NAMES = Object.freeze([
542
+ "client_id",
543
+ "client_assertion_type",
544
+ "client_assertion"
545
+ ]);
546
+ /** Stable, secret-free failure categories for the strict outbound OAuth facade. */
547
+ const McpClientOAuthProtocolErrorCode = {
548
+ InvalidOptions: "MCP_CLIENT_OAUTH_INVALID_OPTIONS",
549
+ EndpointRejected: "MCP_CLIENT_OAUTH_ENDPOINT_REJECTED",
550
+ DiscoveryFailed: "MCP_CLIENT_OAUTH_DISCOVERY_FAILED",
551
+ AuthorityInvalid: "MCP_CLIENT_OAUTH_AUTHORITY_INVALID",
552
+ ClientUnsupported: "MCP_CLIENT_OAUTH_CLIENT_UNSUPPORTED",
553
+ TransactionInvalid: "MCP_CLIENT_OAUTH_TRANSACTION_INVALID",
554
+ AuthorizationDenied: "MCP_CLIENT_OAUTH_AUTHORIZATION_DENIED",
555
+ AuthorizationFailed: "MCP_CLIENT_OAUTH_AUTHORIZATION_FAILED",
556
+ InvalidGrant: "MCP_CLIENT_OAUTH_INVALID_GRANT",
557
+ InvalidClient: "MCP_CLIENT_OAUTH_INVALID_CLIENT",
558
+ TokenExchangeFailed: "MCP_CLIENT_OAUTH_TOKEN_EXCHANGE_FAILED",
559
+ TokenRefreshFailed: "MCP_CLIENT_OAUTH_TOKEN_REFRESH_FAILED",
560
+ RefreshOutcomeUnknown: "MCP_CLIENT_OAUTH_REFRESH_OUTCOME_UNKNOWN"
561
+ };
562
+ /**
563
+ * Public protocol-error shape. Library-emitted instances use fixed, secret-free messages; callers
564
+ * constructing this class directly remain responsible for their message and receive no internal
565
+ * authenticity brand.
566
+ */
567
+ var McpClientOAuthProtocolError = class extends Error {
568
+ code;
569
+ constructor(code, message) {
570
+ super(message);
571
+ this.name = "McpClientOAuthProtocolError";
572
+ this.code = code;
573
+ }
574
+ };
575
+ function createInternalProtocolError(code, message) {
576
+ return markInternalMcpClientOAuthProtocolError(new McpClientOAuthProtocolError(code, message));
577
+ }
578
+ /**
579
+ * Strict, framework-neutral OAuth protocol facade for outbound MCP clients.
580
+ *
581
+ * It deliberately exposes no dynamic registration and never constructs an OAuthClientProvider,
582
+ * preventing the MCP transport from launching interactive or DCR flows implicitly.
583
+ */
584
+ var McpClientOAuthProtocol = class {
585
+ #fetch;
586
+ #endpointPolicy;
587
+ #authorizationTransactionTtlMs;
588
+ #now;
589
+ constructor(options) {
590
+ if (typeof options !== "object" || options === null || typeof options.fetch !== "function" || typeof options.endpointPolicy !== "function" || options.now !== void 0 && typeof options.now !== "function") throw invalidOptionsError$1();
591
+ const ttlMs = options.authorizationTransactionTtlMs ?? DEFAULT_AUTHORIZATION_TRANSACTION_TTL_MS;
592
+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0 || ttlMs > MAX_AUTHORIZATION_TRANSACTION_TTL_MS) throw invalidOptionsError$1();
593
+ this.#fetch = options.fetch;
594
+ this.#endpointPolicy = options.endpointPolicy;
595
+ this.#authorizationTransactionTtlMs = ttlMs;
596
+ this.#now = options.now ?? Date.now;
597
+ }
598
+ /** Resolves and freezes exact RFC 9728/RFC 8414 authority without following DCR. */
599
+ async discover(input) {
600
+ const operation = normalizeDiscoveryInput$1(input);
601
+ throwIfAborted$1(operation.signal);
602
+ let resourceMetadata;
603
+ try {
604
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(operation.serverUrl, operation.resourceMetadataUrl === void 0 ? void 0 : { resourceMetadataUrl: operation.resourceMetadataUrl }, this.#createFetch({
605
+ kind: "resource-metadata",
606
+ credentialed: false,
607
+ resource: operation.resource,
608
+ issuer: operation.issuer,
609
+ signal: operation.signal
610
+ }));
611
+ } catch (error) {
612
+ throwIfAborted$1(operation.signal);
613
+ if (error instanceof McpClientOAuthProtocolError) throw canonicalizeProtocolError(error, discoveryFailedError);
614
+ throw discoveryFailedError();
615
+ }
616
+ if (resourceMetadata.resource !== operation.resource || resourceMetadata.authorization_servers === void 0 || !resourceMetadata.authorization_servers.includes(operation.issuer)) throw authorityInvalidError();
617
+ if (resourceMetadata.bearer_methods_supported !== void 0 && !resourceMetadata.bearer_methods_supported.includes("header") || resourceMetadata.tls_client_certificate_bound_access_tokens === true || resourceMetadata.dpop_bound_access_tokens_required === true) throw authorityInvalidError();
618
+ let metadata;
619
+ try {
620
+ metadata = await discoverAuthorizationServerMetadata(operation.issuer, { fetchFn: this.#createFetch({
621
+ kind: "authorization-server-metadata",
622
+ credentialed: false,
623
+ resource: operation.resource,
624
+ issuer: operation.issuer,
625
+ signal: operation.signal
626
+ }) });
627
+ } catch (error) {
628
+ throwIfAborted$1(operation.signal);
629
+ if (error instanceof McpClientOAuthProtocolError) throw canonicalizeProtocolError(error, discoveryFailedError);
630
+ throw discoveryFailedError();
631
+ }
632
+ throwIfAborted$1(operation.signal);
633
+ if (metadata === void 0 || metadata.issuer !== operation.issuer) throw authorityInvalidError();
634
+ const authority = createAuthority({
635
+ serverUrl: operation.serverUrl,
636
+ resource: operation.resource,
637
+ issuer: operation.issuer,
638
+ metadata,
639
+ ...resourceMetadata.scopes_supported === void 0 ? {} : { resourceScopesSupported: resourceMetadata.scopes_supported }
640
+ });
641
+ await this.#authorizeEndpoint(authority.authorizationEndpoint, {
642
+ kind: "authorization",
643
+ credentialed: false,
644
+ resource: authority.resource,
645
+ issuer: authority.issuer,
646
+ signal: operation.signal
647
+ });
648
+ await this.#authorizeEndpoint(authority.tokenEndpoint, {
649
+ kind: "token",
650
+ credentialed: true,
651
+ resource: authority.resource,
652
+ issuer: authority.issuer,
653
+ signal: operation.signal
654
+ });
655
+ return authority;
656
+ }
657
+ /** Starts a PKCE S256 authorization request and returns an endpoint-pinned transaction. */
658
+ async startAuthorization(input) {
659
+ if (typeof input !== "object" || input === null) throw invalidOptionsError$1();
660
+ const authority = normalizeAuthority(input.authority);
661
+ const client = normalizeClient(input.client, authority);
662
+ const redirectUri = requireRedirectUri(input.redirectUri).href;
663
+ const scope = normalizeScopes(input.scopes, authority);
664
+ throwIfAborted$1(input.signal);
665
+ await this.#authorizeEndpoint(authority.authorizationEndpoint, {
666
+ kind: "authorization",
667
+ credentialed: false,
668
+ resource: authority.resource,
669
+ issuer: authority.issuer,
670
+ signal: input.signal
671
+ });
672
+ const state = createOAuthState();
673
+ let started;
674
+ try {
675
+ started = await startAuthorization(authority.issuer, {
676
+ metadata: toSdkMetadata(authority),
677
+ clientInformation: toSdkClientInformation(client),
678
+ redirectUrl: redirectUri,
679
+ state,
680
+ resource: new URL(authority.resource),
681
+ ...scope === void 0 ? {} : { scope }
682
+ });
683
+ } catch {
684
+ throwIfAborted$1(input.signal);
685
+ throw authorizationFailedError();
686
+ }
687
+ throwIfAborted$1(input.signal);
688
+ const codeChallenge = createPkceS256Challenge(started.codeVerifier);
689
+ assertAuthorizationUrl(started.authorizationUrl, {
690
+ exactEndpoint: authority.authorizationEndpoint,
691
+ clientId: client.clientId,
692
+ redirectUri,
693
+ resource: authority.resource,
694
+ state,
695
+ codeChallenge,
696
+ scope
697
+ });
698
+ const createdAtMs = this.#now();
699
+ if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) throw invalidOptionsError$1();
700
+ const transaction = Object.freeze({
701
+ authority: copyAuthority$1(authority),
702
+ authorityDigest: createAuthorityDigest(authority),
703
+ stateDigest: createOAuthStateLookupDigest(state),
704
+ codeVerifier: started.codeVerifier,
705
+ redirectUri,
706
+ clientId: client.clientId,
707
+ clientAuthenticationMethod: client.authentication.method,
708
+ ...scope === void 0 ? {} : { scope },
709
+ createdAtMs
710
+ });
711
+ return Object.freeze({
712
+ authorizationUrl: started.authorizationUrl.href,
713
+ transaction
714
+ });
715
+ }
716
+ /** Redeems a callback against the originally pinned authority exactly once. */
717
+ async exchangeAuthorization(input) {
718
+ if (typeof input !== "object" || input === null) throw invalidOptionsError$1();
719
+ const transaction = normalizeTransaction(input.transaction);
720
+ const authority = transaction.authority;
721
+ const client = normalizeClient(input.client, authority);
722
+ assertTransactionClient(transaction, client);
723
+ const callback = parseOAuthCallbackParameters(input.callback);
724
+ validateOAuthState({
725
+ actualState: callback.state,
726
+ expectedDigest: transaction.stateDigest,
727
+ createdAtMs: transaction.createdAtMs,
728
+ ttlMs: this.#authorizationTransactionTtlMs,
729
+ nowMs: this.#now()
730
+ });
731
+ assertCallbackIssuer(callback.issuer, authority);
732
+ if (callback.kind === "error") throw authorizationDeniedError();
733
+ throwIfAborted$1(input.signal);
734
+ await this.#authorizeEndpoint(authority.tokenEndpoint, {
735
+ kind: "token",
736
+ credentialed: true,
737
+ resource: authority.resource,
738
+ issuer: authority.issuer,
739
+ signal: input.signal
740
+ });
741
+ try {
742
+ const tokens = await exchangeAuthorization(authority.issuer, {
743
+ metadata: toSdkMetadata(authority),
744
+ clientInformation: toSdkClientInformation(client),
745
+ authorizationCode: callback.code,
746
+ codeVerifier: transaction.codeVerifier,
747
+ redirectUri: transaction.redirectUri,
748
+ resource: new URL(authority.resource),
749
+ addClientAuthentication: createClientAuthentication(client, authority),
750
+ fetchFn: this.#createFetch({
751
+ kind: "token",
752
+ credentialed: true,
753
+ resource: authority.resource,
754
+ issuer: authority.issuer,
755
+ signal: input.signal,
756
+ exactEndpoint: authority.tokenEndpoint
757
+ }),
758
+ ...callback.issuer === void 0 ? {} : { iss: callback.issuer }
759
+ });
760
+ throwIfAborted$1(input.signal);
761
+ return validateTokens(tokens, "exchange", transaction.scope);
762
+ } catch (error) {
763
+ throwIfAborted$1(input.signal);
764
+ throw translateTokenError(error, "exchange");
765
+ }
766
+ }
767
+ /** Refreshes with the same exact authority and configured authentication method. */
768
+ async refreshAuthorization(input) {
769
+ if (typeof input !== "object" || input === null) throw invalidOptionsError$1();
770
+ const authority = normalizeAuthority(input.authority);
771
+ const client = normalizeClient(input.client, authority);
772
+ const currentScope = input.currentScope;
773
+ if (currentScope !== void 0) assertScopeString(currentScope);
774
+ assertSecretValue(input.refreshToken, MAX_TOKEN_LENGTH);
775
+ if (authority.grantTypesSupported === void 0 || !authority.grantTypesSupported.includes("refresh_token")) throw clientUnsupportedError();
776
+ throwIfAborted$1(input.signal);
777
+ await this.#authorizeEndpoint(authority.tokenEndpoint, {
778
+ kind: "token",
779
+ credentialed: true,
780
+ resource: authority.resource,
781
+ issuer: authority.issuer,
782
+ signal: input.signal
783
+ });
784
+ const fetchAttempt = {
785
+ invoked: false,
786
+ responseReturned: false
787
+ };
788
+ try {
789
+ const tokens = await refreshAuthorization(authority.issuer, {
790
+ metadata: toSdkMetadata(authority),
791
+ clientInformation: toSdkClientInformation(client),
792
+ refreshToken: input.refreshToken,
793
+ resource: new URL(authority.resource),
794
+ addClientAuthentication: createClientAuthentication(client, authority),
795
+ fetchFn: this.#createFetch({
796
+ kind: "token",
797
+ credentialed: true,
798
+ resource: authority.resource,
799
+ issuer: authority.issuer,
800
+ signal: input.signal,
801
+ exactEndpoint: authority.tokenEndpoint,
802
+ hostFetchAttempt: fetchAttempt
803
+ })
804
+ });
805
+ throwIfAborted$1(input.signal);
806
+ return validateTokens(tokens, "refresh", currentScope);
807
+ } catch (error) {
808
+ if (!fetchAttempt.invoked) throwIfAborted$1(input.signal);
809
+ throw translateTokenError(error, "refresh", fetchAttempt);
810
+ }
811
+ }
812
+ #createFetch(input) {
813
+ return async (url, init) => {
814
+ throwIfAborted$1(input.signal);
815
+ const endpoint = requireSecureUrl$1(String(url), { query: true });
816
+ if (input.exactEndpoint !== void 0 && endpoint.href !== input.exactEndpoint) throw endpointRejectedError();
817
+ await this.#authorizeEndpoint(endpoint.href, input);
818
+ throwIfAborted$1(input.signal);
819
+ const signal = combineAbortSignals$1(input.signal, init?.signal);
820
+ const requestInit = {
821
+ ...init,
822
+ redirect: "error"
823
+ };
824
+ if (signal !== void 0) requestInit.signal = signal;
825
+ if (input.hostFetchAttempt !== void 0) input.hostFetchAttempt.invoked = true;
826
+ const response = await this.#fetch(new URL(endpoint.href), requestInit);
827
+ if (input.hostFetchAttempt !== void 0) input.hostFetchAttempt.responseReturned = true;
828
+ throwIfAborted$1(input.signal);
829
+ if (response.redirected || input.exactEndpoint !== void 0 && response.url.length > 0 && !isExactResponseUrl$1(response.url, input.exactEndpoint)) throw endpointRejectedError();
830
+ return response;
831
+ };
832
+ }
833
+ async #authorizeEndpoint(endpointValue, input) {
834
+ throwIfAborted$1(input.signal);
835
+ const endpoint = requireSecureUrl$1(endpointValue, { query: true });
836
+ let admitted;
837
+ try {
838
+ admitted = await awaitWithSignal$1(Promise.resolve().then(() => this.#endpointPolicy(Object.freeze({
839
+ endpoint: new URL(endpoint.href),
840
+ kind: input.kind,
841
+ credentialed: input.credentialed,
842
+ exactResource: input.resource,
843
+ exactIssuer: input.issuer,
844
+ resource: new URL(input.resource),
845
+ issuer: new URL(input.issuer),
846
+ ...input.signal === void 0 ? {} : { signal: input.signal }
847
+ }))), input.signal);
848
+ } catch {
849
+ throwIfAborted$1(input.signal);
850
+ throw endpointRejectedError();
851
+ }
852
+ throwIfAborted$1(input.signal);
853
+ if (admitted !== true) throw endpointRejectedError();
854
+ }
855
+ };
856
+ function normalizeDiscoveryInput$1(input) {
857
+ if (typeof input !== "object" || input === null) throw invalidOptionsError$1();
858
+ const serverUrl = requireSecureUrl$1(input.serverUrl, { query: true }).href;
859
+ const resource = requireCanonicalResource(input.resource);
860
+ requireSecureUrl$1(input.issuer, { query: false });
861
+ const issuer = input.issuer;
862
+ const resourceMetadataUrl = input.resourceMetadataUrl === void 0 ? void 0 : requireSecureUrl$1(input.resourceMetadataUrl, { query: true }).href;
863
+ return Object.freeze({
864
+ serverUrl,
865
+ resource,
866
+ issuer,
867
+ ...resourceMetadataUrl === void 0 ? {} : { resourceMetadataUrl },
868
+ signal: input.signal
869
+ });
870
+ }
871
+ function createAuthority(input) {
872
+ const responseTypesSupported = normalizeMetadataList$1(input.metadata.response_types_supported);
873
+ const codeChallengeMethodsSupported = normalizeMetadataList$1(input.metadata.code_challenge_methods_supported);
874
+ const tokenEndpointAuthMethodsSupported = normalizeMetadataList$1(input.metadata.token_endpoint_auth_methods_supported);
875
+ if (!responseTypesSupported.includes("code") || !codeChallengeMethodsSupported.includes("S256") || tokenEndpointAuthMethodsSupported.length === 0 || input.metadata.grant_types_supported !== void 0 && !input.metadata.grant_types_supported.includes("authorization_code") || input.metadata.response_modes_supported !== void 0 && !input.metadata.response_modes_supported.includes("query")) throw authorityInvalidError();
876
+ return copyAuthority$1({
877
+ serverUrl: input.serverUrl,
878
+ resource: input.resource,
879
+ issuer: input.issuer,
880
+ authorizationEndpoint: requireSecureUrl$1(input.metadata.authorization_endpoint, { query: true }).href,
881
+ tokenEndpoint: requireSecureUrl$1(input.metadata.token_endpoint, { query: true }).href,
882
+ responseTypesSupported,
883
+ codeChallengeMethodsSupported,
884
+ tokenEndpointAuthMethodsSupported,
885
+ ...input.metadata.grant_types_supported === void 0 ? {} : { grantTypesSupported: normalizeMetadataList$1(input.metadata.grant_types_supported) },
886
+ ...input.resourceScopesSupported === void 0 ? {} : { resourceScopesSupported: normalizeScopeMetadataList(input.resourceScopesSupported) },
887
+ ...input.metadata.scopes_supported === void 0 ? {} : { authorizationScopesSupported: normalizeScopeMetadataList(input.metadata.scopes_supported) },
888
+ authorizationResponseIssuerParameterSupported: input.metadata.authorization_response_iss_parameter_supported === true
889
+ });
890
+ }
891
+ /** Decode authenticated host storage; this does not admit endpoints or authorize execution. */
892
+ function parseMcpClientOAuthAuthority(value, options = {}) {
893
+ return parseOAuthSnapshot(value, options, (record, maximum) => {
894
+ assertOAuthSnapshotKeys(record, [
895
+ "serverUrl",
896
+ "resource",
897
+ "issuer",
898
+ "authorizationEndpoint",
899
+ "tokenEndpoint",
900
+ "responseTypesSupported",
901
+ "codeChallengeMethodsSupported",
902
+ "tokenEndpointAuthMethodsSupported",
903
+ "grantTypesSupported",
904
+ "resourceScopesSupported",
905
+ "authorizationScopesSupported",
906
+ "authorizationResponseIssuerParameterSupported"
907
+ ]);
908
+ return normalizeAuthority({
909
+ serverUrl: oauthSnapshotString(record.serverUrl, maximum),
910
+ resource: oauthSnapshotString(record.resource, maximum),
911
+ issuer: oauthSnapshotString(record.issuer, maximum),
912
+ authorizationEndpoint: oauthSnapshotString(record.authorizationEndpoint, maximum),
913
+ tokenEndpoint: oauthSnapshotString(record.tokenEndpoint, maximum),
914
+ responseTypesSupported: oauthSnapshotStrings(record.responseTypesSupported, MAX_METADATA_LIST_LENGTH$1),
915
+ codeChallengeMethodsSupported: oauthSnapshotStrings(record.codeChallengeMethodsSupported, MAX_METADATA_LIST_LENGTH$1),
916
+ tokenEndpointAuthMethodsSupported: oauthSnapshotStrings(record.tokenEndpointAuthMethodsSupported, MAX_METADATA_LIST_LENGTH$1),
917
+ ...record.grantTypesSupported === void 0 ? {} : { grantTypesSupported: oauthSnapshotStrings(record.grantTypesSupported, MAX_METADATA_LIST_LENGTH$1) },
918
+ ...record.resourceScopesSupported === void 0 ? {} : { resourceScopesSupported: oauthSnapshotStrings(record.resourceScopesSupported, MAX_SCOPE_COUNT$1) },
919
+ ...record.authorizationScopesSupported === void 0 ? {} : { authorizationScopesSupported: oauthSnapshotStrings(record.authorizationScopesSupported, MAX_SCOPE_COUNT$1) },
920
+ authorizationResponseIssuerParameterSupported: oauthSnapshotBoolean(record.authorizationResponseIssuerParameterSupported)
921
+ });
922
+ });
923
+ }
924
+ /** Pure decoding and authority-digest verification; host session binding and atomic take remain required. */
925
+ function parseMcpClientOAuthAuthorizationTransaction(value, options = {}) {
926
+ return parseOAuthSnapshot(value, options, (record, maximum) => {
927
+ assertOAuthSnapshotKeys(record, [
928
+ "authority",
929
+ "authorityDigest",
930
+ "stateDigest",
931
+ "codeVerifier",
932
+ "redirectUri",
933
+ "clientId",
934
+ "clientAuthenticationMethod",
935
+ "scope",
936
+ "createdAtMs"
937
+ ]);
938
+ const method = record.clientAuthenticationMethod;
939
+ const stateDigest = oauthSnapshotString(record.stateDigest, 43);
940
+ if (!isClientAuthenticationMethod(method) || !/^[A-Za-z0-9_-]{43}$/u.test(stateDigest) || typeof record.createdAtMs !== "number") throw transactionInvalidError();
941
+ return normalizeTransaction({
942
+ authority: parseMcpClientOAuthAuthority(record.authority, options),
943
+ authorityDigest: oauthSnapshotString(record.authorityDigest, 43),
944
+ stateDigest,
945
+ codeVerifier: oauthSnapshotString(record.codeVerifier, 128),
946
+ redirectUri: oauthSnapshotString(record.redirectUri, maximum),
947
+ clientId: oauthSnapshotString(record.clientId, MAX_CLIENT_ID_LENGTH),
948
+ clientAuthenticationMethod: method,
949
+ ...record.scope === void 0 ? {} : { scope: oauthSnapshotString(record.scope, MAX_SCOPE_STRING_LENGTH$1) },
950
+ createdAtMs: record.createdAtMs
951
+ });
952
+ });
953
+ }
954
+ function normalizeAuthority(authority) {
955
+ if (typeof authority !== "object" || authority === null) throw authorityInvalidError();
956
+ const normalized = copyAuthority$1({
957
+ serverUrl: requireSecureUrl$1(authority.serverUrl, { query: true }).href,
958
+ resource: requireCanonicalResource(authority.resource),
959
+ issuer: requireExactIssuer(authority.issuer),
960
+ authorizationEndpoint: requireSecureUrl$1(authority.authorizationEndpoint, { query: true }).href,
961
+ tokenEndpoint: requireSecureUrl$1(authority.tokenEndpoint, { query: true }).href,
962
+ responseTypesSupported: normalizeMetadataList$1(authority.responseTypesSupported),
963
+ codeChallengeMethodsSupported: normalizeMetadataList$1(authority.codeChallengeMethodsSupported),
964
+ tokenEndpointAuthMethodsSupported: normalizeMetadataList$1(authority.tokenEndpointAuthMethodsSupported),
965
+ ...authority.grantTypesSupported === void 0 ? {} : { grantTypesSupported: normalizeMetadataList$1(authority.grantTypesSupported) },
966
+ ...authority.resourceScopesSupported === void 0 ? {} : { resourceScopesSupported: normalizeScopeMetadataList(authority.resourceScopesSupported) },
967
+ ...authority.authorizationScopesSupported === void 0 ? {} : { authorizationScopesSupported: normalizeScopeMetadataList(authority.authorizationScopesSupported) },
968
+ authorizationResponseIssuerParameterSupported: authority.authorizationResponseIssuerParameterSupported
969
+ });
970
+ if (typeof normalized.authorizationResponseIssuerParameterSupported !== "boolean" || !normalized.responseTypesSupported.includes("code") || !normalized.codeChallengeMethodsSupported.includes("S256") || normalized.tokenEndpointAuthMethodsSupported.length === 0 || normalized.grantTypesSupported !== void 0 && !normalized.grantTypesSupported.includes("authorization_code")) throw authorityInvalidError();
971
+ return normalized;
972
+ }
973
+ function copyAuthority$1(authority) {
974
+ return Object.freeze({
975
+ serverUrl: authority.serverUrl,
976
+ resource: authority.resource,
977
+ issuer: authority.issuer,
978
+ authorizationEndpoint: authority.authorizationEndpoint,
979
+ tokenEndpoint: authority.tokenEndpoint,
980
+ responseTypesSupported: Object.freeze([...authority.responseTypesSupported]),
981
+ codeChallengeMethodsSupported: Object.freeze([...authority.codeChallengeMethodsSupported]),
982
+ tokenEndpointAuthMethodsSupported: Object.freeze([...authority.tokenEndpointAuthMethodsSupported]),
983
+ ...authority.grantTypesSupported === void 0 ? {} : { grantTypesSupported: Object.freeze([...authority.grantTypesSupported]) },
984
+ ...authority.resourceScopesSupported === void 0 ? {} : { resourceScopesSupported: Object.freeze([...authority.resourceScopesSupported]) },
985
+ ...authority.authorizationScopesSupported === void 0 ? {} : { authorizationScopesSupported: Object.freeze([...authority.authorizationScopesSupported]) },
986
+ authorizationResponseIssuerParameterSupported: authority.authorizationResponseIssuerParameterSupported
987
+ });
988
+ }
989
+ function createAuthorityDigest(authority) {
990
+ const canonical = JSON.stringify([
991
+ authority.serverUrl,
992
+ authority.resource,
993
+ authority.issuer,
994
+ authority.authorizationEndpoint,
995
+ authority.tokenEndpoint,
996
+ authority.responseTypesSupported,
997
+ authority.codeChallengeMethodsSupported,
998
+ authority.tokenEndpointAuthMethodsSupported,
999
+ authority.grantTypesSupported ?? null,
1000
+ authority.resourceScopesSupported ?? null,
1001
+ authority.authorizationScopesSupported ?? null,
1002
+ authority.authorizationResponseIssuerParameterSupported
1003
+ ]);
1004
+ return createHash("sha256").update(AUTHORITY_DIGEST_DOMAIN, "utf8").update(canonical, "utf8").digest("base64url");
1005
+ }
1006
+ function normalizeTransaction(transaction) {
1007
+ if (typeof transaction !== "object" || transaction === null) throw transactionInvalidError();
1008
+ const authority = normalizeAuthority(transaction.authority);
1009
+ if (transaction.authorityDigest !== createAuthorityDigest(authority)) throw transactionInvalidError();
1010
+ const redirectUri = requireRedirectUri(transaction.redirectUri).href;
1011
+ assertBoundedOpaqueValue(transaction.clientId, MAX_CLIENT_ID_LENGTH);
1012
+ if (!isClientAuthenticationMethod(transaction.clientAuthenticationMethod)) throw transactionInvalidError();
1013
+ createPkceS256Challenge(transaction.codeVerifier);
1014
+ if (!Number.isSafeInteger(transaction.createdAtMs) || transaction.createdAtMs < 0) throw transactionInvalidError();
1015
+ if (transaction.scope !== void 0) assertScopeString(transaction.scope);
1016
+ return Object.freeze({
1017
+ authority,
1018
+ authorityDigest: transaction.authorityDigest,
1019
+ stateDigest: transaction.stateDigest,
1020
+ codeVerifier: transaction.codeVerifier,
1021
+ redirectUri,
1022
+ clientId: transaction.clientId,
1023
+ clientAuthenticationMethod: transaction.clientAuthenticationMethod,
1024
+ ...transaction.scope === void 0 ? {} : { scope: transaction.scope },
1025
+ createdAtMs: transaction.createdAtMs
1026
+ });
1027
+ }
1028
+ function normalizeClient(client, authority) {
1029
+ if (typeof client !== "object" || client === null) throw clientUnsupportedError();
1030
+ assertBoundedOpaqueValue(client.clientId, MAX_CLIENT_ID_LENGTH);
1031
+ const authentication = client.authentication;
1032
+ if (typeof authentication !== "object" || authentication === null) throw clientUnsupportedError();
1033
+ switch (authentication.method) {
1034
+ case "none": break;
1035
+ case "client_secret_basic":
1036
+ case "client_secret_post":
1037
+ assertSecretValue(authentication.clientSecret, MAX_CLIENT_SECRET_LENGTH);
1038
+ break;
1039
+ case "private_key_jwt":
1040
+ if (typeof authentication.addClientAuthentication !== "function") throw clientUnsupportedError();
1041
+ break;
1042
+ default: throw clientUnsupportedError();
1043
+ }
1044
+ if (!authority.tokenEndpointAuthMethodsSupported.includes(authentication.method)) throw clientUnsupportedError();
1045
+ const copiedAuthentication = authentication.method === "none" ? Object.freeze({ method: "none" }) : authentication.method === "private_key_jwt" ? Object.freeze({
1046
+ method: "private_key_jwt",
1047
+ addClientAuthentication: authentication.addClientAuthentication
1048
+ }) : Object.freeze({
1049
+ method: authentication.method,
1050
+ clientSecret: authentication.clientSecret
1051
+ });
1052
+ return Object.freeze({
1053
+ clientId: client.clientId,
1054
+ authentication: copiedAuthentication
1055
+ });
1056
+ }
1057
+ function toSdkClientInformation(client) {
1058
+ return {
1059
+ client_id: client.clientId,
1060
+ token_endpoint_auth_method: client.authentication.method
1061
+ };
1062
+ }
1063
+ function createClientAuthentication(client, authority) {
1064
+ const exactTokenEndpoint = authority.tokenEndpoint;
1065
+ return async (headers, parameters, url, metadata) => {
1066
+ if (requireSecureUrl$1(String(url), { query: true }).href !== exactTokenEndpoint || metadata?.token_endpoint !== exactTokenEndpoint) throw endpointRejectedError();
1067
+ headers.delete("Authorization");
1068
+ parameters.delete("client_id");
1069
+ parameters.delete("client_secret");
1070
+ parameters.delete("client_assertion_type");
1071
+ parameters.delete("client_assertion");
1072
+ switch (client.authentication.method) {
1073
+ case "none":
1074
+ parameters.set("client_id", client.clientId);
1075
+ return;
1076
+ case "client_secret_basic": {
1077
+ const username = encodeFormComponent(client.clientId);
1078
+ const password = encodeFormComponent(client.authentication.clientSecret);
1079
+ headers.set("Authorization", `Basic ${Buffer.from(`${username}:${password}`, "utf8").toString("base64")}`);
1080
+ return;
1081
+ }
1082
+ case "client_secret_post":
1083
+ parameters.set("client_id", client.clientId);
1084
+ parameters.set("client_secret", client.authentication.clientSecret);
1085
+ return;
1086
+ case "private_key_jwt": {
1087
+ const signerHeaders = new Headers();
1088
+ const signerParameters = new URLSearchParams({ client_id: client.clientId });
1089
+ try {
1090
+ await client.authentication.addClientAuthentication(signerHeaders, signerParameters, new URL(exactTokenEndpoint), toSdkMetadata(authority));
1091
+ } catch (error) {
1092
+ if (error instanceof McpClientOAuthProtocolError) throw canonicalizeProtocolError(error, clientUnsupportedError);
1093
+ throw error;
1094
+ }
1095
+ const assertion = requirePrivateKeyJwtSignerOutput(signerHeaders, signerParameters, client.clientId);
1096
+ parameters.set("client_id", client.clientId);
1097
+ parameters.set("client_assertion_type", PRIVATE_KEY_JWT_ASSERTION_TYPE);
1098
+ parameters.set("client_assertion", assertion);
1099
+ return;
1100
+ }
1101
+ }
1102
+ };
1103
+ }
1104
+ function requirePrivateKeyJwtSignerOutput(headers, parameters, exactClientId) {
1105
+ if ([...headers].length !== 0) throw clientUnsupportedError();
1106
+ const entries = [...parameters];
1107
+ if (entries.length !== PRIVATE_KEY_JWT_PARAMETER_NAMES.length || entries.some(([name]) => !PRIVATE_KEY_JWT_PARAMETER_NAMES.includes(name)) || parameters.getAll("client_id").length !== 1 || parameters.get("client_id") !== exactClientId || parameters.getAll("client_assertion_type").length !== 1 || parameters.get("client_assertion_type") !== PRIVATE_KEY_JWT_ASSERTION_TYPE || parameters.getAll("client_assertion").length !== 1) throw clientUnsupportedError();
1108
+ const assertion = parameters.get("client_assertion");
1109
+ assertSecretValue(assertion, MAX_TOKEN_LENGTH);
1110
+ return assertion;
1111
+ }
1112
+ function toSdkMetadata(authority) {
1113
+ return {
1114
+ issuer: authority.issuer,
1115
+ authorization_endpoint: authority.authorizationEndpoint,
1116
+ token_endpoint: authority.tokenEndpoint,
1117
+ response_types_supported: [...authority.responseTypesSupported],
1118
+ code_challenge_methods_supported: [...authority.codeChallengeMethodsSupported],
1119
+ token_endpoint_auth_methods_supported: [...authority.tokenEndpointAuthMethodsSupported],
1120
+ ...authority.grantTypesSupported === void 0 ? {} : { grant_types_supported: [...authority.grantTypesSupported] },
1121
+ ...authority.authorizationScopesSupported === void 0 ? {} : { scopes_supported: [...authority.authorizationScopesSupported] },
1122
+ authorization_response_iss_parameter_supported: authority.authorizationResponseIssuerParameterSupported
1123
+ };
1124
+ }
1125
+ function normalizeScopes(scopes, authority) {
1126
+ if (scopes === void 0) return void 0;
1127
+ if (!Array.isArray(scopes)) throw invalidOptionsError$1();
1128
+ if (scopes.length === 0) return void 0;
1129
+ if (scopes.length > MAX_SCOPE_COUNT$1) throw invalidOptionsError$1();
1130
+ const normalized = [...new Set(scopes)];
1131
+ for (const scope of normalized) {
1132
+ assertScopeToken(scope);
1133
+ if (authority.authorizationScopesSupported !== void 0 && !authority.authorizationScopesSupported.includes(scope)) throw clientUnsupportedError();
1134
+ if (scope !== "offline_access" && authority.resourceScopesSupported !== void 0 && !authority.resourceScopesSupported.includes(scope)) throw clientUnsupportedError();
1135
+ }
1136
+ const value = normalized.join(" ");
1137
+ assertScopeString(value);
1138
+ return value;
1139
+ }
1140
+ function normalizeMetadataList$1(values) {
1141
+ if (values === void 0) return Object.freeze([]);
1142
+ if (!Array.isArray(values) || values.length > MAX_METADATA_LIST_LENGTH$1) throw authorityInvalidError();
1143
+ const normalized = [...new Set(values)];
1144
+ for (const value of normalized) if (typeof value !== "string" || value.length === 0 || value.length > MAX_METADATA_VALUE_LENGTH$1 || containsControlCharacter$1(value)) throw authorityInvalidError();
1145
+ return Object.freeze(normalized);
1146
+ }
1147
+ function assertScopeToken(value) {
1148
+ if (!isMcpClientOAuthScopeToken(value)) throw invalidOptionsError$1();
1149
+ }
1150
+ function assertScopeString(value) {
1151
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_SCOPE_STRING_LENGTH$1) throw invalidOptionsError$1();
1152
+ for (const scope of value.split(" ")) assertScopeToken(scope);
1153
+ }
1154
+ function normalizeScopeMetadataList(values) {
1155
+ if (!Array.isArray(values) || values.length > MAX_SCOPE_COUNT$1) throw authorityInvalidError();
1156
+ const normalized = [...new Set(values)];
1157
+ if (!normalized.every(isMcpClientOAuthScopeToken) || normalized.join(" ").length > MAX_SCOPE_STRING_LENGTH$1) throw authorityInvalidError();
1158
+ return Object.freeze(normalized);
1159
+ }
1160
+ function assertTransactionClient(transaction, client) {
1161
+ if (transaction.clientId !== client.clientId || transaction.clientAuthenticationMethod !== client.authentication.method) throw transactionInvalidError();
1162
+ }
1163
+ function assertCallbackIssuer(callbackIssuer, authority) {
1164
+ if (callbackIssuer === void 0) {
1165
+ if (authority.authorizationResponseIssuerParameterSupported) throw transactionInvalidError();
1166
+ return;
1167
+ }
1168
+ if (callbackIssuer !== authority.issuer) throw transactionInvalidError();
1169
+ }
1170
+ function assertAuthorizationUrl(value, input) {
1171
+ const endpoint = requireSecureUrl$1(input.exactEndpoint, { query: true });
1172
+ const actual = requireSecureUrl$1(value.href, { query: true });
1173
+ if (actual.origin !== endpoint.origin || actual.pathname !== endpoint.pathname || actual.searchParams.get("response_type") !== "code" || actual.searchParams.get("client_id") !== input.clientId || actual.searchParams.get("redirect_uri") !== input.redirectUri || actual.searchParams.get("resource") !== new URL(input.resource).href || actual.searchParams.get("state") !== input.state || actual.searchParams.get("code_challenge_method") !== "S256" || actual.searchParams.get("code_challenge") !== input.codeChallenge || actual.searchParams.get("scope") !== (input.scope ?? null)) throw authorizationFailedError();
1174
+ }
1175
+ function validateTokens(tokens, operation, fallbackScope) {
1176
+ assertTokenValue(tokens.access_token, operation);
1177
+ if (tokens.token_type.length === 0 || tokens.token_type.length > 64 || containsControlCharacter$1(tokens.token_type) || tokens.token_type.toLowerCase() !== "bearer") throw tokenResponseInvalidError(operation);
1178
+ if (tokens.refresh_token !== void 0) assertTokenValue(tokens.refresh_token, operation);
1179
+ if (tokens.id_token !== void 0) assertTokenValue(tokens.id_token, operation);
1180
+ if (tokens.expires_in !== void 0 && (!Number.isFinite(tokens.expires_in) || tokens.expires_in <= 0)) throw tokenResponseInvalidError(operation);
1181
+ if (tokens.scope !== void 0 && (tokens.scope.length === 0 || tokens.scope.length > MAX_SCOPE_STRING_LENGTH$1 || tokens.scope.split(" ").length > MAX_SCOPE_COUNT$1 || !tokens.scope.split(" ").every(isMcpClientOAuthScopeToken))) throw tokenResponseInvalidError(operation);
1182
+ if (tokens.scope !== void 0 && fallbackScope !== void 0 && !isScopeSubset(tokens.scope, fallbackScope)) throw tokenResponseInvalidError(operation);
1183
+ return tokens.scope === void 0 && fallbackScope !== void 0 ? {
1184
+ ...tokens,
1185
+ scope: fallbackScope
1186
+ } : tokens;
1187
+ }
1188
+ function isScopeSubset(candidate, available) {
1189
+ const availableTokens = new Set(available.split(" "));
1190
+ return candidate.split(" ").every((scope) => availableTokens.has(scope));
1191
+ }
1192
+ function assertTokenValue(value, operation) {
1193
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_TOKEN_LENGTH || containsControlCharacter$1(value)) throw tokenResponseInvalidError(operation);
1194
+ }
1195
+ function assertBoundedOpaqueValue(value, maximumLength) {
1196
+ if (typeof value !== "string" || value.length === 0 || value.length > maximumLength || containsControlCharacter$1(value)) throw clientUnsupportedError();
1197
+ }
1198
+ function assertSecretValue(value, maximumLength) {
1199
+ if (typeof value !== "string" || value.length === 0 || value.length > maximumLength) throw clientUnsupportedError();
1200
+ }
1201
+ function requireSecureUrl$1(value, options) {
1202
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_URL_LENGTH$1) throw authorityInvalidError();
1203
+ let url;
1204
+ try {
1205
+ url = new URL(value);
1206
+ } catch {
1207
+ throw authorityInvalidError();
1208
+ }
1209
+ if (url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0 || url.hash.length > 0 || !options.query && url.search.length > 0) throw authorityInvalidError();
1210
+ return url;
1211
+ }
1212
+ function requireRedirectUri(value) {
1213
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_URL_LENGTH$1) throw authorityInvalidError();
1214
+ let url;
1215
+ try {
1216
+ url = new URL(value);
1217
+ } catch {
1218
+ throw authorityInvalidError();
1219
+ }
1220
+ if (url.username.length > 0 || url.password.length > 0 || url.hash.length > 0 || url.protocol !== "https:" && !isLoopbackHttpRedirect(url)) throw authorityInvalidError();
1221
+ return url;
1222
+ }
1223
+ function isLoopbackHttpRedirect(url) {
1224
+ if (url.protocol !== "http:") return false;
1225
+ const host = url.hostname.toLowerCase();
1226
+ if (host === "localhost" || host === "[::1]") return true;
1227
+ const octets = host.split(".");
1228
+ return octets.length === 4 && octets[0] === "127" && octets.every(isDecimalOctet);
1229
+ }
1230
+ function isDecimalOctet(value) {
1231
+ if (!/^\d{1,3}$/u.test(value)) return false;
1232
+ const parsed = Number(value);
1233
+ return parsed >= 0 && parsed <= 255 && String(parsed) === value;
1234
+ }
1235
+ function requireCanonicalResource(value) {
1236
+ if (requireSecureUrl$1(value, { query: true }).href !== value) throw authorityInvalidError();
1237
+ return value;
1238
+ }
1239
+ function requireExactIssuer(value) {
1240
+ requireSecureUrl$1(value, { query: false });
1241
+ return value;
1242
+ }
1243
+ function combineAbortSignals$1(operationSignal, requestSignal) {
1244
+ if (operationSignal === void 0) return requestSignal ?? void 0;
1245
+ if (requestSignal === void 0 || requestSignal === null || requestSignal === operationSignal) return operationSignal;
1246
+ return AbortSignal.any([operationSignal, requestSignal]);
1247
+ }
1248
+ function awaitWithSignal$1(promise, signal) {
1249
+ if (signal === void 0) return Promise.resolve(promise);
1250
+ signal.throwIfAborted();
1251
+ return new Promise((resolve, reject) => {
1252
+ const onAbort = () => reject(signal.reason);
1253
+ signal.addEventListener("abort", onAbort, { once: true });
1254
+ Promise.resolve(promise).then((value) => {
1255
+ signal.removeEventListener("abort", onAbort);
1256
+ resolve(value);
1257
+ }, (error) => {
1258
+ signal.removeEventListener("abort", onAbort);
1259
+ reject(error);
1260
+ });
1261
+ });
1262
+ }
1263
+ function isExactResponseUrl$1(actual, expected) {
1264
+ try {
1265
+ return requireSecureUrl$1(actual, { query: true }).href === expected;
1266
+ } catch {
1267
+ return false;
1268
+ }
1269
+ }
1270
+ function throwIfAborted$1(signal) {
1271
+ signal?.throwIfAborted();
1272
+ }
1273
+ function encodeFormComponent(value) {
1274
+ return new URLSearchParams({ value }).toString().slice(6);
1275
+ }
1276
+ function containsControlCharacter$1(value) {
1277
+ for (const character of value) {
1278
+ const point = character.codePointAt(0);
1279
+ if (point !== void 0 && (point <= 31 || point >= 127 && point <= 159)) return true;
1280
+ }
1281
+ return false;
1282
+ }
1283
+ function isClientAuthenticationMethod(value) {
1284
+ return value === "none" || value === "client_secret_basic" || value === "client_secret_post" || value === "private_key_jwt";
1285
+ }
1286
+ function translateTokenError(error, operation, hostFetchAttempt) {
1287
+ if (operation === "refresh" && hostFetchAttempt?.invoked === true) {
1288
+ if (hostFetchAttempt.responseReturned && OAuthError.isInstance(error)) {
1289
+ if (error.code === "invalid_grant") return invalidGrantError();
1290
+ if (error.code === "invalid_client") return invalidClientError();
1291
+ }
1292
+ return refreshOutcomeUnknownError();
1293
+ }
1294
+ if (error instanceof McpClientOAuthProtocolError) return canonicalizeProtocolError(error, operation === "exchange" ? tokenExchangeFailedError : tokenRefreshFailedError);
1295
+ if (OAuthError.isInstance(error)) {
1296
+ if (error.code === "invalid_grant") return invalidGrantError();
1297
+ if (error.code === "invalid_client") return invalidClientError();
1298
+ }
1299
+ return operation === "exchange" ? tokenExchangeFailedError() : tokenRefreshFailedError();
1300
+ }
1301
+ function canonicalizeProtocolError(error, fallback) {
1302
+ if (!isInternalMcpClientOAuthProtocolError(error)) return fallback();
1303
+ try {
1304
+ switch (error.code) {
1305
+ case McpClientOAuthProtocolErrorCode.InvalidOptions: return invalidOptionsError$1();
1306
+ case McpClientOAuthProtocolErrorCode.EndpointRejected: return endpointRejectedError();
1307
+ case McpClientOAuthProtocolErrorCode.DiscoveryFailed: return discoveryFailedError();
1308
+ case McpClientOAuthProtocolErrorCode.AuthorityInvalid: return authorityInvalidError();
1309
+ case McpClientOAuthProtocolErrorCode.ClientUnsupported: return clientUnsupportedError();
1310
+ case McpClientOAuthProtocolErrorCode.TransactionInvalid: return transactionInvalidError();
1311
+ case McpClientOAuthProtocolErrorCode.AuthorizationDenied: return authorizationDeniedError();
1312
+ case McpClientOAuthProtocolErrorCode.AuthorizationFailed: return authorizationFailedError();
1313
+ case McpClientOAuthProtocolErrorCode.InvalidGrant: return invalidGrantError();
1314
+ case McpClientOAuthProtocolErrorCode.InvalidClient: return invalidClientError();
1315
+ case McpClientOAuthProtocolErrorCode.TokenExchangeFailed: return tokenExchangeFailedError();
1316
+ case McpClientOAuthProtocolErrorCode.TokenRefreshFailed: return tokenRefreshFailedError();
1317
+ case McpClientOAuthProtocolErrorCode.RefreshOutcomeUnknown: return refreshOutcomeUnknownError();
1318
+ }
1319
+ } catch {
1320
+ return fallback();
1321
+ }
1322
+ return fallback();
1323
+ }
1324
+ function invalidOptionsError$1() {
1325
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.InvalidOptions, "The MCP OAuth client options are invalid.");
1326
+ }
1327
+ function endpointRejectedError() {
1328
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.EndpointRejected, "The MCP OAuth endpoint policy rejected the operation.");
1329
+ }
1330
+ function discoveryFailedError() {
1331
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.DiscoveryFailed, "MCP OAuth authority discovery failed.");
1332
+ }
1333
+ function authorityInvalidError() {
1334
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.AuthorityInvalid, "The MCP OAuth authority is invalid or does not match the configured identity.");
1335
+ }
1336
+ function clientUnsupportedError() {
1337
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.ClientUnsupported, "The provisioned MCP OAuth client is invalid or unsupported by this authority.");
1338
+ }
1339
+ function transactionInvalidError() {
1340
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.TransactionInvalid, "The MCP OAuth authorization transaction is invalid.");
1341
+ }
1342
+ function authorizationDeniedError() {
1343
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.AuthorizationDenied, "The MCP OAuth authorization request was not approved.");
1344
+ }
1345
+ function authorizationFailedError() {
1346
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.AuthorizationFailed, "The MCP OAuth authorization request could not be created.");
1347
+ }
1348
+ function invalidGrantError() {
1349
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.InvalidGrant, "The MCP OAuth authorization grant is no longer valid.");
1350
+ }
1351
+ function invalidClientError() {
1352
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.InvalidClient, "The provisioned MCP OAuth client was rejected.");
1353
+ }
1354
+ function tokenExchangeFailedError() {
1355
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.TokenExchangeFailed, "The MCP OAuth authorization code exchange failed.");
1356
+ }
1357
+ function tokenRefreshFailedError() {
1358
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.TokenRefreshFailed, "The MCP OAuth token refresh failed.");
1359
+ }
1360
+ function refreshOutcomeUnknownError() {
1361
+ return createInternalProtocolError(McpClientOAuthProtocolErrorCode.RefreshOutcomeUnknown, "The MCP OAuth token refresh outcome is unknown and must not be retried automatically.");
1362
+ }
1363
+ function tokenResponseInvalidError(operation) {
1364
+ return operation === "exchange" ? tokenExchangeFailedError() : tokenRefreshFailedError();
1365
+ }
1366
+ //#endregion
1367
+ //#region src/oauth/bootstrap.ts
1368
+ const MAX_URL_LENGTH = 4096;
1369
+ const MAX_PROTOCOL_VERSION_LENGTH = 64;
1370
+ const MAX_AUTHORIZATION_SERVER_COUNT = 16;
1371
+ const MAX_METADATA_LIST_LENGTH = 256;
1372
+ const MAX_METADATA_VALUE_LENGTH = 2048;
1373
+ const MAX_SCOPE_COUNT = 128;
1374
+ const MAX_SCOPE_STRING_LENGTH = 4096;
1375
+ const MAX_WWW_AUTHENTICATE_LENGTH = 8192;
1376
+ const STRICT_TOKEN_ENDPOINT_AUTHENTICATION_METHODS = /* @__PURE__ */ new Set([
1377
+ "none",
1378
+ "client_secret_basic",
1379
+ "client_secret_post",
1380
+ "private_key_jwt"
1381
+ ]);
1382
+ /** Stable, secret-free failure categories for OAuth bootstrap discovery. */
1383
+ const McpClientOAuthBootstrapErrorCode = {
1384
+ InvalidOptions: "MCP_CLIENT_OAUTH_BOOTSTRAP_INVALID_OPTIONS",
1385
+ EndpointRejected: "MCP_CLIENT_OAUTH_BOOTSTRAP_ENDPOINT_REJECTED",
1386
+ DiscoveryFailed: "MCP_CLIENT_OAUTH_BOOTSTRAP_DISCOVERY_FAILED",
1387
+ ProtectedResourceInvalid: "MCP_CLIENT_OAUTH_BOOTSTRAP_PROTECTED_RESOURCE_INVALID",
1388
+ AuthorityInvalid: "MCP_CLIENT_OAUTH_BOOTSTRAP_AUTHORITY_INVALID"
1389
+ };
1390
+ /** A bounded public error. Its message never contains remote response data or URLs. */
1391
+ var McpClientOAuthBootstrapError = class extends Error {
1392
+ code;
1393
+ constructor(code) {
1394
+ super(bootstrapErrorMessage(code));
1395
+ this.name = "McpClientOAuthBootstrapError";
1396
+ this.code = code;
1397
+ }
1398
+ };
1399
+ /**
1400
+ * Reasons a current-spec authority cannot be handed to the intentionally stricter runtime
1401
+ * protocol. These are compatibility facts, not a reason to trust or expose its endpoints.
1402
+ */
1403
+ const McpClientOAuthStrictCompatibilityIssue = {
1404
+ AuthorizationCodeResponseUnsupported: "authorization_code_response_unsupported",
1405
+ PkceS256Unsupported: "pkce_s256_unsupported",
1406
+ TokenEndpointAuthenticationUnsupported: "token_endpoint_authentication_unsupported",
1407
+ AuthorizationCodeGrantUnsupported: "authorization_code_grant_unsupported",
1408
+ QueryResponseModeUnsupported: "query_response_mode_unsupported",
1409
+ /** @deprecated RFC 9207 support is optional and this issue is no longer emitted. */
1410
+ AuthorizationResponseIssuerUnsupported: "authorization_response_issuer_unsupported"
1411
+ };
1412
+ /** Decode bounded host-persisted discovery without fetching, admitting endpoints, or registering clients. */
1413
+ function parseMcpClientOAuthBootstrapDiscoveryResult(value, options = {}) {
1414
+ return parseOAuthSnapshot(value, options, (record, maximum) => {
1415
+ const resourceValue = oauthSnapshotRecord(record.resource);
1416
+ assertOAuthSnapshotKeys(resourceValue, [
1417
+ "serverUrl",
1418
+ "resource",
1419
+ "resourceMetadataUrl",
1420
+ "scopesSupported"
1421
+ ]);
1422
+ const url = (input, query = true) => {
1423
+ const text = oauthSnapshotString(input, maximum);
1424
+ requireSecureUrl(text, query);
1425
+ return text;
1426
+ };
1427
+ const scopes = (input) => normalizeScopeList(oauthSnapshotStrings(input, MAX_SCOPE_COUNT), McpClientOAuthBootstrapErrorCode.InvalidOptions);
1428
+ const resource = Object.freeze({
1429
+ serverUrl: url(resourceValue.serverUrl),
1430
+ resource: url(resourceValue.resource),
1431
+ resourceMetadataUrl: url(resourceValue.resourceMetadataUrl),
1432
+ ...resourceValue.scopesSupported === void 0 ? {} : { scopesSupported: scopes(resourceValue.scopesSupported) }
1433
+ });
1434
+ const selectedScopes = record.scopes === void 0 ? void 0 : scopes(record.scopes);
1435
+ if (record.kind === "authorization-server-selection-required") {
1436
+ assertOAuthSnapshotKeys(record, [
1437
+ "kind",
1438
+ "resource",
1439
+ "scopes",
1440
+ "candidates"
1441
+ ]);
1442
+ if (!Array.isArray(record.candidates) || record.candidates.length < 2 || record.candidates.length > MAX_AUTHORIZATION_SERVER_COUNT) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1443
+ const issuers = record.candidates.map((item) => {
1444
+ const candidate = oauthSnapshotRecord(item);
1445
+ assertOAuthSnapshotKeys(candidate, ["issuer"]);
1446
+ return url(candidate.issuer, false);
1447
+ });
1448
+ if (new Set(issuers).size !== issuers.length) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1449
+ return freezeSelectionRequired(resource, selectedScopes, issuers);
1450
+ }
1451
+ if (record.kind === "ready") {
1452
+ assertOAuthSnapshotKeys(record, [
1453
+ "kind",
1454
+ "resource",
1455
+ "scopes",
1456
+ "candidate"
1457
+ ]);
1458
+ const candidate = oauthSnapshotRecord(record.candidate);
1459
+ assertOAuthSnapshotKeys(candidate, [
1460
+ "authority",
1461
+ "clientIdMetadataDocumentSupported",
1462
+ "legacyDynamicRegistrationEndpoint"
1463
+ ]);
1464
+ const authority = parseMcpClientOAuthAuthority(candidate.authority, options);
1465
+ if (authority.serverUrl !== resource.serverUrl || authority.resource !== resource.resource) throw bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);
1466
+ return freezeReady(resource, selectedScopes, {
1467
+ authority,
1468
+ clientIdMetadataDocumentSupported: oauthSnapshotBoolean(candidate.clientIdMetadataDocumentSupported),
1469
+ ...candidate.legacyDynamicRegistrationEndpoint === void 0 ? {} : { legacyDynamicRegistrationEndpoint: url(candidate.legacyDynamicRegistrationEndpoint) }
1470
+ });
1471
+ }
1472
+ if (record.kind === "strict-protocol-unsupported") {
1473
+ assertOAuthSnapshotKeys(record, [
1474
+ "kind",
1475
+ "resource",
1476
+ "scopes",
1477
+ "issuer",
1478
+ "issues"
1479
+ ]);
1480
+ const issues = oauthSnapshotStrings(record.issues, 6);
1481
+ if (issues.length === 0 || !issues.every(isCompatibilityIssue) || new Set(issues).size !== issues.length) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1482
+ return freezeStrictUnsupported(resource, selectedScopes, url(record.issuer, false), issues);
1483
+ }
1484
+ throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1485
+ });
1486
+ }
1487
+ function isCompatibilityIssue(value) {
1488
+ return Object.values(McpClientOAuthStrictCompatibilityIssue).some((issue) => issue === value);
1489
+ }
1490
+ /**
1491
+ * Parses the bounded fields needed from a raw `WWW-Authenticate` header. It deliberately drops
1492
+ * attacker-controlled OAuth error text and returns `undefined` when no Bearer challenge exists.
1493
+ */
1494
+ function parseMcpClientOAuthBootstrapChallenge(wwwAuthenticate) {
1495
+ if (typeof wwwAuthenticate !== "string" || wwwAuthenticate.length === 0 || wwwAuthenticate.length > MAX_WWW_AUTHENTICATE_LENGTH || containsForbiddenHeaderCharacter(wwwAuthenticate)) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1496
+ const bearer = findBearerChallenge(wwwAuthenticate);
1497
+ if (bearer === void 0) return void 0;
1498
+ const parameters = parseBearerParameters(bearer);
1499
+ if (parameters === null) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1500
+ return Object.freeze({
1501
+ ...parameters.resourceMetadataUrl === void 0 ? {} : { resourceMetadataUrl: requireSecureUrl(parameters.resourceMetadataUrl, true).href },
1502
+ ...parameters.scope === void 0 ? {} : { scope: normalizeScopeString(parameters.scope).join(" ") }
1503
+ });
1504
+ }
1505
+ /**
1506
+ * Framework-neutral discovery bootstrap for an application-owned interactive OAuth flow.
1507
+ *
1508
+ * It owns no persistence, tenant policy, browser redirect, client registration, or token state.
1509
+ * Hosts retain those responsibilities and pass a ready authority to `McpClientOAuthProtocol`.
1510
+ */
1511
+ var McpClientOAuthBootstrap = class {
1512
+ #fetch;
1513
+ #endpointPolicy;
1514
+ #protocolVersion;
1515
+ constructor(options) {
1516
+ if (typeof options !== "object" || options === null || typeof options.fetch !== "function" || typeof options.endpointPolicy !== "function") throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1517
+ this.#fetch = options.fetch;
1518
+ this.#endpointPolicy = options.endpointPolicy;
1519
+ this.#protocolVersion = normalizeProtocolVersion(options.protocolVersion ?? LATEST_PROTOCOL_VERSION);
1520
+ }
1521
+ async discover(input) {
1522
+ const operation = normalizeDiscoveryInput(input);
1523
+ throwIfAborted(operation.signal);
1524
+ let discoveredResourceMetadataUrl;
1525
+ let metadata;
1526
+ try {
1527
+ metadata = await discoverOAuthProtectedResourceMetadata(operation.serverUrl, {
1528
+ protocolVersion: this.#protocolVersion,
1529
+ ...operation.challenge?.resourceMetadataUrl === void 0 ? {} : { resourceMetadataUrl: operation.challenge.resourceMetadataUrl }
1530
+ }, this.#createFetch({
1531
+ kind: "resource-metadata",
1532
+ credentialed: false,
1533
+ serverUrl: operation.serverUrl,
1534
+ signal: operation.signal,
1535
+ onAcceptedResponse(endpoint, response) {
1536
+ if (response.ok) discoveredResourceMetadataUrl = endpoint;
1537
+ }
1538
+ }));
1539
+ } catch (error) {
1540
+ throwIfAborted(operation.signal);
1541
+ if (error instanceof McpClientOAuthBootstrapError) throw error;
1542
+ throw bootstrapError(McpClientOAuthBootstrapErrorCode.DiscoveryFailed);
1543
+ }
1544
+ throwIfAborted(operation.signal);
1545
+ const resource = normalizeProtectedResource({
1546
+ serverUrl: operation.serverUrl,
1547
+ resourceMetadataUrl: discoveredResourceMetadataUrl ?? operation.challenge?.resourceMetadataUrl,
1548
+ challengeResourceMetadataUrl: operation.challenge?.resourceMetadataUrl,
1549
+ metadata
1550
+ });
1551
+ const scopes = selectScopes(operation.challenge?.scope, resource.scopesSupported);
1552
+ const issuers = normalizeAuthorizationServers(metadata.authorization_servers);
1553
+ if (operation.issuer === void 0 && issuers.length > 1) return freezeSelectionRequired(resource, scopes, issuers);
1554
+ const issuer = operation.issuer ?? issuers[0];
1555
+ if (issuer === void 0 || !issuers.includes(issuer)) throw bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);
1556
+ let authorizationMetadata;
1557
+ try {
1558
+ authorizationMetadata = await discoverAuthorizationServerMetadata(issuer, {
1559
+ fetchFn: this.#createFetch({
1560
+ kind: "authorization-server-metadata",
1561
+ credentialed: false,
1562
+ serverUrl: operation.serverUrl,
1563
+ resource: resource.resource,
1564
+ issuer,
1565
+ signal: operation.signal
1566
+ }),
1567
+ protocolVersion: this.#protocolVersion
1568
+ });
1569
+ } catch (error) {
1570
+ throwIfAborted(operation.signal);
1571
+ if (error instanceof McpClientOAuthBootstrapError) throw error;
1572
+ throw bootstrapError(McpClientOAuthBootstrapErrorCode.DiscoveryFailed);
1573
+ }
1574
+ throwIfAborted(operation.signal);
1575
+ if (authorizationMetadata === void 0 || authorizationMetadata.issuer !== issuer) throw bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);
1576
+ const compatibilityIssues = strictCompatibilityIssues(authorizationMetadata);
1577
+ if (compatibilityIssues.length > 0) return freezeStrictUnsupported(resource, scopes, issuer, compatibilityIssues);
1578
+ const authority = createStrictAuthority({
1579
+ serverUrl: operation.serverUrl,
1580
+ resource,
1581
+ issuer,
1582
+ metadata: authorizationMetadata,
1583
+ ...operation.challenge?.scope === void 0 ? {} : { challengedScope: operation.challenge.scope }
1584
+ });
1585
+ await this.#authorizeEndpoint(authority.authorizationEndpoint, {
1586
+ kind: "authorization",
1587
+ credentialed: false,
1588
+ serverUrl: operation.serverUrl,
1589
+ resource: authority.resource,
1590
+ issuer,
1591
+ signal: operation.signal
1592
+ });
1593
+ await this.#authorizeEndpoint(authority.tokenEndpoint, {
1594
+ kind: "token",
1595
+ credentialed: true,
1596
+ serverUrl: operation.serverUrl,
1597
+ resource: authority.resource,
1598
+ issuer,
1599
+ signal: operation.signal
1600
+ });
1601
+ const legacyDynamicRegistrationEndpoint = normalizeOptionalLegacyRegistrationEndpoint(authorizationMetadata.registration_endpoint);
1602
+ return freezeReady(resource, scopes, {
1603
+ authority,
1604
+ clientIdMetadataDocumentSupported: authorizationMetadata.client_id_metadata_document_supported === true,
1605
+ ...legacyDynamicRegistrationEndpoint === void 0 ? {} : { legacyDynamicRegistrationEndpoint }
1606
+ });
1607
+ }
1608
+ #createFetch(input) {
1609
+ return async (url, init) => {
1610
+ throwIfAborted(input.signal);
1611
+ const endpoint = requireSecureUrl(String(url), true);
1612
+ await this.#authorizeEndpoint(endpoint.href, input);
1613
+ throwIfAborted(input.signal);
1614
+ const signal = combineAbortSignals(input.signal, init?.signal);
1615
+ const requestInit = {
1616
+ ...init,
1617
+ redirect: "error"
1618
+ };
1619
+ if (signal !== void 0) requestInit.signal = signal;
1620
+ const response = await this.#fetch(new URL(endpoint.href), requestInit);
1621
+ throwIfAborted(input.signal);
1622
+ if (response.redirected || response.url.length > 0 && !isExactResponseUrl(response.url, endpoint.href)) throw bootstrapError(McpClientOAuthBootstrapErrorCode.EndpointRejected);
1623
+ input.onAcceptedResponse?.(endpoint.href, response);
1624
+ return response;
1625
+ };
1626
+ }
1627
+ async #authorizeEndpoint(endpointValue, input) {
1628
+ throwIfAborted(input.signal);
1629
+ const endpoint = requireSecureUrl(endpointValue, true);
1630
+ let admitted;
1631
+ try {
1632
+ admitted = await awaitWithSignal(Promise.resolve().then(() => this.#endpointPolicy(Object.freeze({
1633
+ endpoint: new URL(endpoint.href),
1634
+ kind: input.kind,
1635
+ credentialed: input.credentialed,
1636
+ serverUrl: new URL(input.serverUrl),
1637
+ ...input.resource === void 0 ? {} : { resource: new URL(input.resource) },
1638
+ ...input.resource === void 0 ? {} : { exactResource: input.resource },
1639
+ ...input.issuer === void 0 ? {} : {
1640
+ issuer: new URL(input.issuer),
1641
+ exactIssuer: input.issuer
1642
+ },
1643
+ ...input.signal === void 0 ? {} : { signal: input.signal }
1644
+ }))), input.signal);
1645
+ } catch {
1646
+ throwIfAborted(input.signal);
1647
+ throw bootstrapError(McpClientOAuthBootstrapErrorCode.EndpointRejected);
1648
+ }
1649
+ throwIfAborted(input.signal);
1650
+ if (admitted !== true) throw bootstrapError(McpClientOAuthBootstrapErrorCode.EndpointRejected);
1651
+ }
1652
+ };
1653
+ function normalizeDiscoveryInput(input) {
1654
+ if (typeof input !== "object" || input === null) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1655
+ if (input.challenge !== void 0 && input.wwwAuthenticate !== void 0) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1656
+ const serverUrl = requireSecureUrl(input.serverUrl, true).href;
1657
+ let challenge = input.wwwAuthenticate === void 0 ? void 0 : parseMcpClientOAuthBootstrapChallenge(input.wwwAuthenticate);
1658
+ if (input.challenge !== void 0) {
1659
+ if (typeof input.challenge !== "object" || input.challenge === null) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1660
+ challenge = Object.freeze({
1661
+ ...input.challenge.resourceMetadataUrl === void 0 ? {} : { resourceMetadataUrl: requireSecureUrl(input.challenge.resourceMetadataUrl, true).href },
1662
+ ...input.challenge.scope === void 0 ? {} : { scope: normalizeScopeString(input.challenge.scope).join(" ") }
1663
+ });
1664
+ }
1665
+ if (input.issuer !== void 0) requireSecureUrl(input.issuer, false);
1666
+ const issuer = input.issuer;
1667
+ return Object.freeze({
1668
+ serverUrl,
1669
+ ...challenge === void 0 ? {} : { challenge },
1670
+ ...issuer === void 0 ? {} : { issuer },
1671
+ signal: input.signal
1672
+ });
1673
+ }
1674
+ function normalizeProtectedResource(input) {
1675
+ if (input.resourceMetadataUrl === void 0) throw bootstrapError(McpClientOAuthBootstrapErrorCode.DiscoveryFailed);
1676
+ const resource = requireSecureUrl(input.metadata.resource, true);
1677
+ if (input.metadata.resource !== resource.href) throw bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);
1678
+ const metadataEndpoint = requireSecureUrl(input.resourceMetadataUrl, true);
1679
+ if (!(input.challengeResourceMetadataUrl === void 0 ? protectedResourceWellKnownUrl(resource).href === metadataEndpoint.href : resourceUrlFromServerUrl(input.serverUrl).href === resource.href)) throw bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);
1680
+ if (input.metadata.bearer_methods_supported !== void 0 && !input.metadata.bearer_methods_supported.includes("header") || input.metadata.tls_client_certificate_bound_access_tokens === true || input.metadata.dpop_bound_access_tokens_required === true) throw bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);
1681
+ const scopesSupported = input.metadata.scopes_supported === void 0 ? void 0 : normalizeScopeList(input.metadata.scopes_supported, McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);
1682
+ return Object.freeze({
1683
+ serverUrl: input.serverUrl,
1684
+ resource: resource.href,
1685
+ resourceMetadataUrl: metadataEndpoint.href,
1686
+ ...scopesSupported === void 0 ? {} : { scopesSupported }
1687
+ });
1688
+ }
1689
+ function protectedResourceWellKnownUrl(resource) {
1690
+ let pathname = resource.pathname;
1691
+ if (pathname.endsWith("/")) pathname = pathname.slice(0, -1);
1692
+ const metadataUrl = new URL(`/.well-known/oauth-protected-resource${pathname}`, resource.origin);
1693
+ metadataUrl.search = resource.search;
1694
+ return metadataUrl;
1695
+ }
1696
+ function normalizeAuthorizationServers(values) {
1697
+ if (!Array.isArray(values) || values.length === 0 || values.length > MAX_AUTHORIZATION_SERVER_COUNT) throw bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);
1698
+ const normalized = [...new Set(values)];
1699
+ for (const value of normalized) requireSecureUrl(value, false);
1700
+ if (normalized.length === 0) throw bootstrapError(McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid);
1701
+ return Object.freeze(normalized);
1702
+ }
1703
+ function strictCompatibilityIssues(metadata) {
1704
+ const issues = [];
1705
+ const responseTypes = normalizeMetadataList(metadata.response_types_supported);
1706
+ const codeChallengeMethods = normalizeMetadataList(metadata.code_challenge_methods_supported);
1707
+ const tokenAuthenticationMethods = normalizeMetadataList(metadata.token_endpoint_auth_methods_supported);
1708
+ if (!responseTypes.includes("code")) issues.push(McpClientOAuthStrictCompatibilityIssue.AuthorizationCodeResponseUnsupported);
1709
+ if (!codeChallengeMethods.includes("S256")) issues.push(McpClientOAuthStrictCompatibilityIssue.PkceS256Unsupported);
1710
+ if (!tokenAuthenticationMethods.some((method) => STRICT_TOKEN_ENDPOINT_AUTHENTICATION_METHODS.has(method))) issues.push(McpClientOAuthStrictCompatibilityIssue.TokenEndpointAuthenticationUnsupported);
1711
+ if (metadata.grant_types_supported !== void 0 && !normalizeMetadataList(metadata.grant_types_supported).includes("authorization_code")) issues.push(McpClientOAuthStrictCompatibilityIssue.AuthorizationCodeGrantUnsupported);
1712
+ if (metadata.response_modes_supported !== void 0 && !normalizeMetadataList(metadata.response_modes_supported).includes("query")) issues.push(McpClientOAuthStrictCompatibilityIssue.QueryResponseModeUnsupported);
1713
+ return Object.freeze(issues);
1714
+ }
1715
+ function createStrictAuthority(input) {
1716
+ return Object.freeze({
1717
+ serverUrl: input.serverUrl,
1718
+ resource: input.resource.resource,
1719
+ issuer: input.issuer,
1720
+ authorizationEndpoint: requireSecureUrl(input.metadata.authorization_endpoint, true).href,
1721
+ tokenEndpoint: requireSecureUrl(input.metadata.token_endpoint, true).href,
1722
+ responseTypesSupported: normalizeMetadataList(input.metadata.response_types_supported),
1723
+ codeChallengeMethodsSupported: normalizeMetadataList(input.metadata.code_challenge_methods_supported),
1724
+ tokenEndpointAuthMethodsSupported: normalizeMetadataList(input.metadata.token_endpoint_auth_methods_supported),
1725
+ ...input.metadata.grant_types_supported === void 0 ? {} : { grantTypesSupported: normalizeMetadataList(input.metadata.grant_types_supported) },
1726
+ ...input.challengedScope !== void 0 || input.resource.scopesSupported === void 0 ? {} : { resourceScopesSupported: input.resource.scopesSupported },
1727
+ ...input.challengedScope !== void 0 || input.metadata.scopes_supported === void 0 ? {} : { authorizationScopesSupported: normalizeScopeList(input.metadata.scopes_supported, McpClientOAuthBootstrapErrorCode.AuthorityInvalid) },
1728
+ authorizationResponseIssuerParameterSupported: input.metadata.authorization_response_iss_parameter_supported === true
1729
+ });
1730
+ }
1731
+ function selectScopes(challengeScope, resourceScopes) {
1732
+ if (challengeScope !== void 0) return normalizeScopeString(challengeScope);
1733
+ return resourceScopes;
1734
+ }
1735
+ function normalizeScopeString(value) {
1736
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_SCOPE_STRING_LENGTH || containsControlCharacter(value)) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1737
+ return normalizeScopeList(value.split(" "), McpClientOAuthBootstrapErrorCode.InvalidOptions);
1738
+ }
1739
+ function normalizeScopeList(values, errorCode) {
1740
+ if (!Array.isArray(values) || values.length > MAX_SCOPE_COUNT) throw bootstrapError(errorCode);
1741
+ const normalized = [...new Set(values)];
1742
+ for (const value of normalized) if (!isMcpClientOAuthScopeToken(value)) throw bootstrapError(errorCode);
1743
+ return Object.freeze(normalized);
1744
+ }
1745
+ function normalizeMetadataList(values) {
1746
+ if (values === void 0) return Object.freeze([]);
1747
+ if (!Array.isArray(values) || values.length > MAX_METADATA_LIST_LENGTH) throw bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);
1748
+ const normalized = [...new Set(values)];
1749
+ for (const value of normalized) if (typeof value !== "string" || value.length === 0 || value.length > MAX_METADATA_VALUE_LENGTH || containsControlCharacter(value)) throw bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);
1750
+ return Object.freeze(normalized);
1751
+ }
1752
+ function normalizeOptionalLegacyRegistrationEndpoint(value) {
1753
+ if (value === void 0) return void 0;
1754
+ try {
1755
+ return requireSecureUrl(value, true).href;
1756
+ } catch {
1757
+ return;
1758
+ }
1759
+ }
1760
+ function freezeSelectionRequired(resource, scopes, issuers) {
1761
+ return Object.freeze({
1762
+ kind: "authorization-server-selection-required",
1763
+ resource: copyResource(resource),
1764
+ ...scopes === void 0 ? {} : { scopes: Object.freeze([...scopes]) },
1765
+ candidates: Object.freeze(issuers.map((issuer) => Object.freeze({ issuer })))
1766
+ });
1767
+ }
1768
+ function freezeStrictUnsupported(resource, scopes, issuer, issues) {
1769
+ return Object.freeze({
1770
+ kind: "strict-protocol-unsupported",
1771
+ resource: copyResource(resource),
1772
+ ...scopes === void 0 ? {} : { scopes: Object.freeze([...scopes]) },
1773
+ issuer,
1774
+ issues: Object.freeze([...issues])
1775
+ });
1776
+ }
1777
+ function freezeReady(resource, scopes, candidate) {
1778
+ return Object.freeze({
1779
+ kind: "ready",
1780
+ resource: copyResource(resource),
1781
+ ...scopes === void 0 ? {} : { scopes: Object.freeze([...scopes]) },
1782
+ candidate: Object.freeze({
1783
+ authority: copyAuthority(candidate.authority),
1784
+ clientIdMetadataDocumentSupported: candidate.clientIdMetadataDocumentSupported,
1785
+ ...candidate.legacyDynamicRegistrationEndpoint === void 0 ? {} : { legacyDynamicRegistrationEndpoint: candidate.legacyDynamicRegistrationEndpoint }
1786
+ })
1787
+ });
1788
+ }
1789
+ function copyResource(resource) {
1790
+ return Object.freeze({
1791
+ serverUrl: resource.serverUrl,
1792
+ resource: resource.resource,
1793
+ resourceMetadataUrl: resource.resourceMetadataUrl,
1794
+ ...resource.scopesSupported === void 0 ? {} : { scopesSupported: Object.freeze([...resource.scopesSupported]) }
1795
+ });
1796
+ }
1797
+ function copyAuthority(authority) {
1798
+ return Object.freeze({
1799
+ serverUrl: authority.serverUrl,
1800
+ resource: authority.resource,
1801
+ issuer: authority.issuer,
1802
+ authorizationEndpoint: authority.authorizationEndpoint,
1803
+ tokenEndpoint: authority.tokenEndpoint,
1804
+ responseTypesSupported: Object.freeze([...authority.responseTypesSupported]),
1805
+ codeChallengeMethodsSupported: Object.freeze([...authority.codeChallengeMethodsSupported]),
1806
+ tokenEndpointAuthMethodsSupported: Object.freeze([...authority.tokenEndpointAuthMethodsSupported]),
1807
+ ...authority.grantTypesSupported === void 0 ? {} : { grantTypesSupported: Object.freeze([...authority.grantTypesSupported]) },
1808
+ ...authority.resourceScopesSupported === void 0 ? {} : { resourceScopesSupported: Object.freeze([...authority.resourceScopesSupported]) },
1809
+ ...authority.authorizationScopesSupported === void 0 ? {} : { authorizationScopesSupported: Object.freeze([...authority.authorizationScopesSupported]) },
1810
+ authorizationResponseIssuerParameterSupported: authority.authorizationResponseIssuerParameterSupported
1811
+ });
1812
+ }
1813
+ function normalizeProtocolVersion(value) {
1814
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_PROTOCOL_VERSION_LENGTH || containsControlCharacter(value)) throw bootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
1815
+ return value;
1816
+ }
1817
+ function requireSecureUrl(value, query) {
1818
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_URL_LENGTH) throw bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);
1819
+ let url;
1820
+ try {
1821
+ url = new URL(value);
1822
+ } catch {
1823
+ throw bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);
1824
+ }
1825
+ if (url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0 || url.hash.length > 0 || !query && url.search.length > 0) throw bootstrapError(McpClientOAuthBootstrapErrorCode.AuthorityInvalid);
1826
+ return url;
1827
+ }
1828
+ function isExactResponseUrl(value, expected) {
1829
+ try {
1830
+ return new URL(value).href === expected;
1831
+ } catch {
1832
+ return false;
1833
+ }
1834
+ }
1835
+ function combineAbortSignals(operationSignal, requestSignal) {
1836
+ if (operationSignal === void 0) return requestSignal ?? void 0;
1837
+ if (requestSignal === void 0 || requestSignal === null || requestSignal === operationSignal) return operationSignal;
1838
+ return AbortSignal.any([operationSignal, requestSignal]);
1839
+ }
1840
+ function awaitWithSignal(promise, signal) {
1841
+ if (signal === void 0) return Promise.resolve(promise);
1842
+ signal.throwIfAborted();
1843
+ return new Promise((resolve, reject) => {
1844
+ const onAbort = () => reject(signal.reason);
1845
+ signal.addEventListener("abort", onAbort, { once: true });
1846
+ Promise.resolve(promise).then((value) => {
1847
+ signal.removeEventListener("abort", onAbort);
1848
+ resolve(value);
1849
+ }, (error) => {
1850
+ signal.removeEventListener("abort", onAbort);
1851
+ reject(error);
1852
+ });
1853
+ });
1854
+ }
1855
+ function throwIfAborted(signal) {
1856
+ signal?.throwIfAborted();
1857
+ }
1858
+ function containsControlCharacter(value) {
1859
+ for (const character of value) {
1860
+ const point = character.codePointAt(0);
1861
+ if (point !== void 0 && (point <= 31 || point >= 127 && point <= 159)) return true;
1862
+ }
1863
+ return false;
1864
+ }
1865
+ function findBearerChallenge(value) {
1866
+ let quoted = false;
1867
+ let escaped = false;
1868
+ for (let index = 0; index < value.length; index += 1) {
1869
+ const character = value[index];
1870
+ if (quoted) {
1871
+ if (escaped) {
1872
+ escaped = false;
1873
+ continue;
1874
+ }
1875
+ if (character === "\\") {
1876
+ escaped = true;
1877
+ continue;
1878
+ }
1879
+ if (character === "\"") quoted = false;
1880
+ continue;
1881
+ }
1882
+ if (character === "\"") {
1883
+ quoted = true;
1884
+ continue;
1885
+ }
1886
+ if (value.slice(index, index + 6).toLowerCase() !== "bearer") continue;
1887
+ let boundary = index - 1;
1888
+ while (boundary >= 0 && /\s/u.test(value[boundary] ?? "")) boundary -= 1;
1889
+ const before = boundary < 0 ? void 0 : value[boundary];
1890
+ const after = value[index + 6];
1891
+ if ((before === void 0 || before === ",") && /\s/u.test(after ?? "")) {
1892
+ let parameterStart = index + 6;
1893
+ while (parameterStart < value.length && /\s/u.test(value[parameterStart] ?? "")) parameterStart += 1;
1894
+ const challengeEnd = findAuthenticationChallengeEnd(value, parameterStart);
1895
+ return value.slice(parameterStart, challengeEnd).trimEnd();
1896
+ }
1897
+ }
1898
+ }
1899
+ function findAuthenticationChallengeEnd(value, start) {
1900
+ let quoted = false;
1901
+ let escaped = false;
1902
+ for (let index = start; index < value.length; index += 1) {
1903
+ const character = value[index];
1904
+ if (quoted) {
1905
+ if (escaped) {
1906
+ escaped = false;
1907
+ continue;
1908
+ }
1909
+ if (character === "\\") {
1910
+ escaped = true;
1911
+ continue;
1912
+ }
1913
+ if (character === "\"") quoted = false;
1914
+ continue;
1915
+ }
1916
+ if (character === "\"") {
1917
+ quoted = true;
1918
+ continue;
1919
+ }
1920
+ if (character !== ",") continue;
1921
+ let cursor = index + 1;
1922
+ while (cursor < value.length && /\s/u.test(value[cursor] ?? "")) cursor += 1;
1923
+ const tokenStart = cursor;
1924
+ while (cursor < value.length && isAuthenticationTokenCharacter(value[cursor])) cursor += 1;
1925
+ if (cursor === tokenStart) continue;
1926
+ while (cursor < value.length && /\s/u.test(value[cursor] ?? "")) cursor += 1;
1927
+ if (value[cursor] !== "=") return index;
1928
+ }
1929
+ return value.length;
1930
+ }
1931
+ function isAuthenticationTokenCharacter(value) {
1932
+ return value !== void 0 && /^[!#$%&'*+\-.^_`|~A-Za-z0-9]$/u.test(value);
1933
+ }
1934
+ /** `null` means the Bearer credential was malformed or repeated a security-relevant field. */
1935
+ function parseBearerParameters(bearerParameters) {
1936
+ let offset = 0;
1937
+ let resourceMetadataUrl;
1938
+ let scope;
1939
+ while (offset < bearerParameters.length) {
1940
+ while (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) offset += 1;
1941
+ const nameStart = offset;
1942
+ while (offset < bearerParameters.length && isAuthenticationTokenCharacter(bearerParameters[offset])) offset += 1;
1943
+ if (offset === nameStart) return null;
1944
+ const name = bearerParameters.slice(nameStart, offset).toLowerCase();
1945
+ while (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) offset += 1;
1946
+ if (bearerParameters[offset] !== "=") return null;
1947
+ offset += 1;
1948
+ while (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) offset += 1;
1949
+ let value = "";
1950
+ if (bearerParameters[offset] === "\"") {
1951
+ offset += 1;
1952
+ let closed = false;
1953
+ while (offset < bearerParameters.length) {
1954
+ const character = bearerParameters[offset];
1955
+ offset += 1;
1956
+ if (character === " ") return null;
1957
+ if (character === "\\") {
1958
+ const escaped = bearerParameters[offset];
1959
+ if (escaped === void 0 || escaped === " ") return null;
1960
+ value += escaped;
1961
+ offset += 1;
1962
+ continue;
1963
+ }
1964
+ if (character === "\"") {
1965
+ closed = true;
1966
+ break;
1967
+ }
1968
+ if (character === void 0) return null;
1969
+ value += character;
1970
+ }
1971
+ if (!closed) return null;
1972
+ } else {
1973
+ const valueStart = offset;
1974
+ while (offset < bearerParameters.length && !isOptionalWhitespace(bearerParameters[offset]) && bearerParameters[offset] !== ",") offset += 1;
1975
+ value = bearerParameters.slice(valueStart, offset);
1976
+ }
1977
+ if (value.length === 0 && (name === "resource_metadata" || name === "scope")) return null;
1978
+ if (name === "resource_metadata") {
1979
+ if (resourceMetadataUrl !== void 0) return null;
1980
+ resourceMetadataUrl = value;
1981
+ } else if (name === "scope") {
1982
+ if (scope !== void 0) return null;
1983
+ scope = value;
1984
+ }
1985
+ while (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) offset += 1;
1986
+ if (offset === bearerParameters.length) break;
1987
+ if (bearerParameters[offset] !== ",") return null;
1988
+ offset += 1;
1989
+ while (offset < bearerParameters.length && isOptionalWhitespace(bearerParameters[offset])) offset += 1;
1990
+ if (offset === bearerParameters.length) return null;
1991
+ }
1992
+ return Object.freeze({
1993
+ ...resourceMetadataUrl === void 0 ? {} : { resourceMetadataUrl },
1994
+ ...scope === void 0 ? {} : { scope }
1995
+ });
1996
+ }
1997
+ function isOptionalWhitespace(value) {
1998
+ return value === " " || value === " ";
1999
+ }
2000
+ function containsForbiddenHeaderCharacter(value) {
2001
+ for (const character of value) {
2002
+ const point = character.codePointAt(0);
2003
+ if (point !== void 0 && (point <= 31 && point !== 9 || point >= 127 && point <= 159)) return true;
2004
+ }
2005
+ return false;
2006
+ }
2007
+ function bootstrapError(code) {
2008
+ return new McpClientOAuthBootstrapError(code);
2009
+ }
2010
+ function bootstrapErrorMessage(code) {
2011
+ switch (code) {
2012
+ case McpClientOAuthBootstrapErrorCode.InvalidOptions: return "The OAuth bootstrap options are invalid.";
2013
+ case McpClientOAuthBootstrapErrorCode.EndpointRejected: return "An OAuth bootstrap endpoint was rejected.";
2014
+ case McpClientOAuthBootstrapErrorCode.DiscoveryFailed: return "OAuth bootstrap discovery failed.";
2015
+ case McpClientOAuthBootstrapErrorCode.ProtectedResourceInvalid: return "The OAuth protected-resource metadata is invalid.";
2016
+ case McpClientOAuthBootstrapErrorCode.AuthorityInvalid: return "The OAuth authorization-server metadata is invalid.";
2017
+ default: return "OAuth bootstrap failed.";
2018
+ }
2019
+ }
2020
+ //#endregion
2021
+ //#region src/oauth/refresh-coordinator.ts
2022
+ const DEFAULT_MAX_IN_FLIGHT_KEYS = 100;
2023
+ const CALLER_ABORTED = Symbol("caller-aborted");
2024
+ const GENERATION_RETIRED = Symbol("generation-retired");
2025
+ /** Stable, secret-free refresh-coordinator failures. */
2026
+ const McpClientOAuthRefreshErrorCode = {
2027
+ InvalidOptions: "MCP_CLIENT_OAUTH_REFRESH_INVALID_OPTIONS",
2028
+ Closed: "MCP_CLIENT_OAUTH_REFRESH_COORDINATOR_CLOSED",
2029
+ CapacityExceeded: "MCP_CLIENT_OAUTH_REFRESH_CAPACITY_EXCEEDED",
2030
+ RevisionInFlight: "MCP_CLIENT_OAUTH_REFRESH_REVISION_IN_FLIGHT",
2031
+ CredentialMissing: "MCP_CLIENT_OAUTH_CREDENTIAL_MISSING",
2032
+ CredentialInvalidated: "MCP_CLIENT_OAUTH_CREDENTIAL_INVALIDATED",
2033
+ RevisionMismatch: "MCP_CLIENT_OAUTH_CREDENTIAL_REVISION_MISMATCH",
2034
+ RefreshFailed: "MCP_CLIENT_OAUTH_REFRESH_FAILED",
2035
+ StoreFailed: "MCP_CLIENT_OAUTH_CREDENTIAL_STORE_FAILED",
2036
+ InvalidStoreResult: "MCP_CLIENT_OAUTH_CREDENTIAL_STORE_RESULT_INVALID",
2037
+ InvalidationHookFailed: "MCP_CLIENT_OAUTH_INVALIDATION_HOOK_FAILED",
2038
+ CallerAborted: "MCP_CLIENT_OAUTH_REFRESH_CALLER_ABORTED",
2039
+ InternalFailure: "MCP_CLIENT_OAUTH_REFRESH_INTERNAL_FAILURE"
2040
+ };
2041
+ /**
2042
+ * Public coordinator error. Errors emitted across coordinator boundaries are rematerialized by
2043
+ * code so their fixed messages never retain identity, credential, or caught error data.
2044
+ */
2045
+ var McpClientOAuthRefreshError = class extends Error {
2046
+ code;
2047
+ constructor(code, message) {
2048
+ super(message);
2049
+ this.name = "McpClientOAuthRefreshError";
2050
+ this.code = code;
2051
+ }
2052
+ };
2053
+ /**
2054
+ * Bounded, framework-neutral refresh ownership keyed by an opaque, non-secret identity.
2055
+ *
2056
+ * Calls for the same identity and exact revision share one refresh. A different revision is never
2057
+ * joined to existing work. A durable pre-dispatch claim prevents multiple coordinators from
2058
+ * sending the same refresh token. Only the holder's exact claim can commit the complete next
2059
+ * generation. Commit loss reloads the authoritative winner and never retries the old token.
2060
+ * Closing drains accepted mutations; it does not abandon a claimed generation.
2061
+ */
2062
+ var McpClientOAuthRefreshCoordinator = class {
2063
+ #store;
2064
+ #refreshCredential;
2065
+ #classifyRefreshFailure;
2066
+ #onInvalidated;
2067
+ #maxInFlightKeys;
2068
+ #refreshes = /* @__PURE__ */ new Map();
2069
+ #invalidations = /* @__PURE__ */ new Map();
2070
+ #retiredRevisions = /* @__PURE__ */ new Map();
2071
+ #closed = false;
2072
+ #closeTask;
2073
+ constructor(options) {
2074
+ if (!isObjectLike(options)) throw invalidOptionsError();
2075
+ let store;
2076
+ let refreshCredential;
2077
+ let classifyRefreshFailure;
2078
+ let onInvalidated;
2079
+ let maxInFlightKeys;
2080
+ try {
2081
+ store = options.store;
2082
+ refreshCredential = options.refresh;
2083
+ classifyRefreshFailure = options.classifyRefreshFailure;
2084
+ onInvalidated = options.onInvalidated;
2085
+ maxInFlightKeys = options.maxInFlightKeys ?? DEFAULT_MAX_IN_FLIGHT_KEYS;
2086
+ } catch {
2087
+ throw invalidOptionsError();
2088
+ }
2089
+ if (!isCredentialStore(store) || typeof refreshCredential !== "function") throw invalidOptionsError();
2090
+ if (classifyRefreshFailure !== void 0 && typeof classifyRefreshFailure !== "function") throw invalidOptionsError();
2091
+ if (onInvalidated !== void 0 && typeof onInvalidated !== "function") throw invalidOptionsError();
2092
+ if (!Number.isSafeInteger(maxInFlightKeys) || maxInFlightKeys <= 0) throw invalidOptionsError();
2093
+ this.#store = store;
2094
+ this.#refreshCredential = refreshCredential;
2095
+ this.#classifyRefreshFailure = classifyRefreshFailure ?? classifyMcpClientOAuthRefreshFailure;
2096
+ this.#onInvalidated = onInvalidated;
2097
+ this.#maxInFlightKeys = maxInFlightKeys;
2098
+ }
2099
+ get closed() {
2100
+ return this.#closed;
2101
+ }
2102
+ snapshot() {
2103
+ let waiterCount = 0;
2104
+ for (const entry of this.#refreshes.values()) waiterCount += entry.waiterCount;
2105
+ for (const entry of this.#invalidations.values()) waiterCount += entry.waiterCount;
2106
+ return Object.freeze({
2107
+ closed: this.#closed,
2108
+ maxInFlightKeys: this.#maxInFlightKeys,
2109
+ inFlightKeyCount: this.#inFlightKeyCount(),
2110
+ refreshCount: this.#refreshes.size,
2111
+ invalidationCount: this.#invalidations.size,
2112
+ waiterCount
2113
+ });
2114
+ }
2115
+ async refresh(identity, expectedRevision, options = {}) {
2116
+ this.#assertOpen();
2117
+ assertRevision(expectedRevision);
2118
+ throwIfCallerAborted(options.signal);
2119
+ if (this.#invalidations.get(identity) !== void 0) throw credentialInvalidatedError();
2120
+ this.#assertGenerationUsable(identity, expectedRevision);
2121
+ const existing = this.#refreshes.get(identity);
2122
+ if (existing !== void 0) {
2123
+ if (existing.revision !== expectedRevision) throw revisionInFlightError();
2124
+ return this.#waitForRefresh(existing, options.signal);
2125
+ }
2126
+ this.#assertCapacity(identity);
2127
+ const entry = this.#createRefreshEntry(identity, expectedRevision);
2128
+ return this.#waitForRefresh(entry, options.signal);
2129
+ }
2130
+ async invalidate(identity, expectedRevision, options = {}) {
2131
+ this.#assertOpen();
2132
+ assertRevision(expectedRevision);
2133
+ throwIfCallerAborted(options.signal);
2134
+ const reason = options.reason ?? McpClientOAuthCredentialInvalidationReason.Explicit;
2135
+ assertInvalidationReason(reason);
2136
+ const existing = this.#invalidations.get(identity);
2137
+ if (existing !== void 0) {
2138
+ if (existing.revision !== expectedRevision || existing.reason !== reason) throw revisionInFlightError();
2139
+ return this.#waitForInvalidation(existing, options.signal);
2140
+ }
2141
+ this.#assertCapacity(identity);
2142
+ const refreshEntry = this.#refreshes.get(identity);
2143
+ const matchingRefresh = refreshEntry?.revision === expectedRevision ? refreshEntry : void 0;
2144
+ if (matchingRefresh?.phase === "settling" && matchingRefresh.settlementOwnsInvalidation && matchingRefresh.retirementError === void 0) return this.#waitForSettlingInvalidation(matchingRefresh, options.signal);
2145
+ const entry = this.#createInvalidationEntry(identity, expectedRevision, reason, matchingRefresh);
2146
+ if (matchingRefresh !== void 0) this.#retireRefresh(matchingRefresh);
2147
+ return this.#waitForInvalidation(entry, options.signal);
2148
+ }
2149
+ close() {
2150
+ if (this.#closeTask !== void 0) return this.#closeTask;
2151
+ this.#closed = true;
2152
+ const tasks = [...[...this.#refreshes.values()].map(requireRefreshTask), ...[...this.#invalidations.values()].map(requireInvalidationTask)];
2153
+ this.#closeTask = Promise.all(tasks).then(() => {
2154
+ this.#retiredRevisions.clear();
2155
+ });
2156
+ return this.#closeTask;
2157
+ }
2158
+ async [Symbol.asyncDispose]() {
2159
+ await this.close();
2160
+ }
2161
+ #createRefreshEntry(identity, revision) {
2162
+ const entry = {
2163
+ token: Symbol("mcp-client-oauth-refresh"),
2164
+ revision,
2165
+ claimId: createRefreshClaimId(),
2166
+ workController: new AbortController(),
2167
+ settlementController: new AbortController(),
2168
+ retirementController: new AbortController(),
2169
+ phase: "loading",
2170
+ settlementOwnsInvalidation: false,
2171
+ waiterCount: 0,
2172
+ retirementError: void 0,
2173
+ task: void 0
2174
+ };
2175
+ this.#refreshes.set(identity, entry);
2176
+ entry.task = Promise.resolve().then(async () => this.#executeRefresh(identity, entry)).catch(() => refreshErrorOutcome(internalFailureError()));
2177
+ entry.task.then(() => {
2178
+ entry.phase = "done";
2179
+ if (this.#refreshes.get(identity)?.token === entry.token) this.#refreshes.delete(identity);
2180
+ });
2181
+ return entry;
2182
+ }
2183
+ #createInvalidationEntry(identity, revision, reason, matchingRefresh) {
2184
+ const entry = {
2185
+ token: Symbol("mcp-client-oauth-invalidation"),
2186
+ revision,
2187
+ reason,
2188
+ controller: new AbortController(),
2189
+ waiterCount: 0,
2190
+ task: void 0
2191
+ };
2192
+ this.#invalidations.set(identity, entry);
2193
+ const refreshTask = matchingRefresh === void 0 ? void 0 : requireRefreshTask(matchingRefresh);
2194
+ entry.task = Promise.resolve().then(async () => this.#executeInvalidation(identity, entry, refreshTask)).catch(() => invalidationErrorOutcome(internalFailureError()));
2195
+ entry.task.then(() => {
2196
+ if (this.#invalidations.get(identity)?.token === entry.token) this.#invalidations.delete(identity);
2197
+ });
2198
+ return entry;
2199
+ }
2200
+ async #executeRefresh(identity, entry) {
2201
+ let claim;
2202
+ try {
2203
+ claim = await this.#claimRefresh(identity, entry, entry.workController.signal);
2204
+ } catch (error) {
2205
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2206
+ entry.phase = "settling";
2207
+ return this.#settleClaimUncertainty(identity, entry, sanitizeCoordinatorError(error));
2208
+ }
2209
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2210
+ if (claim.status !== "claimed") {
2211
+ entry.phase = "settling";
2212
+ return this.#settleUnclaimed(identity, entry, claim.status);
2213
+ }
2214
+ const current = claim.snapshot;
2215
+ this.#clearRetiredRevision(identity, current.revision);
2216
+ entry.phase = "refreshing";
2217
+ let replacement;
2218
+ try {
2219
+ replacement = await this.#refreshCredential(identity, current, { signal: entry.workController.signal });
2220
+ } catch (error) {
2221
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2222
+ return this.#handleRefreshFailure(identity, entry, error);
2223
+ }
2224
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2225
+ if (!isObjectLike(replacement)) return this.#retireGeneration(identity, entry, McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure);
2226
+ entry.phase = "committing";
2227
+ let result;
2228
+ try {
2229
+ result = await this.#commitRefresh(identity, entry, replacement, entry.settlementController.signal);
2230
+ } catch (error) {
2231
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2232
+ entry.phase = "settling";
2233
+ return this.#settleCommitUncertainty(identity, entry, McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure, sanitizeCoordinatorError(error));
2234
+ }
2235
+ if (result.status === "applied") return refreshSuccessOutcome(result.snapshot);
2236
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2237
+ entry.phase = "settling";
2238
+ return this.#settleCommitUncertainty(identity, entry, McpClientOAuthCredentialInvalidationReason.ObservedExternal, revisionMismatchError());
2239
+ }
2240
+ async #handleRefreshFailure(identity, entry, error) {
2241
+ let disposition;
2242
+ try {
2243
+ disposition = this.#classifyRefreshFailure(error);
2244
+ } catch {
2245
+ disposition = terminalRefreshFailureDisposition();
2246
+ }
2247
+ const normalized = normalizeRefreshFailureDisposition(disposition);
2248
+ if (normalized.kind === "retry-safe") return this.#releaseRetrySafeClaim(identity, entry);
2249
+ return this.#retireGeneration(identity, entry, normalized.reason);
2250
+ }
2251
+ async #releaseRetrySafeClaim(identity, entry) {
2252
+ entry.phase = "settling";
2253
+ let result;
2254
+ try {
2255
+ result = await this.#releaseRefreshClaim(identity, entry, entry.settlementController.signal);
2256
+ } catch (error) {
2257
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2258
+ return refreshErrorOutcome(sanitizeCoordinatorError(error));
2259
+ }
2260
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2261
+ if (result.status === "released") return refreshErrorOutcome(refreshFailedError());
2262
+ let current;
2263
+ try {
2264
+ current = await this.#load(identity, entry.settlementController.signal);
2265
+ } catch (error) {
2266
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2267
+ return refreshErrorOutcome(sanitizeCoordinatorError(error));
2268
+ }
2269
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2270
+ if (current === void 0) {
2271
+ entry.settlementOwnsInvalidation = true;
2272
+ try {
2273
+ await this.#notifyInvalidated(identity, entry.revision, McpClientOAuthCredentialInvalidationReason.ObservedExternal);
2274
+ } catch (error) {
2275
+ return refreshErrorOutcome(sanitizeCoordinatorError(error));
2276
+ }
2277
+ return refreshErrorOutcome(credentialInvalidatedError());
2278
+ }
2279
+ if (current.revision > entry.revision) return refreshSuccessOutcome(current);
2280
+ if (current.revision === entry.revision) return refreshErrorOutcome(refreshFailedError());
2281
+ return refreshErrorOutcome(invalidStoreResultError());
2282
+ }
2283
+ async #retireGeneration(identity, entry, reason) {
2284
+ entry.phase = "settling";
2285
+ entry.settlementOwnsInvalidation = true;
2286
+ let result;
2287
+ try {
2288
+ result = await this.#invalidateStored(identity, entry.revision, reason, entry.settlementController.signal);
2289
+ } catch (storeError) {
2290
+ return this.#failClosedGeneration(identity, entry.revision, reason, sanitizeCoordinatorError(storeError));
2291
+ }
2292
+ if (result.status === "applied") {
2293
+ this.#clearRetiredRevision(identity, entry.revision);
2294
+ try {
2295
+ await this.#notifyInvalidated(identity, entry.revision, reason);
2296
+ } catch (hookError) {
2297
+ return refreshErrorOutcome(sanitizeCoordinatorError(hookError));
2298
+ }
2299
+ return refreshErrorOutcome(credentialInvalidatedError());
2300
+ }
2301
+ return this.#reloadAfterInvalidationConflict(identity, entry, reason);
2302
+ }
2303
+ async #settleClaimUncertainty(identity, entry, claimFailure) {
2304
+ return this.#settleCommitUncertainty(identity, entry, McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure, claimFailure);
2305
+ }
2306
+ async #settleUnclaimed(identity, entry, status) {
2307
+ let current;
2308
+ try {
2309
+ current = await this.#load(identity, entry.settlementController.signal);
2310
+ } catch (error) {
2311
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2312
+ return refreshErrorOutcome(sanitizeCoordinatorError(error));
2313
+ }
2314
+ if (entry.retirementError !== void 0) return refreshErrorOutcome(entry.retirementError);
2315
+ if (current === void 0) {
2316
+ entry.settlementOwnsInvalidation = true;
2317
+ try {
2318
+ await this.#notifyInvalidated(identity, entry.revision, McpClientOAuthCredentialInvalidationReason.ObservedExternal);
2319
+ } catch (error) {
2320
+ return refreshErrorOutcome(sanitizeCoordinatorError(error));
2321
+ }
2322
+ return refreshErrorOutcome(credentialMissingError());
2323
+ }
2324
+ if (current.revision > entry.revision) {
2325
+ this.#clearRetiredRevision(identity, current.revision);
2326
+ return refreshSuccessOutcome(current);
2327
+ }
2328
+ if (current.revision === entry.revision) {
2329
+ this.#clearRetiredRevision(identity, current.revision);
2330
+ return refreshErrorOutcome(status === "busy" ? revisionInFlightError() : revisionMismatchError());
2331
+ }
2332
+ return refreshErrorOutcome(invalidStoreResultError());
2333
+ }
2334
+ async #settleCommitUncertainty(identity, entry, missingReason, loadFailure) {
2335
+ entry.settlementOwnsInvalidation = true;
2336
+ let winner;
2337
+ try {
2338
+ winner = await this.#load(identity, entry.settlementController.signal);
2339
+ } catch (error) {
2340
+ return this.#failClosedGeneration(identity, entry.revision, McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure, sanitizeCoordinatorError(error));
2341
+ }
2342
+ if (winner === void 0) {
2343
+ this.#clearRetiredRevision(identity, entry.revision);
2344
+ try {
2345
+ await this.#notifyInvalidated(identity, entry.revision, missingReason);
2346
+ } catch (error) {
2347
+ return refreshErrorOutcome(sanitizeCoordinatorError(error));
2348
+ }
2349
+ return refreshErrorOutcome(credentialInvalidatedError());
2350
+ }
2351
+ if (winner.revision > entry.revision) {
2352
+ this.#clearRetiredRevision(identity, winner.revision);
2353
+ return refreshSuccessOutcome(winner);
2354
+ }
2355
+ if (winner.revision === entry.revision) return this.#retireGeneration(identity, entry, McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure);
2356
+ return this.#failClosedGeneration(identity, entry.revision, McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure, loadFailure.code === McpClientOAuthRefreshErrorCode.InvalidStoreResult ? loadFailure : invalidStoreResultError());
2357
+ }
2358
+ async #reloadAfterInvalidationConflict(identity, entry, reason) {
2359
+ let winner;
2360
+ try {
2361
+ winner = await this.#load(identity, entry.settlementController.signal);
2362
+ } catch (error) {
2363
+ return this.#failClosedGeneration(identity, entry.revision, reason, sanitizeCoordinatorError(error));
2364
+ }
2365
+ if (winner === void 0) {
2366
+ this.#clearRetiredRevision(identity, entry.revision);
2367
+ try {
2368
+ await this.#notifyInvalidated(identity, entry.revision, reason);
2369
+ } catch (error) {
2370
+ return refreshErrorOutcome(sanitizeCoordinatorError(error));
2371
+ }
2372
+ return refreshErrorOutcome(credentialInvalidatedError());
2373
+ }
2374
+ if (winner.revision > entry.revision) {
2375
+ this.#clearRetiredRevision(identity, winner.revision);
2376
+ return refreshSuccessOutcome(winner);
2377
+ }
2378
+ if (winner.revision === entry.revision) return this.#failClosedGeneration(identity, entry.revision, reason, credentialInvalidatedError());
2379
+ return this.#failClosedGeneration(identity, entry.revision, reason, invalidStoreResultError());
2380
+ }
2381
+ async #failClosedGeneration(identity, revision, reason, error) {
2382
+ this.#retireRevision(identity, revision);
2383
+ try {
2384
+ await this.#notifyInvalidated(identity, revision, reason);
2385
+ } catch (hookError) {
2386
+ return refreshErrorOutcome(sanitizeCoordinatorError(hookError));
2387
+ }
2388
+ return refreshErrorOutcome(error);
2389
+ }
2390
+ async #executeInvalidation(identity, entry, refreshTask) {
2391
+ let outcome;
2392
+ try {
2393
+ if ((await this.#invalidateStored(identity, entry.revision, entry.reason, entry.controller.signal)).status === "applied") {
2394
+ this.#clearRetiredRevision(identity, entry.revision);
2395
+ await this.#notifyInvalidated(identity, entry.revision, entry.reason);
2396
+ outcome = invalidationSuccessOutcome("invalidated");
2397
+ } else {
2398
+ const current = await this.#load(identity, entry.controller.signal);
2399
+ if (current === void 0) {
2400
+ this.#clearRetiredRevision(identity, entry.revision);
2401
+ await this.#notifyInvalidated(identity, entry.revision, entry.reason);
2402
+ outcome = invalidationSuccessOutcome("missing");
2403
+ } else if (current.revision > entry.revision) {
2404
+ this.#clearRetiredRevision(identity, current.revision);
2405
+ outcome = invalidationSuccessOutcome("superseded");
2406
+ } else if (current.revision === entry.revision) outcome = invalidationSuccessOutcome("conflict");
2407
+ else outcome = invalidationErrorOutcome(invalidStoreResultError());
2408
+ }
2409
+ } catch (error) {
2410
+ outcome = invalidationErrorOutcome(sanitizeCoordinatorError(error));
2411
+ }
2412
+ if (refreshTask !== void 0) await refreshTask;
2413
+ return outcome;
2414
+ }
2415
+ async #load(identity, signal) {
2416
+ let value;
2417
+ try {
2418
+ value = await this.#store.load(identity, storeContext(signal));
2419
+ } catch {
2420
+ throw storeFailedError();
2421
+ }
2422
+ if (value === void 0) return void 0;
2423
+ return normalizeCredentialSnapshot(value);
2424
+ }
2425
+ async #claimRefresh(identity, entry, signal) {
2426
+ let value;
2427
+ try {
2428
+ value = await this.#store.claimRefresh(identity, entry.revision, entry.claimId, storeContext(signal));
2429
+ } catch {
2430
+ throw storeFailedError();
2431
+ }
2432
+ return normalizeRefreshClaimResult(value, entry.revision);
2433
+ }
2434
+ async #commitRefresh(identity, entry, credential, signal) {
2435
+ let value;
2436
+ try {
2437
+ value = await this.#store.commitRefresh(identity, entry.revision, entry.claimId, credential, storeContext(signal));
2438
+ } catch {
2439
+ throw storeFailedError();
2440
+ }
2441
+ return normalizeRefreshCommitResult(value, entry.revision);
2442
+ }
2443
+ async #releaseRefreshClaim(identity, entry, signal) {
2444
+ let value;
2445
+ try {
2446
+ value = await this.#store.releaseRefreshClaim(identity, entry.revision, entry.claimId, storeContext(signal));
2447
+ } catch {
2448
+ throw storeFailedError();
2449
+ }
2450
+ return normalizeRefreshClaimReleaseResult(value);
2451
+ }
2452
+ async #invalidateStored(identity, expectedRevision, reason, signal) {
2453
+ let value;
2454
+ try {
2455
+ value = await this.#store.invalidate(identity, expectedRevision, reason, storeContext(signal));
2456
+ } catch {
2457
+ throw storeFailedError();
2458
+ }
2459
+ return normalizeInvalidationResult(value);
2460
+ }
2461
+ async #notifyInvalidated(identity, revision, reason) {
2462
+ if (this.#onInvalidated === void 0) return;
2463
+ try {
2464
+ await this.#onInvalidated(identity, Object.freeze({
2465
+ revision,
2466
+ reason
2467
+ }));
2468
+ } catch {
2469
+ throw invalidationHookFailedError();
2470
+ }
2471
+ }
2472
+ #retireRefresh(entry) {
2473
+ if (entry.retirementError !== void 0) return;
2474
+ entry.retirementError = credentialInvalidatedError();
2475
+ entry.retirementController.abort(generationInvalidatedAbortReason());
2476
+ if (entry.phase === "loading" || entry.phase === "refreshing") entry.workController.abort(generationInvalidatedAbortReason());
2477
+ }
2478
+ async #waitForRefresh(entry, signal) {
2479
+ entry.waiterCount += 1;
2480
+ const caller = signal === void 0 ? void 0 : waitForAbort(signal, CALLER_ABORTED);
2481
+ const retired = waitForAbort(entry.retirementController.signal, GENERATION_RETIRED);
2482
+ try {
2483
+ const result = await Promise.race([
2484
+ requireRefreshTask(entry),
2485
+ retired.promise,
2486
+ ...caller === void 0 ? [] : [caller.promise]
2487
+ ]);
2488
+ if (result === CALLER_ABORTED) throw callerAbortedError();
2489
+ if (result === GENERATION_RETIRED) throw entry.retirementError ?? credentialInvalidatedError();
2490
+ if (result.status === "error") throw result.error;
2491
+ return result.snapshot;
2492
+ } finally {
2493
+ entry.waiterCount -= 1;
2494
+ caller?.detach();
2495
+ retired.detach();
2496
+ }
2497
+ }
2498
+ async #waitForInvalidation(entry, signal) {
2499
+ entry.waiterCount += 1;
2500
+ const caller = signal === void 0 ? void 0 : waitForAbort(signal, CALLER_ABORTED);
2501
+ try {
2502
+ const result = await Promise.race([requireInvalidationTask(entry), ...caller === void 0 ? [] : [caller.promise]]);
2503
+ if (result === CALLER_ABORTED) throw callerAbortedError();
2504
+ if (result.status === "error") throw result.error;
2505
+ return result.result;
2506
+ } finally {
2507
+ entry.waiterCount -= 1;
2508
+ caller?.detach();
2509
+ }
2510
+ }
2511
+ async #waitForSettlingInvalidation(entry, signal) {
2512
+ entry.waiterCount += 1;
2513
+ const caller = signal === void 0 ? void 0 : waitForAbort(signal, CALLER_ABORTED);
2514
+ try {
2515
+ const outcome = await Promise.race([requireRefreshTask(entry), ...caller === void 0 ? [] : [caller.promise]]);
2516
+ if (outcome === CALLER_ABORTED) throw callerAbortedError();
2517
+ if (outcome.status === "success") return createInvalidationResult("superseded");
2518
+ if (outcome.error.code === McpClientOAuthRefreshErrorCode.CredentialInvalidated) return createInvalidationResult("invalidated");
2519
+ if (outcome.error.code === McpClientOAuthRefreshErrorCode.CredentialMissing) return createInvalidationResult("missing");
2520
+ if (outcome.error.code === McpClientOAuthRefreshErrorCode.RevisionMismatch) return createInvalidationResult("conflict");
2521
+ throw outcome.error;
2522
+ } finally {
2523
+ entry.waiterCount -= 1;
2524
+ caller?.detach();
2525
+ }
2526
+ }
2527
+ #assertOpen() {
2528
+ if (this.#closed) throw coordinatorClosedError();
2529
+ }
2530
+ #assertCapacity(identity) {
2531
+ if (this.#refreshes.has(identity) || this.#invalidations.has(identity) || this.#retiredRevisions.has(identity)) return;
2532
+ if (this.#inFlightKeyCount() >= this.#maxInFlightKeys) throw capacityExceededError();
2533
+ }
2534
+ #inFlightKeyCount() {
2535
+ const identities = new Set(this.#refreshes.keys());
2536
+ for (const identity of this.#invalidations.keys()) identities.add(identity);
2537
+ for (const identity of this.#retiredRevisions.keys()) identities.add(identity);
2538
+ return identities.size;
2539
+ }
2540
+ #assertGenerationUsable(identity, revision) {
2541
+ const retiredRevision = this.#retiredRevisions.get(identity);
2542
+ if (retiredRevision === void 0) return;
2543
+ if (revision <= retiredRevision) throw credentialInvalidatedError();
2544
+ }
2545
+ #retireRevision(identity, revision) {
2546
+ const current = this.#retiredRevisions.get(identity);
2547
+ if (current === void 0 || revision > current) this.#retiredRevisions.set(identity, revision);
2548
+ }
2549
+ #clearRetiredRevision(identity, authoritativeRevision) {
2550
+ const current = this.#retiredRevisions.get(identity);
2551
+ if (current !== void 0 && current <= authoritativeRevision) this.#retiredRevisions.delete(identity);
2552
+ }
2553
+ };
2554
+ /**
2555
+ * Fails terminally by default. Only internally branded strict-protocol errors with a definitive
2556
+ * pre-dispatch outcome are retry-safe; public constructor/code lookalikes are not.
2557
+ */
2558
+ function classifyMcpClientOAuthRefreshFailure(error) {
2559
+ if (!isInternalMcpClientOAuthProtocolError(error)) return terminalRefreshFailureDisposition();
2560
+ switch (readStringProperty(error, "code")) {
2561
+ case McpClientOAuthProtocolErrorCode.InvalidGrant: return terminalRefreshFailureDisposition(McpClientOAuthCredentialInvalidationReason.InvalidGrant);
2562
+ case McpClientOAuthProtocolErrorCode.RefreshOutcomeUnknown:
2563
+ case McpClientOAuthProtocolErrorCode.InvalidClient: return terminalRefreshFailureDisposition();
2564
+ case McpClientOAuthProtocolErrorCode.InvalidOptions:
2565
+ case McpClientOAuthProtocolErrorCode.EndpointRejected:
2566
+ case McpClientOAuthProtocolErrorCode.DiscoveryFailed:
2567
+ case McpClientOAuthProtocolErrorCode.AuthorityInvalid:
2568
+ case McpClientOAuthProtocolErrorCode.ClientUnsupported:
2569
+ case McpClientOAuthProtocolErrorCode.TransactionInvalid:
2570
+ case McpClientOAuthProtocolErrorCode.AuthorizationDenied:
2571
+ case McpClientOAuthProtocolErrorCode.AuthorizationFailed:
2572
+ case McpClientOAuthProtocolErrorCode.TokenExchangeFailed:
2573
+ case McpClientOAuthProtocolErrorCode.TokenRefreshFailed: return retrySafeRefreshFailureDisposition();
2574
+ default: return terminalRefreshFailureDisposition();
2575
+ }
2576
+ }
2577
+ function normalizeCredentialSnapshot(value) {
2578
+ try {
2579
+ if (!isObjectLike(value)) throw invalidStoreResultError();
2580
+ const { credential, revision } = value;
2581
+ if (!isMcpClientOAuthCredentialRevision(revision) || !isObjectLike(credential)) throw invalidStoreResultError();
2582
+ return createMcpClientOAuthCredentialSnapshot(revision, credential);
2583
+ } catch (error) {
2584
+ throw sanitizeInvalidStoreResult(error);
2585
+ }
2586
+ }
2587
+ function normalizeRefreshClaimResult(value, expectedRevision) {
2588
+ try {
2589
+ if (!isObjectLike(value)) throw invalidStoreResultError();
2590
+ const { status } = value;
2591
+ if (status === "busy" || status === "conflict") return Object.freeze({ status });
2592
+ if (status !== "claimed") throw invalidStoreResultError();
2593
+ const snapshot = normalizeCredentialSnapshot(value.snapshot);
2594
+ if (snapshot.revision !== expectedRevision) throw invalidStoreResultError();
2595
+ return Object.freeze({
2596
+ status,
2597
+ snapshot
2598
+ });
2599
+ } catch (error) {
2600
+ throw sanitizeInvalidStoreResult(error);
2601
+ }
2602
+ }
2603
+ function normalizeRefreshCommitResult(value, expectedRevision) {
2604
+ try {
2605
+ if (!isObjectLike(value)) throw invalidStoreResultError();
2606
+ const { status } = value;
2607
+ if (status === "conflict") return Object.freeze({ status });
2608
+ if (status !== "applied") throw invalidStoreResultError();
2609
+ const snapshot = normalizeCredentialSnapshot(value.snapshot);
2610
+ if (snapshot.revision !== nextMcpClientOAuthCredentialRevision(expectedRevision)) throw invalidStoreResultError();
2611
+ return Object.freeze({
2612
+ status,
2613
+ snapshot
2614
+ });
2615
+ } catch (error) {
2616
+ throw sanitizeInvalidStoreResult(error);
2617
+ }
2618
+ }
2619
+ function normalizeRefreshClaimReleaseResult(value) {
2620
+ try {
2621
+ if (!isObjectLike(value)) throw invalidStoreResultError();
2622
+ const { status } = value;
2623
+ if (status !== "released" && status !== "conflict") throw invalidStoreResultError();
2624
+ return Object.freeze({ status });
2625
+ } catch (error) {
2626
+ throw sanitizeInvalidStoreResult(error);
2627
+ }
2628
+ }
2629
+ function normalizeInvalidationResult(value) {
2630
+ try {
2631
+ if (!isObjectLike(value)) throw invalidStoreResultError();
2632
+ const { status } = value;
2633
+ if (status !== "applied" && status !== "conflict") throw invalidStoreResultError();
2634
+ return Object.freeze({ status });
2635
+ } catch (error) {
2636
+ throw sanitizeInvalidStoreResult(error);
2637
+ }
2638
+ }
2639
+ function refreshSuccessOutcome(snapshot) {
2640
+ return Object.freeze({
2641
+ status: "success",
2642
+ snapshot
2643
+ });
2644
+ }
2645
+ function refreshErrorOutcome(error) {
2646
+ return Object.freeze({
2647
+ status: "error",
2648
+ error
2649
+ });
2650
+ }
2651
+ function invalidationSuccessOutcome(status) {
2652
+ return Object.freeze({
2653
+ status: "success",
2654
+ result: createInvalidationResult(status)
2655
+ });
2656
+ }
2657
+ function createInvalidationResult(status) {
2658
+ return Object.freeze({ status });
2659
+ }
2660
+ function invalidationErrorOutcome(error) {
2661
+ return Object.freeze({
2662
+ status: "error",
2663
+ error
2664
+ });
2665
+ }
2666
+ function requireRefreshTask(entry) {
2667
+ if (entry.task === void 0) throw internalFailureError();
2668
+ return entry.task;
2669
+ }
2670
+ function requireInvalidationTask(entry) {
2671
+ if (entry.task === void 0) throw internalFailureError();
2672
+ return entry.task;
2673
+ }
2674
+ function storeContext(signal) {
2675
+ return Object.freeze({ signal });
2676
+ }
2677
+ function waitForAbort(signal, result) {
2678
+ if (signal.aborted) return {
2679
+ promise: Promise.resolve(result),
2680
+ detach: noop
2681
+ };
2682
+ let resolveAbort;
2683
+ const promise = new Promise((resolve) => {
2684
+ resolveAbort = resolve;
2685
+ });
2686
+ const onAbort = () => resolveAbort?.(result);
2687
+ signal.addEventListener("abort", onAbort, { once: true });
2688
+ return {
2689
+ promise,
2690
+ detach() {
2691
+ signal.removeEventListener("abort", onAbort);
2692
+ }
2693
+ };
2694
+ }
2695
+ function throwIfCallerAborted(signal) {
2696
+ if (signal?.aborted === true) throw callerAbortedError();
2697
+ }
2698
+ function assertRevision(value) {
2699
+ if (!isMcpClientOAuthCredentialRevision(value)) throw invalidOptionsError();
2700
+ }
2701
+ function createRefreshClaimId() {
2702
+ try {
2703
+ return Object.freeze({ value: randomUUID() });
2704
+ } catch {
2705
+ throw internalFailureError();
2706
+ }
2707
+ }
2708
+ function retrySafeRefreshFailureDisposition() {
2709
+ return Object.freeze({ kind: "retry-safe" });
2710
+ }
2711
+ function terminalRefreshFailureDisposition(reason = McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure) {
2712
+ return Object.freeze({
2713
+ kind: "terminal",
2714
+ reason
2715
+ });
2716
+ }
2717
+ function normalizeRefreshFailureDisposition(value) {
2718
+ try {
2719
+ if (!isObjectLike(value)) return terminalRefreshFailureDisposition();
2720
+ const { kind } = value;
2721
+ if (kind === "retry-safe") return retrySafeRefreshFailureDisposition();
2722
+ if (kind !== "terminal") return terminalRefreshFailureDisposition();
2723
+ const { reason } = value;
2724
+ return isTerminalRefreshReason(reason) ? terminalRefreshFailureDisposition(reason) : terminalRefreshFailureDisposition();
2725
+ } catch {
2726
+ return terminalRefreshFailureDisposition();
2727
+ }
2728
+ }
2729
+ function assertInvalidationReason(value) {
2730
+ if (value !== McpClientOAuthCredentialInvalidationReason.Explicit && value !== McpClientOAuthCredentialInvalidationReason.ObservedExternal && !isTerminalRefreshReason(value)) throw invalidOptionsError();
2731
+ }
2732
+ function isTerminalRefreshReason(value) {
2733
+ return value === McpClientOAuthCredentialInvalidationReason.InvalidGrant || value === McpClientOAuthCredentialInvalidationReason.TerminalRefreshFailure;
2734
+ }
2735
+ function isCredentialStore(value) {
2736
+ if (!isObjectLike(value)) return false;
2737
+ try {
2738
+ return typeof Reflect.get(value, "load") === "function" && typeof Reflect.get(value, "claimRefresh") === "function" && typeof Reflect.get(value, "commitRefresh") === "function" && typeof Reflect.get(value, "releaseRefreshClaim") === "function" && typeof Reflect.get(value, "compareAndSwap") === "function" && typeof Reflect.get(value, "invalidate") === "function";
2739
+ } catch {
2740
+ return false;
2741
+ }
2742
+ }
2743
+ function isObjectLike(value) {
2744
+ return value !== null && (typeof value === "object" || typeof value === "function");
2745
+ }
2746
+ function readStringProperty(value, property) {
2747
+ if (!isObjectLike(value)) return void 0;
2748
+ try {
2749
+ const result = Reflect.get(value, property);
2750
+ return typeof result === "string" ? result : void 0;
2751
+ } catch {
2752
+ return;
2753
+ }
2754
+ }
2755
+ function sanitizeCoordinatorError(error) {
2756
+ try {
2757
+ if (!(error instanceof McpClientOAuthRefreshError)) return internalFailureError();
2758
+ } catch {
2759
+ return internalFailureError();
2760
+ }
2761
+ switch (readStringProperty(error, "code")) {
2762
+ case McpClientOAuthRefreshErrorCode.InvalidOptions: return invalidOptionsError();
2763
+ case McpClientOAuthRefreshErrorCode.Closed: return coordinatorClosedError();
2764
+ case McpClientOAuthRefreshErrorCode.CapacityExceeded: return capacityExceededError();
2765
+ case McpClientOAuthRefreshErrorCode.RevisionInFlight: return revisionInFlightError();
2766
+ case McpClientOAuthRefreshErrorCode.CredentialMissing: return credentialMissingError();
2767
+ case McpClientOAuthRefreshErrorCode.CredentialInvalidated: return credentialInvalidatedError();
2768
+ case McpClientOAuthRefreshErrorCode.RevisionMismatch: return revisionMismatchError();
2769
+ case McpClientOAuthRefreshErrorCode.RefreshFailed: return refreshFailedError();
2770
+ case McpClientOAuthRefreshErrorCode.StoreFailed: return storeFailedError();
2771
+ case McpClientOAuthRefreshErrorCode.InvalidStoreResult: return invalidStoreResultError();
2772
+ case McpClientOAuthRefreshErrorCode.InvalidationHookFailed: return invalidationHookFailedError();
2773
+ case McpClientOAuthRefreshErrorCode.CallerAborted: return callerAbortedError();
2774
+ case McpClientOAuthRefreshErrorCode.InternalFailure:
2775
+ default: return internalFailureError();
2776
+ }
2777
+ }
2778
+ function sanitizeInvalidStoreResult(_error) {
2779
+ return invalidStoreResultError();
2780
+ }
2781
+ function invalidOptionsError() {
2782
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.InvalidOptions, "The OAuth refresh coordinator options are invalid.");
2783
+ }
2784
+ function coordinatorClosedError() {
2785
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.Closed, "The OAuth refresh coordinator is closed and cannot accept new work.");
2786
+ }
2787
+ function capacityExceededError() {
2788
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.CapacityExceeded, "The OAuth refresh coordinator is at capacity.");
2789
+ }
2790
+ function revisionInFlightError() {
2791
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.RevisionInFlight, "A different OAuth credential revision already has accepted work.");
2792
+ }
2793
+ function credentialMissingError() {
2794
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.CredentialMissing, "The OAuth credential generation is unavailable.");
2795
+ }
2796
+ function credentialInvalidatedError() {
2797
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.CredentialInvalidated, "The OAuth credential generation is no longer usable.");
2798
+ }
2799
+ function revisionMismatchError() {
2800
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.RevisionMismatch, "The OAuth credential revision changed before refresh could be committed.");
2801
+ }
2802
+ function refreshFailedError() {
2803
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.RefreshFailed, "The OAuth credential refresh failed.");
2804
+ }
2805
+ function storeFailedError() {
2806
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.StoreFailed, "The OAuth credential store operation failed.");
2807
+ }
2808
+ function invalidStoreResultError() {
2809
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.InvalidStoreResult, "The OAuth credential store returned an invalid result.");
2810
+ }
2811
+ function invalidationHookFailedError() {
2812
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.InvalidationHookFailed, "The OAuth credential invalidation hook failed.");
2813
+ }
2814
+ function callerAbortedError() {
2815
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.CallerAborted, "The caller stopped waiting for OAuth credential work.");
2816
+ }
2817
+ function internalFailureError() {
2818
+ return new McpClientOAuthRefreshError(McpClientOAuthRefreshErrorCode.InternalFailure, "The OAuth refresh coordinator could not complete the operation.");
2819
+ }
2820
+ function generationInvalidatedAbortReason() {
2821
+ return new DOMException("The OAuth credential generation was invalidated.", "AbortError");
2822
+ }
2823
+ function noop() {}
2824
+ //#endregion
2825
+ //#region src/oauth/provisioning.ts
2826
+ /**
2827
+ * Pure provisioning decision over captured protocol facts and explicit host preferences.
2828
+ * Performs no I/O, registration, decryption, authorization or persistence. A registration plan
2829
+ * is only a capability result; hosts must obtain consent and fence dispatch independently.
2830
+ */
2831
+ function planMcpClientOAuthProvisioning(input) {
2832
+ const discovery = parseMcpClientOAuthBootstrapDiscoveryResult(input.discovery);
2833
+ if (discovery.kind !== "ready") throw invalidOptions$1();
2834
+ const applicationType = getMcpClientOAuthApplicationType(input.redirectUri);
2835
+ if (applicationType === void 0) throw invalidOptions$1();
2836
+ const strategies = [...input.strategies];
2837
+ if (strategies.length > 3 || new Set(strategies).size !== strategies.length || strategies.some((value) => value !== "reuse" && value !== "client_id_metadata" && value !== "dynamic_registration") || input.allowRegistrationAfterScopeExpansion !== void 0 && typeof input.allowRegistrationAfterScopeExpansion !== "boolean") throw invalidOptions$1();
2838
+ const clientIdMetadataUrl = input.clientIdMetadataUrl;
2839
+ if (clientIdMetadataUrl !== void 0 && getMcpClientOAuthApplicationType(clientIdMetadataUrl) !== "web") throw invalidOptions$1();
2840
+ const existing = input.existingClient === void 0 ? void 0 : captureExistingClient(input.existingClient);
2841
+ const status = existingClientStatus(existing, discovery, input.redirectUri, clientIdMetadataUrl);
2842
+ const scopes = Object.freeze([...discovery.scopes ?? []]);
2843
+ const result = (kind, authorizationScopes = scopes) => Object.freeze({
2844
+ kind,
2845
+ existingClientStatus: status,
2846
+ authorizationScopes
2847
+ });
2848
+ const publicClient = discovery.candidate.authority.tokenEndpointAuthMethodsSupported.includes("none");
2849
+ for (const strategy of strategies) {
2850
+ if (strategy === "reuse" && status === "reusable" && existing !== void 0) return result("reuse", existing.provisioningMethod === "manual" ? existing.scopes : scopes);
2851
+ if (strategy === "client_id_metadata" && publicClient && applicationType === "web" && discovery.candidate.clientIdMetadataDocumentSupported && clientIdMetadataUrl !== void 0) return result("client_id_metadata");
2852
+ if (strategy === "dynamic_registration" && publicClient && discovery.candidate.legacyDynamicRegistrationEndpoint !== void 0) {
2853
+ if (status === "scope_insufficient" && input.allowRegistrationAfterScopeExpansion !== true) return result("registration_scope_insufficient");
2854
+ return result("dynamic_registration");
2855
+ }
2856
+ }
2857
+ return result(status === "scope_insufficient" ? "registration_scope_insufficient" : "manual_client_required");
2858
+ }
2859
+ /** Canonical HTTPS web callback or RFC 8252 loopback HTTP native callback; no network admission. */
2860
+ function getMcpClientOAuthApplicationType(value) {
2861
+ if (typeof value !== "string" || value.length === 0 || value.length > 4096) return void 0;
2862
+ try {
2863
+ const url = new URL(value);
2864
+ if (url.href !== value || url.username !== "" || url.password !== "" || url.hash !== "") return void 0;
2865
+ if (url.protocol === "https:") return "web";
2866
+ if (url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/u.test(url.hostname))) return "native";
2867
+ } catch {}
2868
+ }
2869
+ /** Empty or absent discovery asks for no scopes; it never expands a registered allowance. */
2870
+ function mcpClientOAuthScopesCover(available, requested = []) {
2871
+ validateScopes(available);
2872
+ validateScopes(requested);
2873
+ const allowed = new Set(available);
2874
+ return requested.every((scope) => allowed.has(scope));
2875
+ }
2876
+ function existingClientStatus(existing, ready, redirectUri, metadataUrl) {
2877
+ if (existing === void 0) return "absent";
2878
+ if (existing.serverUrl !== ready.resource.serverUrl || existing.issuer !== ready.candidate.authority.issuer || existing.resource !== ready.resource.resource || existing.provisioningMethod !== "manual" && existing.redirectUri !== redirectUri || existing.provisioningMethod === "client_id_metadata" && (!ready.candidate.clientIdMetadataDocumentSupported || metadataUrl === void 0 || existing.clientId !== metadataUrl) || !ready.candidate.authority.tokenEndpointAuthMethodsSupported.includes(existing.authenticationMethod) || existing.authenticationMethod !== "none" && !existing.authenticationAvailable) return "incompatible";
2879
+ return existing.provisioningMethod === "dynamic_registration" && !mcpClientOAuthScopesCover(existing.scopes, ready.scopes) ? "scope_insufficient" : "reusable";
2880
+ }
2881
+ function captureExistingClient(value) {
2882
+ return parseOAuthSnapshot(value, {}, (record) => {
2883
+ assertOAuthSnapshotKeys(record, [
2884
+ "clientId",
2885
+ "serverUrl",
2886
+ "issuer",
2887
+ "resource",
2888
+ "provisioningMethod",
2889
+ "authenticationMethod",
2890
+ "authenticationAvailable",
2891
+ "redirectUri",
2892
+ "scopes"
2893
+ ]);
2894
+ const method = record.provisioningMethod;
2895
+ const authentication = record.authenticationMethod;
2896
+ if (method !== "manual" && method !== "client_id_metadata" && method !== "dynamic_registration") throw invalidOptions$1();
2897
+ if (authentication !== "none" && authentication !== "client_secret_basic" && authentication !== "client_secret_post" && authentication !== "private_key_jwt") throw invalidOptions$1();
2898
+ const scopes = oauthSnapshotStrings(record.scopes, 128);
2899
+ validateScopes(scopes);
2900
+ return Object.freeze({
2901
+ clientId: oauthSnapshotString(record.clientId, 2048),
2902
+ serverUrl: oauthSnapshotString(record.serverUrl, 4096),
2903
+ issuer: oauthSnapshotString(record.issuer, 4096),
2904
+ resource: oauthSnapshotString(record.resource, 4096),
2905
+ provisioningMethod: method,
2906
+ authenticationMethod: authentication,
2907
+ authenticationAvailable: oauthSnapshotBoolean(record.authenticationAvailable),
2908
+ ...record.redirectUri === void 0 ? {} : { redirectUri: oauthSnapshotString(record.redirectUri, 4096) },
2909
+ scopes: Object.freeze([...scopes])
2910
+ });
2911
+ });
2912
+ }
2913
+ function validateScopes(value) {
2914
+ if (!Array.isArray(value) || value.length > 128 || !value.every(isMcpClientOAuthScopeToken) || value.join(" ").length > 4096) throw invalidOptions$1();
2915
+ }
2916
+ function invalidOptions$1() {
2917
+ return /* @__PURE__ */ new TypeError("The MCP OAuth provisioning options are invalid.");
2918
+ }
2919
+ //#endregion
2920
+ //#region src/oauth/challenge-probe.ts
2921
+ /** One non-credentialed GET. Pass its bounded raw header to bootstrap.discover({ wwwAuthenticate }). */
2922
+ async function probeMcpClientOAuthChallenge(input) {
2923
+ const { fetch, signal, serverUrl } = input;
2924
+ if (typeof fetch !== "function" || typeof serverUrl !== "string" || serverUrl.length > 4096) throw invalidOptions();
2925
+ let endpoint;
2926
+ try {
2927
+ endpoint = new URL(serverUrl);
2928
+ } catch {
2929
+ throw invalidOptions();
2930
+ }
2931
+ if (endpoint.protocol !== "https:" && endpoint.protocol !== "http:" || endpoint.username !== "" || endpoint.password !== "" || endpoint.hash !== "") throw invalidOptions();
2932
+ signal.throwIfAborted();
2933
+ let response;
2934
+ try {
2935
+ response = await fetch(serverUrl, {
2936
+ cache: "no-store",
2937
+ credentials: "omit",
2938
+ headers: {
2939
+ Accept: "text/event-stream",
2940
+ "Cache-Control": "no-store"
2941
+ },
2942
+ method: "GET",
2943
+ redirect: "error",
2944
+ signal
2945
+ });
2946
+ } catch {
2947
+ signal.throwIfAborted();
2948
+ throw new McpClientOAuthBootstrapError(McpClientOAuthBootstrapErrorCode.DiscoveryFailed);
2949
+ }
2950
+ try {
2951
+ signal.throwIfAborted();
2952
+ const challenge = response.status === 401 ? response.headers.get("www-authenticate") ?? void 0 : void 0;
2953
+ if (challenge !== void 0 && challenge.length > 8192) throw invalidOptions();
2954
+ return challenge;
2955
+ } finally {
2956
+ try {
2957
+ await response.body?.cancel();
2958
+ } catch {}
2959
+ }
2960
+ }
2961
+ function invalidOptions() {
2962
+ return new McpClientOAuthBootstrapError(McpClientOAuthBootstrapErrorCode.InvalidOptions);
2963
+ }
2964
+ //#endregion
2965
+ //#region src/oauth/authentication-detection.ts
2966
+ /**
2967
+ * Passive Streamable HTTP detection using the SDK's modern discovery / legacy handshake.
2968
+ * No credentials, registration, browser navigation, token requests, or feature invocation.
2969
+ * Never infer anonymous access from a status code or missing OAuth metadata. HTTP+SSE (2024)
2970
+ * endpoints are not followed. The caller must always release its admitted network lease.
2971
+ */
2972
+ async function detectMcpClientAuthentication(input) {
2973
+ if (typeof input !== "object" || input === null || !(input.signal instanceof AbortSignal)) return indeterminate("invalid-options");
2974
+ input.signal.throwIfAborted();
2975
+ const timeoutMs = input.timeoutMs ?? 1e4;
2976
+ const maxResponseBytes = input.maxResponseBytes ?? 262144;
2977
+ let endpoint;
2978
+ try {
2979
+ endpoint = new URL(input.serverUrl);
2980
+ if (typeof input.serverUrl !== "string" || input.serverUrl.length > 4096 || !["http:", "https:"].includes(endpoint.protocol) || endpoint.username !== "" || endpoint.password !== "" || endpoint.hash !== "" || typeof input.fetch !== "function" || input.discoveryFetch !== void 0 && typeof input.discoveryFetch !== "function" || typeof input.endpointPolicy !== "function" || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e4 || !Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || maxResponseBytes > 1048576) return indeterminate("invalid-options");
2981
+ } catch {
2982
+ return indeterminate("invalid-options");
2983
+ }
2984
+ const scope = new DetectionScope(input, maxResponseBytes);
2985
+ const timer = setTimeout(() => scope.stop("timeout"), timeoutMs);
2986
+ let denied;
2987
+ let accepting = true;
2988
+ const pendingGets = /* @__PURE__ */ new Set();
2989
+ const transportFetch = (url, init) => {
2990
+ const request = (async () => {
2991
+ if (!accepting || denied !== void 0) throw new DetectionFailure("http-error");
2992
+ if (String(url) !== endpoint.href) throw new DetectionFailure("endpoint-rejected");
2993
+ const method = init?.method;
2994
+ const rpcMethod = method === "POST" ? outgoingMethod(init?.body) : void 0;
2995
+ if (method !== "GET" && (method !== "POST" || ![
2996
+ "server/discover",
2997
+ "initialize",
2998
+ "notifications/initialized"
2999
+ ].includes(rpcMethod ?? ""))) {
3000
+ scope.stop("invalid-response");
3001
+ throw new DetectionFailure("invalid-response");
3002
+ }
3003
+ const response = await scope.fetch(url, init);
3004
+ if (response.status === 401 || response.status === 403) {
3005
+ const header = response.headers.get("www-authenticate");
3006
+ denied = {
3007
+ status: response.status,
3008
+ ...header === null ? {} : { header }
3009
+ };
3010
+ scope.cancel(response);
3011
+ throw new DetectionFailure("http-error");
3012
+ }
3013
+ if (method === "GET") {
3014
+ scope.cancel(response);
3015
+ if (!response.ok && response.status !== 405) {
3016
+ scope.stop("http-error");
3017
+ throw new DetectionFailure("http-error");
3018
+ }
3019
+ return new Response(null, {
3020
+ status: response.status,
3021
+ headers: response.headers
3022
+ });
3023
+ }
3024
+ if (!response.ok && ![
3025
+ 400,
3026
+ 404,
3027
+ 405
3028
+ ].includes(response.status)) {
3029
+ scope.cancel(response);
3030
+ scope.stop("http-error");
3031
+ throw new DetectionFailure("http-error");
3032
+ }
3033
+ if (rpcMethod === "notifications/initialized" && response.ok) {
3034
+ scope.cancel(response);
3035
+ if (response.status !== 202) {
3036
+ scope.stop("invalid-response");
3037
+ throw new DetectionFailure("invalid-response");
3038
+ }
3039
+ return new Response(null, {
3040
+ status: 202,
3041
+ headers: response.headers
3042
+ });
3043
+ }
3044
+ return response;
3045
+ })();
3046
+ if (init?.method === "GET") pendingGets.add(request);
3047
+ return request;
3048
+ };
3049
+ const transport = new StreamableHTTPClientTransport(endpoint, {
3050
+ fetch: transportFetch,
3051
+ reconnectionOptions: {
3052
+ maxRetries: 0,
3053
+ initialReconnectionDelay: 1e3,
3054
+ maxReconnectionDelay: 1e3,
3055
+ reconnectionDelayGrowFactor: 1
3056
+ }
3057
+ });
3058
+ const client = new Client({
3059
+ name: "nest-mcp-authentication-detection",
3060
+ version: "1"
3061
+ }, {
3062
+ capabilities: {},
3063
+ versionNegotiation: {
3064
+ mode: "auto",
3065
+ probe: {
3066
+ timeoutMs,
3067
+ maxRetries: 0
3068
+ }
3069
+ }
3070
+ });
3071
+ let result;
3072
+ try {
3073
+ try {
3074
+ await withSignal(client.connect(transport, {
3075
+ signal: scope.signal,
3076
+ timeout: timeoutMs
3077
+ }), scope.signal);
3078
+ await withSignal(Promise.all(pendingGets), scope.signal);
3079
+ if (denied !== void 0) throw new DetectionFailure("http-error");
3080
+ const protocolVersion = client.getNegotiatedProtocolVersion();
3081
+ const protocolEra = client.getProtocolEra();
3082
+ if (protocolVersion === void 0 || protocolEra === void 0) throw new DetectionFailure("invalid-response");
3083
+ const serverInfo = boundedServerInfo(client.getServerVersion());
3084
+ result = Object.freeze({
3085
+ kind: "anonymous",
3086
+ protocolVersion,
3087
+ protocolEra,
3088
+ ...serverInfo === void 0 ? {} : { serverInfo }
3089
+ });
3090
+ } catch (error) {
3091
+ if (denied === void 0 || scope.signal.aborted) throw error;
3092
+ const { status, header } = denied;
3093
+ let bearer;
3094
+ try {
3095
+ bearer = header === void 0 ? void 0 : parseMcpClientOAuthBootstrapChallenge(header);
3096
+ } catch {
3097
+ throw new DetectionFailure("unsupported-authentication");
3098
+ }
3099
+ if (header !== void 0 && bearer === void 0 || status === 403 && bearer === void 0) throw new DetectionFailure("unsupported-authentication");
3100
+ const discovery = await withSignal(new McpClientOAuthBootstrap({
3101
+ fetch: scope.discoveryFetch,
3102
+ endpointPolicy: input.endpointPolicy
3103
+ }).discover({
3104
+ serverUrl: endpoint.href,
3105
+ ...header === void 0 ? {} : { wwwAuthenticate: header },
3106
+ signal: scope.signal
3107
+ }), scope.signal);
3108
+ result = Object.freeze({
3109
+ kind: "oauth-required",
3110
+ discovery
3111
+ });
3112
+ }
3113
+ } catch (error) {
3114
+ result = indeterminate(scope.failure ?? (error instanceof DetectionFailure ? error.reason : error instanceof McpClientOAuthBootstrapError ? "oauth-discovery-failed" : "invalid-response"), denied?.status ?? scope.httpStatus, error instanceof McpClientOAuthBootstrapError ? error.code : void 0);
3115
+ } finally {
3116
+ accepting = false;
3117
+ clearTimeout(timer);
3118
+ }
3119
+ const cleaned = await scope.close(client, transport, endpoint);
3120
+ input.signal.throwIfAborted();
3121
+ if (!cleaned && result.kind === "anonymous") return indeterminate("cleanup-failed");
3122
+ return result;
3123
+ }
3124
+ var DetectionFailure = class extends Error {
3125
+ reason;
3126
+ constructor(reason) {
3127
+ super("MCP authentication detection did not complete.");
3128
+ this.reason = reason;
3129
+ }
3130
+ };
3131
+ var DetectionScope = class {
3132
+ input;
3133
+ maximum;
3134
+ #controller = new AbortController();
3135
+ signal;
3136
+ #cancellations = /* @__PURE__ */ new Set();
3137
+ #readers = /* @__PURE__ */ new Map();
3138
+ #bytes = 0;
3139
+ #requests = 0;
3140
+ failure;
3141
+ httpStatus;
3142
+ constructor(input, maximum) {
3143
+ this.input = input;
3144
+ this.maximum = maximum;
3145
+ this.signal = AbortSignal.any([input.signal, this.#controller.signal]);
3146
+ }
3147
+ stop(reason) {
3148
+ this.failure ??= reason;
3149
+ this.#controller.abort(new DetectionFailure(reason));
3150
+ }
3151
+ fetch = (url, init) => this.#fetch(this.input.fetch, url, init);
3152
+ discoveryFetch = (url, init) => this.#fetch(this.input.discoveryFetch ?? this.input.fetch, url, init);
3153
+ async #fetch(fetch, url, init) {
3154
+ this.signal.throwIfAborted();
3155
+ if (++this.#requests > 12) {
3156
+ this.stop("request-limit");
3157
+ throw new DetectionFailure("request-limit");
3158
+ }
3159
+ const signal = AbortSignal.any([this.signal, ...init?.signal == null ? [] : [init.signal]]);
3160
+ const pending = Promise.resolve().then(() => {
3161
+ signal.throwIfAborted();
3162
+ return fetch(url, credentialFreeInit(init, signal));
3163
+ });
3164
+ const request = Promise.resolve(pending).then((response) => {
3165
+ if (signal.aborted) {
3166
+ this.#cancelBody(response);
3167
+ signal.throwIfAborted();
3168
+ }
3169
+ return response;
3170
+ });
3171
+ let response;
3172
+ try {
3173
+ response = await withSignal(request, signal);
3174
+ } catch {
3175
+ signal.throwIfAborted();
3176
+ this.stop("network-error");
3177
+ throw new DetectionFailure("network-error");
3178
+ }
3179
+ if (response.redirected || response.status >= 300 && response.status < 400 || response.url !== "" && response.url !== String(url)) {
3180
+ this.#cancelBody(response);
3181
+ this.stop("endpoint-rejected");
3182
+ throw new DetectionFailure("endpoint-rejected");
3183
+ }
3184
+ this.httpStatus = response.status;
3185
+ if ((response.headers.get("www-authenticate")?.length ?? 0) > 8192 || (response.headers.get("mcp-session-id")?.length ?? 0) > 1024) {
3186
+ this.#cancelBody(response);
3187
+ this.stop("response-too-large");
3188
+ throw new DetectionFailure("response-too-large");
3189
+ }
3190
+ const sessionId = response.headers.get("mcp-session-id");
3191
+ if (sessionId !== null && !/^[\x21-\x7e]+$/.test(sessionId)) {
3192
+ this.#cancelBody(response);
3193
+ this.stop("invalid-response");
3194
+ throw new DetectionFailure("invalid-response");
3195
+ }
3196
+ return this.#bounded(response, signal);
3197
+ }
3198
+ cancel(response) {
3199
+ this.#readers.get(response)?.();
3200
+ }
3201
+ #cancelBody(response) {
3202
+ if (response.body !== null) this.#cancellations.add(response.body.cancel().catch(() => {}));
3203
+ }
3204
+ #bounded(response, signal) {
3205
+ if (response.body === null) return response;
3206
+ const reader = response.body.getReader();
3207
+ let ended = false;
3208
+ let wrapped;
3209
+ let controller;
3210
+ const detach = () => {
3211
+ signal.removeEventListener("abort", abort);
3212
+ this.#readers.delete(wrapped);
3213
+ };
3214
+ const cancel = () => {
3215
+ if (ended) return;
3216
+ ended = true;
3217
+ detach();
3218
+ controller.close();
3219
+ this.#cancellations.add(reader.cancel().catch(() => {}).finally(() => reader.releaseLock()));
3220
+ };
3221
+ const abort = () => {
3222
+ if (ended) return;
3223
+ controller.error(new DetectionFailure(this.failure ?? "invalid-response"));
3224
+ ended = true;
3225
+ detach();
3226
+ this.#cancellations.add(reader.cancel().catch(() => {}).finally(() => reader.releaseLock()));
3227
+ };
3228
+ const stream = new ReadableStream({
3229
+ start(value) {
3230
+ controller = value;
3231
+ },
3232
+ pull: async () => {
3233
+ try {
3234
+ const chunk = await reader.read();
3235
+ if (ended) return;
3236
+ if (chunk.done) {
3237
+ ended = true;
3238
+ detach();
3239
+ reader.releaseLock();
3240
+ controller.close();
3241
+ return;
3242
+ }
3243
+ this.#bytes += chunk.value.byteLength;
3244
+ if (this.#bytes > this.maximum) {
3245
+ this.stop("response-too-large");
3246
+ return;
3247
+ }
3248
+ controller.enqueue(chunk.value);
3249
+ } catch {
3250
+ if (!ended) this.stop("network-error");
3251
+ }
3252
+ },
3253
+ cancel: () => {
3254
+ if (!ended) {
3255
+ ended = true;
3256
+ detach();
3257
+ this.#cancellations.add(reader.cancel().catch(() => {}).finally(() => reader.releaseLock()));
3258
+ }
3259
+ }
3260
+ }, { highWaterMark: 0 });
3261
+ wrapped = new Response(stream, {
3262
+ status: response.status,
3263
+ headers: response.headers
3264
+ });
3265
+ this.#readers.set(wrapped, cancel);
3266
+ signal.addEventListener("abort", abort, { once: true });
3267
+ if (signal.aborted) abort();
3268
+ return wrapped;
3269
+ }
3270
+ async close(client, transport, endpoint) {
3271
+ const cleanup = new AbortController();
3272
+ const timer = setTimeout(() => cleanup.abort(), 1e3);
3273
+ const signal = AbortSignal.any([this.input.signal, cleanup.signal]);
3274
+ try {
3275
+ const sessionId = transport.sessionId;
3276
+ this.#controller.abort();
3277
+ await withSignal(Promise.all([client.close(), transport.close()]), signal);
3278
+ if (sessionId !== void 0 && /^[\x21-\x7e]{1,1024}$/.test(sessionId)) {
3279
+ signal.throwIfAborted();
3280
+ const headers = new Headers({ "mcp-session-id": sessionId });
3281
+ if (transport.protocolVersion !== void 0) headers.set("mcp-protocol-version", transport.protocolVersion);
3282
+ const response = await withSignal(Promise.resolve(this.input.fetch(endpoint, credentialFreeInit({
3283
+ method: "DELETE",
3284
+ headers
3285
+ }, signal))).then((response) => {
3286
+ this.#cancelBody(response);
3287
+ return response;
3288
+ }), signal);
3289
+ if (response.redirected || response.url !== "" && response.url !== endpoint.href || !response.ok && response.status !== 405) return false;
3290
+ }
3291
+ await withSignal(Promise.all(this.#cancellations), signal);
3292
+ return true;
3293
+ } catch {
3294
+ return false;
3295
+ } finally {
3296
+ cleanup.abort();
3297
+ clearTimeout(timer);
3298
+ }
3299
+ }
3300
+ };
3301
+ function credentialFreeInit(init, signal) {
3302
+ const headers = new Headers(init?.headers);
3303
+ for (const name of [
3304
+ "authorization",
3305
+ "proxy-authorization",
3306
+ "cookie"
3307
+ ]) headers.delete(name);
3308
+ return {
3309
+ ...init,
3310
+ headers,
3311
+ signal,
3312
+ credentials: "omit",
3313
+ redirect: "error",
3314
+ cache: "no-store"
3315
+ };
3316
+ }
3317
+ function outgoingMethod(body) {
3318
+ if (typeof body !== "string") return void 0;
3319
+ const value = JSON.parse(body);
3320
+ return typeof value === "object" && value !== null && "method" in value && typeof value.method === "string" ? value.method : void 0;
3321
+ }
3322
+ function boundedServerInfo(info) {
3323
+ if (info === void 0 || info.name.length > 256 || info.version.length > 128) return void 0;
3324
+ return Object.freeze({
3325
+ name: info.name,
3326
+ version: info.version,
3327
+ ...info.title === void 0 || info.title.length > 256 ? {} : { title: info.title }
3328
+ });
3329
+ }
3330
+ function indeterminate(reason, httpStatus, discoveryErrorCode) {
3331
+ return Object.freeze({
3332
+ kind: "indeterminate",
3333
+ reason,
3334
+ ...httpStatus === void 0 ? {} : { httpStatus },
3335
+ ...discoveryErrorCode === void 0 ? {} : { discoveryErrorCode }
3336
+ });
3337
+ }
3338
+ function withSignal(promise, signal) {
3339
+ return new Promise((resolve, reject) => {
3340
+ const aborted = () => reject(signal.reason);
3341
+ signal.addEventListener("abort", aborted, { once: true });
3342
+ if (signal.aborted) aborted();
3343
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", aborted));
3344
+ });
3345
+ }
3346
+ //#endregion
3347
+ export { MCP_CLIENT_OAUTH_MAX_SCOPE_LENGTH, McpClientOAuthAuthProvider, McpClientOAuthAuthProviderError, McpClientOAuthAuthProviderErrorCode, McpClientOAuthBootstrap, McpClientOAuthBootstrapError, McpClientOAuthBootstrapErrorCode, McpClientOAuthCredentialInvalidationReason, McpClientOAuthProtocol, McpClientOAuthProtocolError, McpClientOAuthProtocolErrorCode, McpClientOAuthRefreshCoordinator, McpClientOAuthRefreshError, McpClientOAuthRefreshErrorCode, McpClientOAuthSnapshotError, McpClientOAuthStrictCompatibilityIssue, McpOAuthStateError, McpOAuthStateErrorCode, classifyMcpClientOAuthRefreshFailure, createMcpClientOAuthCredentialRevision, createMcpClientOAuthCredentialSnapshot, createOAuthState, createOAuthStateLookupDigest, createPkceS256Challenge, createPkceVerifier, detectMcpClientAuthentication, getMcpClientOAuthApplicationType, isMcpClientOAuthCredentialRevision, isMcpClientOAuthScopeToken, mcpClientOAuthScopesCover, nextMcpClientOAuthCredentialRevision, parseMcpClientOAuthAuthority, parseMcpClientOAuthAuthorizationTransaction, parseMcpClientOAuthBootstrapChallenge, parseMcpClientOAuthBootstrapDiscoveryResult, parseOAuthCallbackParameters, planMcpClientOAuthProvisioning, probeMcpClientOAuthChallenge, validateOAuthState };
3348
+
3349
+ //# sourceMappingURL=index.mjs.map