x402-proxy 0.10.7 → 0.10.9

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 (90) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/README.md +7 -1
  3. package/dist/Credential-COZQnr1-.js +2055 -0
  4. package/dist/Mcp-CrCEqLqO.js +10 -0
  5. package/dist/Sse-ChldYgU7.js +9742 -0
  6. package/dist/Sse-kCB38G56.js +16482 -0
  7. package/dist/accounts-DsuvWwph.js +232 -0
  8. package/dist/accounts-DzvAlQRn.js +5 -0
  9. package/dist/accounts-IG-Cmrwy.js +229 -0
  10. package/dist/api-CUzmQvTQ.js +2802 -0
  11. package/dist/auth-DTzQmnZ_.js +1196 -0
  12. package/dist/bin/cli.js +585 -242
  13. package/dist/ccip-Bx-zoUCJ.js +240 -0
  14. package/dist/ccip-C2k1DD1T.js +153 -0
  15. package/dist/ccip-C6CQOJYv.js +152 -0
  16. package/dist/ccip-RZzsZ5Mv.js +156 -0
  17. package/dist/chain-CafcHffR.js +1997 -0
  18. package/dist/chain-DwfP5RGZ.js +1968 -0
  19. package/dist/chunk-DBEY4PJZ.js +16 -0
  20. package/dist/chunk-DjEMn6fM.js +36 -0
  21. package/dist/client-Blw2V7LF.js +657 -0
  22. package/dist/client-C37gWJOZ.js +102 -0
  23. package/dist/client-CEc4NYAA.js +6388 -0
  24. package/dist/client-CVDTUY0l.js +5152 -0
  25. package/dist/config-BUQsit4s.js +3 -0
  26. package/dist/config-DR1Fs_wL.js +6600 -0
  27. package/dist/{config-D9wIR3xc.js → config-rvKA3SYT.js} +10 -5
  28. package/dist/decodeFunctionData-DuFcwhC_.js +4510 -0
  29. package/dist/decodeFunctionData-JPOUdvil.js +4394 -0
  30. package/dist/derive-DNUl8LU9.js +9109 -0
  31. package/dist/dist-C2YO6HSQ.js +6581 -0
  32. package/dist/dist-DM5_F3r5.js +4 -0
  33. package/dist/dist-DxJCYyL5.js +1388 -0
  34. package/dist/hashTypedData-BHmP9dBd.js +859 -0
  35. package/dist/hashTypedData-CtEdfx4y.js +846 -0
  36. package/dist/helpers-CuUSw-tH.js +7125 -0
  37. package/dist/hmac-59IlS_by.js +648 -0
  38. package/dist/http-BAtucMbS.js +2060 -0
  39. package/dist/index.d.ts +1903 -9
  40. package/dist/index.js +18006 -50
  41. package/dist/index.node-CxkL0OFh.js +3592 -0
  42. package/dist/index.node-DvmeuZBj.js +3 -0
  43. package/dist/isAddressEqual-BLrd1Hg1.js +9 -0
  44. package/dist/isAddressEqual-DsAqfQOD.js +10 -0
  45. package/dist/localBatchGatewayRequest-C-RPJyDO.js +6260 -0
  46. package/dist/localBatchGatewayRequest-DOdQ9bR7.js +93 -0
  47. package/dist/localBatchGatewayRequest-DQkbZaSy.js +6261 -0
  48. package/dist/parseUnits-CApwcKSD.js +49 -0
  49. package/dist/parseUnits-cMO2udMe.js +48 -0
  50. package/dist/schemas-BxMFYNbH.js +1270 -0
  51. package/dist/secp256k1-BZpiyffY.js +2525 -0
  52. package/dist/secp256k1-BjenrLl5.js +1877 -0
  53. package/dist/secp256k1-CLPUX17u.js +3 -0
  54. package/dist/sendRawTransactionSync-DvSkhZtW.js +3612 -0
  55. package/dist/server-CSq0IuUq.js +565 -0
  56. package/dist/setup-BY4J49Lv.js +1110 -0
  57. package/dist/setup-wMOAgrsN.js +3 -0
  58. package/dist/sha256-FAs0qeni.js +17 -0
  59. package/dist/sha3-CYkWM8Xa.js +195 -0
  60. package/dist/sha3-DbMJRJ3C.js +194 -0
  61. package/dist/sse-B4LLqBQm.js +408 -0
  62. package/dist/status-Bu23RjW6.js +3 -0
  63. package/dist/{status-DihAcUSC.js → status-X21VnGUO.js} +16 -15
  64. package/dist/stdio-BADqxZdZ.js +85 -0
  65. package/dist/streamableHttp-BHkJypcI.js +358 -0
  66. package/dist/tempo-3nttrxgQ.js +17 -0
  67. package/dist/tempo-DER0P-ul.js +18 -0
  68. package/dist/types-BEKUz-Mf.js +1240 -0
  69. package/dist/types-DatK5vR5.js +3 -0
  70. package/dist/utils-BYjkXZDF.js +444 -0
  71. package/dist/utils-SeGHMW9O.js +445 -0
  72. package/dist/wallet-DKVlrR1S.js +3 -0
  73. package/dist/wallet-DSyht15_.js +17759 -0
  74. package/package.json +18 -71
  75. package/dist/config-B_upkJeK.js +0 -66
  76. package/dist/config-Be35NM5s.js +0 -3
  77. package/dist/config-J1m-CWXT.js +0 -27
  78. package/dist/derive-CL6e8K0Z.js +0 -81
  79. package/dist/openclaw/plugin.d.ts +0 -15
  80. package/dist/openclaw/plugin.js +0 -2067
  81. package/dist/openclaw.plugin.json +0 -93
  82. package/dist/setup-CNyMLnM-.js +0 -197
  83. package/dist/setup-DTIxPe58.js +0 -3
  84. package/dist/status-DZlJ4pS7.js +0 -3
  85. package/dist/wallet-B0S-rma9.js +0 -544
  86. package/dist/wallet-DBrVZJqe.js +0 -3
  87. package/openclaw.plugin.json +0 -93
  88. package/skills/SKILL.md +0 -183
  89. package/skills/references/library.md +0 -85
  90. package/skills/references/openclaw-plugin.md +0 -145
@@ -0,0 +1,1196 @@
1
+ #!/usr/bin/env node
2
+ import { Wn as NEVER, c as _coercedNumber } from "./api-CUzmQvTQ.js";
3
+ import { _ as string, a as array, b as url, d as looseObject, f as number$1, i as any, o as boolean, p as object, t as ZodNumber, u as literal } from "./schemas-BxMFYNbH.js";
4
+ import { tt as LATEST_PROTOCOL_VERSION } from "./types-BEKUz-Mf.js";
5
+ //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js
6
+ /** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
7
+ const ZodIssueCode = {
8
+ invalid_type: "invalid_type",
9
+ too_big: "too_big",
10
+ too_small: "too_small",
11
+ invalid_format: "invalid_format",
12
+ not_multiple_of: "not_multiple_of",
13
+ unrecognized_keys: "unrecognized_keys",
14
+ invalid_union: "invalid_union",
15
+ invalid_key: "invalid_key",
16
+ invalid_element: "invalid_element",
17
+ invalid_value: "invalid_value",
18
+ custom: "custom"
19
+ };
20
+ /** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
21
+ var ZodFirstPartyTypeKind;
22
+ (function(ZodFirstPartyTypeKind) {})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
23
+ //#endregion
24
+ //#region node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js
25
+ function number(params) {
26
+ return _coercedNumber(ZodNumber, params);
27
+ }
28
+ //#endregion
29
+ //#region node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
30
+ var ParseError = class extends Error {
31
+ constructor(message, options) {
32
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
33
+ }
34
+ };
35
+ function noop(_arg) {}
36
+ function createParser(callbacks) {
37
+ if (typeof callbacks == "function") throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
38
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
39
+ let incompleteLine = "", isFirstChunk = !0, id, data = "", eventType = "";
40
+ function feed(newChunk) {
41
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
42
+ for (const line of complete) parseLine(line);
43
+ incompleteLine = incomplete, isFirstChunk = !1;
44
+ }
45
+ function parseLine(line) {
46
+ if (line === "") {
47
+ dispatchEvent();
48
+ return;
49
+ }
50
+ if (line.startsWith(":")) {
51
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
52
+ return;
53
+ }
54
+ const fieldSeparatorIndex = line.indexOf(":");
55
+ if (fieldSeparatorIndex !== -1) {
56
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1;
57
+ processField(field, line.slice(fieldSeparatorIndex + offset), line);
58
+ return;
59
+ }
60
+ processField(line, "", line);
61
+ }
62
+ function processField(field, value, line) {
63
+ switch (field) {
64
+ case "event":
65
+ eventType = value;
66
+ break;
67
+ case "data":
68
+ data = `${data}${value}
69
+ `;
70
+ break;
71
+ case "id":
72
+ id = value.includes("\0") ? void 0 : value;
73
+ break;
74
+ case "retry":
75
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
76
+ type: "invalid-retry",
77
+ value,
78
+ line
79
+ }));
80
+ break;
81
+ default:
82
+ onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
83
+ type: "unknown-field",
84
+ field,
85
+ value,
86
+ line
87
+ }));
88
+ break;
89
+ }
90
+ }
91
+ function dispatchEvent() {
92
+ data.length > 0 && onEvent({
93
+ id,
94
+ event: eventType || void 0,
95
+ data: data.endsWith(`
96
+ `) ? data.slice(0, -1) : data
97
+ }), id = void 0, data = "", eventType = "";
98
+ }
99
+ function reset(options = {}) {
100
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = "", eventType = "", incompleteLine = "";
101
+ }
102
+ return {
103
+ feed,
104
+ reset
105
+ };
106
+ }
107
+ function splitLines(chunk) {
108
+ const lines = [];
109
+ let incompleteLine = "", searchIndex = 0;
110
+ for (; searchIndex < chunk.length;) {
111
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
112
+ `, searchIndex);
113
+ let lineEnd = -1;
114
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
115
+ incompleteLine = chunk.slice(searchIndex);
116
+ break;
117
+ } else {
118
+ const line = chunk.slice(searchIndex, lineEnd);
119
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
120
+ ` && searchIndex++;
121
+ }
122
+ }
123
+ return [lines, incompleteLine];
124
+ }
125
+ //#endregion
126
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
127
+ /**
128
+ * Normalizes HeadersInit to a plain Record<string, string> for manipulation.
129
+ * Handles Headers objects, arrays of tuples, and plain objects.
130
+ */
131
+ function normalizeHeaders(headers) {
132
+ if (!headers) return {};
133
+ if (headers instanceof Headers) return Object.fromEntries(headers.entries());
134
+ if (Array.isArray(headers)) return Object.fromEntries(headers);
135
+ return { ...headers };
136
+ }
137
+ /**
138
+ * Creates a fetch function that includes base RequestInit options.
139
+ * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.
140
+ *
141
+ * @param baseFetch - The base fetch function to wrap (defaults to global fetch)
142
+ * @param baseInit - The base RequestInit to merge with each request
143
+ * @returns A wrapped fetch function that merges base options with call-specific options
144
+ */
145
+ function createFetchWithInit(baseFetch = fetch, baseInit) {
146
+ if (!baseInit) return baseFetch;
147
+ return async (url, init) => {
148
+ return baseFetch(url, {
149
+ ...baseInit,
150
+ ...init,
151
+ headers: init?.headers ? {
152
+ ...normalizeHeaders(baseInit.headers),
153
+ ...normalizeHeaders(init.headers)
154
+ } : baseInit.headers
155
+ });
156
+ };
157
+ }
158
+ //#endregion
159
+ //#region node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
160
+ let crypto;
161
+ crypto = globalThis.crypto?.webcrypto ?? globalThis.crypto ?? import("node:crypto").then((m) => m.webcrypto);
162
+ /**
163
+ * Creates an array of length `size` of random bytes
164
+ * @param size
165
+ * @returns Array of random ints (0 to 255)
166
+ */
167
+ async function getRandomValues(size) {
168
+ return (await crypto).getRandomValues(new Uint8Array(size));
169
+ }
170
+ /** Generate cryptographically strong random string
171
+ * @param size The desired length of the string
172
+ * @returns The random string
173
+ */
174
+ async function random(size) {
175
+ const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
176
+ const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % 66;
177
+ let result = "";
178
+ while (result.length < size) {
179
+ const randomBytes = await getRandomValues(size - result.length);
180
+ for (const randomByte of randomBytes) if (randomByte < evenDistCutoff) result += mask[randomByte % 66];
181
+ }
182
+ return result;
183
+ }
184
+ /** Generate a PKCE challenge verifier
185
+ * @param length Length of the verifier
186
+ * @returns A random verifier `length` characters long
187
+ */
188
+ async function generateVerifier(length) {
189
+ return await random(length);
190
+ }
191
+ /** Generate a PKCE code challenge from a code verifier
192
+ * @param code_verifier
193
+ * @returns The base64 url encoded code challenge
194
+ */
195
+ async function generateChallenge(code_verifier) {
196
+ const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
197
+ return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
198
+ }
199
+ /** Generate a PKCE challenge pair
200
+ * @param length Length of the verifer (between 43-128). Defaults to 43.
201
+ * @returns PKCE challenge pair
202
+ */
203
+ async function pkceChallenge(length) {
204
+ if (!length) length = 43;
205
+ if (length < 43 || length > 128) throw `Expected a length between 43 and 128. Received ${length}.`;
206
+ const verifier = await generateVerifier(length);
207
+ return {
208
+ code_verifier: verifier,
209
+ code_challenge: await generateChallenge(verifier)
210
+ };
211
+ }
212
+ //#endregion
213
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
214
+ /**
215
+ * Reusable URL validation that disallows javascript: scheme
216
+ */
217
+ const SafeUrlSchema = url().superRefine((val, ctx) => {
218
+ if (!URL.canParse(val)) {
219
+ ctx.addIssue({
220
+ code: ZodIssueCode.custom,
221
+ message: "URL must be parseable",
222
+ fatal: true
223
+ });
224
+ return NEVER;
225
+ }
226
+ }).refine((url) => {
227
+ const u = new URL(url);
228
+ return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
229
+ }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
230
+ /**
231
+ * RFC 9728 OAuth Protected Resource Metadata
232
+ */
233
+ const OAuthProtectedResourceMetadataSchema = looseObject({
234
+ resource: string().url(),
235
+ authorization_servers: array(SafeUrlSchema).optional(),
236
+ jwks_uri: string().url().optional(),
237
+ scopes_supported: array(string()).optional(),
238
+ bearer_methods_supported: array(string()).optional(),
239
+ resource_signing_alg_values_supported: array(string()).optional(),
240
+ resource_name: string().optional(),
241
+ resource_documentation: string().optional(),
242
+ resource_policy_uri: string().url().optional(),
243
+ resource_tos_uri: string().url().optional(),
244
+ tls_client_certificate_bound_access_tokens: boolean().optional(),
245
+ authorization_details_types_supported: array(string()).optional(),
246
+ dpop_signing_alg_values_supported: array(string()).optional(),
247
+ dpop_bound_access_tokens_required: boolean().optional()
248
+ });
249
+ /**
250
+ * RFC 8414 OAuth 2.0 Authorization Server Metadata
251
+ */
252
+ const OAuthMetadataSchema = looseObject({
253
+ issuer: string(),
254
+ authorization_endpoint: SafeUrlSchema,
255
+ token_endpoint: SafeUrlSchema,
256
+ registration_endpoint: SafeUrlSchema.optional(),
257
+ scopes_supported: array(string()).optional(),
258
+ response_types_supported: array(string()),
259
+ response_modes_supported: array(string()).optional(),
260
+ grant_types_supported: array(string()).optional(),
261
+ token_endpoint_auth_methods_supported: array(string()).optional(),
262
+ token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
263
+ service_documentation: SafeUrlSchema.optional(),
264
+ revocation_endpoint: SafeUrlSchema.optional(),
265
+ revocation_endpoint_auth_methods_supported: array(string()).optional(),
266
+ revocation_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
267
+ introspection_endpoint: string().optional(),
268
+ introspection_endpoint_auth_methods_supported: array(string()).optional(),
269
+ introspection_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
270
+ code_challenge_methods_supported: array(string()).optional(),
271
+ client_id_metadata_document_supported: boolean().optional()
272
+ });
273
+ /**
274
+ * OpenID Connect Discovery metadata that may include OAuth 2.0 fields
275
+ * This schema represents the real-world scenario where OIDC providers
276
+ * return a mix of OpenID Connect and OAuth 2.0 metadata fields
277
+ */
278
+ const OpenIdProviderDiscoveryMetadataSchema = object({
279
+ ...looseObject({
280
+ issuer: string(),
281
+ authorization_endpoint: SafeUrlSchema,
282
+ token_endpoint: SafeUrlSchema,
283
+ userinfo_endpoint: SafeUrlSchema.optional(),
284
+ jwks_uri: SafeUrlSchema,
285
+ registration_endpoint: SafeUrlSchema.optional(),
286
+ scopes_supported: array(string()).optional(),
287
+ response_types_supported: array(string()),
288
+ response_modes_supported: array(string()).optional(),
289
+ grant_types_supported: array(string()).optional(),
290
+ acr_values_supported: array(string()).optional(),
291
+ subject_types_supported: array(string()),
292
+ id_token_signing_alg_values_supported: array(string()),
293
+ id_token_encryption_alg_values_supported: array(string()).optional(),
294
+ id_token_encryption_enc_values_supported: array(string()).optional(),
295
+ userinfo_signing_alg_values_supported: array(string()).optional(),
296
+ userinfo_encryption_alg_values_supported: array(string()).optional(),
297
+ userinfo_encryption_enc_values_supported: array(string()).optional(),
298
+ request_object_signing_alg_values_supported: array(string()).optional(),
299
+ request_object_encryption_alg_values_supported: array(string()).optional(),
300
+ request_object_encryption_enc_values_supported: array(string()).optional(),
301
+ token_endpoint_auth_methods_supported: array(string()).optional(),
302
+ token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
303
+ display_values_supported: array(string()).optional(),
304
+ claim_types_supported: array(string()).optional(),
305
+ claims_supported: array(string()).optional(),
306
+ service_documentation: string().optional(),
307
+ claims_locales_supported: array(string()).optional(),
308
+ ui_locales_supported: array(string()).optional(),
309
+ claims_parameter_supported: boolean().optional(),
310
+ request_parameter_supported: boolean().optional(),
311
+ request_uri_parameter_supported: boolean().optional(),
312
+ require_request_uri_registration: boolean().optional(),
313
+ op_policy_uri: SafeUrlSchema.optional(),
314
+ op_tos_uri: SafeUrlSchema.optional(),
315
+ client_id_metadata_document_supported: boolean().optional()
316
+ }).shape,
317
+ ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape
318
+ });
319
+ /**
320
+ * OAuth 2.1 token response
321
+ */
322
+ const OAuthTokensSchema = object({
323
+ access_token: string(),
324
+ id_token: string().optional(),
325
+ token_type: string(),
326
+ expires_in: number().optional(),
327
+ scope: string().optional(),
328
+ refresh_token: string().optional()
329
+ }).strip();
330
+ /**
331
+ * OAuth 2.1 error response
332
+ */
333
+ const OAuthErrorResponseSchema = object({
334
+ error: string(),
335
+ error_description: string().optional(),
336
+ error_uri: string().optional()
337
+ });
338
+ /**
339
+ * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri
340
+ */
341
+ const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0));
342
+ /**
343
+ * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata
344
+ */
345
+ const OAuthClientMetadataSchema = object({
346
+ redirect_uris: array(SafeUrlSchema),
347
+ token_endpoint_auth_method: string().optional(),
348
+ grant_types: array(string()).optional(),
349
+ response_types: array(string()).optional(),
350
+ client_name: string().optional(),
351
+ client_uri: SafeUrlSchema.optional(),
352
+ logo_uri: OptionalSafeUrlSchema,
353
+ scope: string().optional(),
354
+ contacts: array(string()).optional(),
355
+ tos_uri: OptionalSafeUrlSchema,
356
+ policy_uri: string().optional(),
357
+ jwks_uri: SafeUrlSchema.optional(),
358
+ jwks: any().optional(),
359
+ software_id: string().optional(),
360
+ software_version: string().optional(),
361
+ software_statement: string().optional()
362
+ }).strip();
363
+ /**
364
+ * RFC 7591 OAuth 2.0 Dynamic Client Registration client information
365
+ */
366
+ const OAuthClientInformationSchema = object({
367
+ client_id: string(),
368
+ client_secret: string().optional(),
369
+ client_id_issued_at: number$1().optional(),
370
+ client_secret_expires_at: number$1().optional()
371
+ }).strip();
372
+ /**
373
+ * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)
374
+ */
375
+ const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
376
+ object({
377
+ error: string(),
378
+ error_description: string().optional()
379
+ }).strip();
380
+ object({
381
+ token: string(),
382
+ token_type_hint: string().optional()
383
+ }).strip();
384
+ //#endregion
385
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
386
+ /**
387
+ * Utilities for handling OAuth resource URIs.
388
+ */
389
+ /**
390
+ * Converts a server URL to a resource URL by removing the fragment.
391
+ * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component".
392
+ * Keeps everything else unchanged (scheme, domain, port, path, query).
393
+ */
394
+ function resourceUrlFromServerUrl(url) {
395
+ const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href);
396
+ resourceURL.hash = "";
397
+ return resourceURL;
398
+ }
399
+ /**
400
+ * Checks if a requested resource URL matches a configured resource URL.
401
+ * A requested resource matches if it has the same scheme, domain, port,
402
+ * and its path starts with the configured resource's path.
403
+ *
404
+ * @param requestedResource The resource URL being requested
405
+ * @param configuredResource The resource URL that has been configured
406
+ * @returns true if the requested resource matches the configured resource, false otherwise
407
+ */
408
+ function checkResourceAllowed({ requestedResource, configuredResource }) {
409
+ const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
410
+ const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
411
+ if (requested.origin !== configured.origin) return false;
412
+ if (requested.pathname.length < configured.pathname.length) return false;
413
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
414
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
415
+ return requestedPath.startsWith(configuredPath);
416
+ }
417
+ //#endregion
418
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
419
+ /**
420
+ * Base class for all OAuth errors
421
+ */
422
+ var OAuthError = class extends Error {
423
+ constructor(message, errorUri) {
424
+ super(message);
425
+ this.errorUri = errorUri;
426
+ this.name = this.constructor.name;
427
+ }
428
+ /**
429
+ * Converts the error to a standard OAuth error response object
430
+ */
431
+ toResponseObject() {
432
+ const response = {
433
+ error: this.errorCode,
434
+ error_description: this.message
435
+ };
436
+ if (this.errorUri) response.error_uri = this.errorUri;
437
+ return response;
438
+ }
439
+ get errorCode() {
440
+ return this.constructor.errorCode;
441
+ }
442
+ };
443
+ /**
444
+ * Invalid request error - The request is missing a required parameter,
445
+ * includes an invalid parameter value, includes a parameter more than once,
446
+ * or is otherwise malformed.
447
+ */
448
+ var InvalidRequestError = class extends OAuthError {};
449
+ InvalidRequestError.errorCode = "invalid_request";
450
+ /**
451
+ * Invalid client error - Client authentication failed (e.g., unknown client, no client
452
+ * authentication included, or unsupported authentication method).
453
+ */
454
+ var InvalidClientError = class extends OAuthError {};
455
+ InvalidClientError.errorCode = "invalid_client";
456
+ /**
457
+ * Invalid grant error - The provided authorization grant or refresh token is
458
+ * invalid, expired, revoked, does not match the redirection URI used in the
459
+ * authorization request, or was issued to another client.
460
+ */
461
+ var InvalidGrantError = class extends OAuthError {};
462
+ InvalidGrantError.errorCode = "invalid_grant";
463
+ /**
464
+ * Unauthorized client error - The authenticated client is not authorized to use
465
+ * this authorization grant type.
466
+ */
467
+ var UnauthorizedClientError = class extends OAuthError {};
468
+ UnauthorizedClientError.errorCode = "unauthorized_client";
469
+ /**
470
+ * Unsupported grant type error - The authorization grant type is not supported
471
+ * by the authorization server.
472
+ */
473
+ var UnsupportedGrantTypeError = class extends OAuthError {};
474
+ UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
475
+ /**
476
+ * Invalid scope error - The requested scope is invalid, unknown, malformed, or
477
+ * exceeds the scope granted by the resource owner.
478
+ */
479
+ var InvalidScopeError = class extends OAuthError {};
480
+ InvalidScopeError.errorCode = "invalid_scope";
481
+ /**
482
+ * Access denied error - The resource owner or authorization server denied the request.
483
+ */
484
+ var AccessDeniedError = class extends OAuthError {};
485
+ AccessDeniedError.errorCode = "access_denied";
486
+ /**
487
+ * Server error - The authorization server encountered an unexpected condition
488
+ * that prevented it from fulfilling the request.
489
+ */
490
+ var ServerError = class extends OAuthError {};
491
+ ServerError.errorCode = "server_error";
492
+ /**
493
+ * Temporarily unavailable error - The authorization server is currently unable to
494
+ * handle the request due to a temporary overloading or maintenance of the server.
495
+ */
496
+ var TemporarilyUnavailableError = class extends OAuthError {};
497
+ TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
498
+ /**
499
+ * Unsupported response type error - The authorization server does not support
500
+ * obtaining an authorization code using this method.
501
+ */
502
+ var UnsupportedResponseTypeError = class extends OAuthError {};
503
+ UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
504
+ /**
505
+ * Unsupported token type error - The authorization server does not support
506
+ * the requested token type.
507
+ */
508
+ var UnsupportedTokenTypeError = class extends OAuthError {};
509
+ UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
510
+ /**
511
+ * Invalid token error - The access token provided is expired, revoked, malformed,
512
+ * or invalid for other reasons.
513
+ */
514
+ var InvalidTokenError = class extends OAuthError {};
515
+ InvalidTokenError.errorCode = "invalid_token";
516
+ /**
517
+ * Method not allowed error - The HTTP method used is not allowed for this endpoint.
518
+ * (Custom, non-standard error)
519
+ */
520
+ var MethodNotAllowedError = class extends OAuthError {};
521
+ MethodNotAllowedError.errorCode = "method_not_allowed";
522
+ /**
523
+ * Too many requests error - Rate limit exceeded.
524
+ * (Custom, non-standard error based on RFC 6585)
525
+ */
526
+ var TooManyRequestsError = class extends OAuthError {};
527
+ TooManyRequestsError.errorCode = "too_many_requests";
528
+ /**
529
+ * Invalid client metadata error - The client metadata is invalid.
530
+ * (Custom error for dynamic client registration - RFC 7591)
531
+ */
532
+ var InvalidClientMetadataError = class extends OAuthError {};
533
+ InvalidClientMetadataError.errorCode = "invalid_client_metadata";
534
+ /**
535
+ * Insufficient scope error - The request requires higher privileges than provided by the access token.
536
+ */
537
+ var InsufficientScopeError = class extends OAuthError {};
538
+ InsufficientScopeError.errorCode = "insufficient_scope";
539
+ /**
540
+ * Invalid target error - The requested resource is invalid, missing, unknown, or malformed.
541
+ * (Custom error for resource indicators - RFC 8707)
542
+ */
543
+ var InvalidTargetError = class extends OAuthError {};
544
+ InvalidTargetError.errorCode = "invalid_target";
545
+ /**
546
+ * A full list of all OAuthErrors, enabling parsing from error responses
547
+ */
548
+ const OAUTH_ERRORS = {
549
+ [InvalidRequestError.errorCode]: InvalidRequestError,
550
+ [InvalidClientError.errorCode]: InvalidClientError,
551
+ [InvalidGrantError.errorCode]: InvalidGrantError,
552
+ [UnauthorizedClientError.errorCode]: UnauthorizedClientError,
553
+ [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
554
+ [InvalidScopeError.errorCode]: InvalidScopeError,
555
+ [AccessDeniedError.errorCode]: AccessDeniedError,
556
+ [ServerError.errorCode]: ServerError,
557
+ [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
558
+ [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
559
+ [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
560
+ [InvalidTokenError.errorCode]: InvalidTokenError,
561
+ [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
562
+ [TooManyRequestsError.errorCode]: TooManyRequestsError,
563
+ [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
564
+ [InsufficientScopeError.errorCode]: InsufficientScopeError,
565
+ [InvalidTargetError.errorCode]: InvalidTargetError
566
+ };
567
+ //#endregion
568
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
569
+ var UnauthorizedError = class extends Error {
570
+ constructor(message) {
571
+ super(message ?? "Unauthorized");
572
+ }
573
+ };
574
+ function isClientAuthMethod(method) {
575
+ return [
576
+ "client_secret_basic",
577
+ "client_secret_post",
578
+ "none"
579
+ ].includes(method);
580
+ }
581
+ const AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
582
+ const AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
583
+ /**
584
+ * Determines the best client authentication method to use based on server support and client configuration.
585
+ *
586
+ * Priority order (highest to lowest):
587
+ * 1. client_secret_basic (if client secret is available)
588
+ * 2. client_secret_post (if client secret is available)
589
+ * 3. none (for public clients)
590
+ *
591
+ * @param clientInformation - OAuth client information containing credentials
592
+ * @param supportedMethods - Authentication methods supported by the authorization server
593
+ * @returns The selected authentication method
594
+ */
595
+ function selectClientAuthMethod(clientInformation, supportedMethods) {
596
+ const hasClientSecret = clientInformation.client_secret !== void 0;
597
+ if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) return clientInformation.token_endpoint_auth_method;
598
+ if (supportedMethods.length === 0) return hasClientSecret ? "client_secret_basic" : "none";
599
+ if (hasClientSecret && supportedMethods.includes("client_secret_basic")) return "client_secret_basic";
600
+ if (hasClientSecret && supportedMethods.includes("client_secret_post")) return "client_secret_post";
601
+ if (supportedMethods.includes("none")) return "none";
602
+ return hasClientSecret ? "client_secret_post" : "none";
603
+ }
604
+ /**
605
+ * Applies client authentication to the request based on the specified method.
606
+ *
607
+ * Implements OAuth 2.1 client authentication methods:
608
+ * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)
609
+ * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)
610
+ * - none: Public client authentication (RFC 6749 Section 2.1)
611
+ *
612
+ * @param method - The authentication method to use
613
+ * @param clientInformation - OAuth client information containing credentials
614
+ * @param headers - HTTP headers object to modify
615
+ * @param params - URL search parameters to modify
616
+ * @throws {Error} When required credentials are missing
617
+ */
618
+ function applyClientAuthentication(method, clientInformation, headers, params) {
619
+ const { client_id, client_secret } = clientInformation;
620
+ switch (method) {
621
+ case "client_secret_basic":
622
+ applyBasicAuth(client_id, client_secret, headers);
623
+ return;
624
+ case "client_secret_post":
625
+ applyPostAuth(client_id, client_secret, params);
626
+ return;
627
+ case "none":
628
+ applyPublicAuth(client_id, params);
629
+ return;
630
+ default: throw new Error(`Unsupported client authentication method: ${method}`);
631
+ }
632
+ }
633
+ /**
634
+ * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)
635
+ */
636
+ function applyBasicAuth(clientId, clientSecret, headers) {
637
+ if (!clientSecret) throw new Error("client_secret_basic authentication requires a client_secret");
638
+ const credentials = btoa(`${clientId}:${clientSecret}`);
639
+ headers.set("Authorization", `Basic ${credentials}`);
640
+ }
641
+ /**
642
+ * Applies POST body authentication (RFC 6749 Section 2.3.1)
643
+ */
644
+ function applyPostAuth(clientId, clientSecret, params) {
645
+ params.set("client_id", clientId);
646
+ if (clientSecret) params.set("client_secret", clientSecret);
647
+ }
648
+ /**
649
+ * Applies public client authentication (RFC 6749 Section 2.1)
650
+ */
651
+ function applyPublicAuth(clientId, params) {
652
+ params.set("client_id", clientId);
653
+ }
654
+ /**
655
+ * Parses an OAuth error response from a string or Response object.
656
+ *
657
+ * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
658
+ * and an instance of the appropriate OAuthError subclass will be returned.
659
+ * If parsing fails, it falls back to a generic ServerError that includes
660
+ * the response status (if available) and original content.
661
+ *
662
+ * @param input - A Response object or string containing the error response
663
+ * @returns A Promise that resolves to an OAuthError instance
664
+ */
665
+ async function parseErrorResponse(input) {
666
+ const statusCode = input instanceof Response ? input.status : void 0;
667
+ const body = input instanceof Response ? await input.text() : input;
668
+ try {
669
+ const { error, error_description, error_uri } = OAuthErrorResponseSchema.parse(JSON.parse(body));
670
+ return new (OAUTH_ERRORS[error] || ServerError)(error_description || "", error_uri);
671
+ } catch (error) {
672
+ return new ServerError(`${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`);
673
+ }
674
+ }
675
+ /**
676
+ * Orchestrates the full auth flow with a server.
677
+ *
678
+ * This can be used as a single entry point for all authorization functionality,
679
+ * instead of linking together the other lower-level functions in this module.
680
+ */
681
+ async function auth(provider, options) {
682
+ try {
683
+ return await authInternal(provider, options);
684
+ } catch (error) {
685
+ if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
686
+ await provider.invalidateCredentials?.("all");
687
+ return await authInternal(provider, options);
688
+ } else if (error instanceof InvalidGrantError) {
689
+ await provider.invalidateCredentials?.("tokens");
690
+ return await authInternal(provider, options);
691
+ }
692
+ throw error;
693
+ }
694
+ }
695
+ async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
696
+ const cachedState = await provider.discoveryState?.();
697
+ let resourceMetadata;
698
+ let authorizationServerUrl;
699
+ let metadata;
700
+ let effectiveResourceMetadataUrl = resourceMetadataUrl;
701
+ if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
702
+ if (cachedState?.authorizationServerUrl) {
703
+ authorizationServerUrl = cachedState.authorizationServerUrl;
704
+ resourceMetadata = cachedState.resourceMetadata;
705
+ metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
706
+ if (!resourceMetadata) try {
707
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
708
+ } catch {}
709
+ if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) await provider.saveDiscoveryState?.({
710
+ authorizationServerUrl: String(authorizationServerUrl),
711
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
712
+ resourceMetadata,
713
+ authorizationServerMetadata: metadata
714
+ });
715
+ } else {
716
+ const serverInfo = await discoverOAuthServerInfo(serverUrl, {
717
+ resourceMetadataUrl: effectiveResourceMetadataUrl,
718
+ fetchFn
719
+ });
720
+ authorizationServerUrl = serverInfo.authorizationServerUrl;
721
+ metadata = serverInfo.authorizationServerMetadata;
722
+ resourceMetadata = serverInfo.resourceMetadata;
723
+ await provider.saveDiscoveryState?.({
724
+ authorizationServerUrl: String(authorizationServerUrl),
725
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
726
+ resourceMetadata,
727
+ authorizationServerMetadata: metadata
728
+ });
729
+ }
730
+ const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
731
+ const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
732
+ let clientInformation = await Promise.resolve(provider.clientInformation());
733
+ if (!clientInformation) {
734
+ if (authorizationCode !== void 0) throw new Error("Existing OAuth client information is required when exchanging an authorization code");
735
+ const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
736
+ const clientMetadataUrl = provider.clientMetadataUrl;
737
+ if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
738
+ if (supportsUrlBasedClientId && clientMetadataUrl) {
739
+ clientInformation = { client_id: clientMetadataUrl };
740
+ await provider.saveClientInformation?.(clientInformation);
741
+ } else {
742
+ if (!provider.saveClientInformation) throw new Error("OAuth client information must be saveable for dynamic registration");
743
+ const fullInformation = await registerClient(authorizationServerUrl, {
744
+ metadata,
745
+ clientMetadata: provider.clientMetadata,
746
+ scope: resolvedScope,
747
+ fetchFn
748
+ });
749
+ await provider.saveClientInformation(fullInformation);
750
+ clientInformation = fullInformation;
751
+ }
752
+ }
753
+ const nonInteractiveFlow = !provider.redirectUrl;
754
+ if (authorizationCode !== void 0 || nonInteractiveFlow) {
755
+ const tokens = await fetchToken(provider, authorizationServerUrl, {
756
+ metadata,
757
+ resource,
758
+ authorizationCode,
759
+ fetchFn
760
+ });
761
+ await provider.saveTokens(tokens);
762
+ return "AUTHORIZED";
763
+ }
764
+ const tokens = await provider.tokens();
765
+ if (tokens?.refresh_token) try {
766
+ const newTokens = await refreshAuthorization(authorizationServerUrl, {
767
+ metadata,
768
+ clientInformation,
769
+ refreshToken: tokens.refresh_token,
770
+ resource,
771
+ addClientAuthentication: provider.addClientAuthentication,
772
+ fetchFn
773
+ });
774
+ await provider.saveTokens(newTokens);
775
+ return "AUTHORIZED";
776
+ } catch (error) {
777
+ if (!(error instanceof OAuthError) || error instanceof ServerError) {} else throw error;
778
+ }
779
+ const state = provider.state ? await provider.state() : void 0;
780
+ const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
781
+ metadata,
782
+ clientInformation,
783
+ state,
784
+ redirectUrl: provider.redirectUrl,
785
+ scope: resolvedScope,
786
+ resource
787
+ });
788
+ await provider.saveCodeVerifier(codeVerifier);
789
+ await provider.redirectToAuthorization(authorizationUrl);
790
+ return "REDIRECT";
791
+ }
792
+ /**
793
+ * SEP-991: URL-based Client IDs
794
+ * Validate that the client_id is a valid URL with https scheme
795
+ */
796
+ function isHttpsUrl(value) {
797
+ if (!value) return false;
798
+ try {
799
+ const url = new URL(value);
800
+ return url.protocol === "https:" && url.pathname !== "/";
801
+ } catch {
802
+ return false;
803
+ }
804
+ }
805
+ async function selectResourceURL(serverUrl, provider, resourceMetadata) {
806
+ const defaultResource = resourceUrlFromServerUrl(serverUrl);
807
+ if (provider.validateResourceURL) return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
808
+ if (!resourceMetadata) return;
809
+ if (!checkResourceAllowed({
810
+ requestedResource: defaultResource,
811
+ configuredResource: resourceMetadata.resource
812
+ })) throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
813
+ return new URL(resourceMetadata.resource);
814
+ }
815
+ /**
816
+ * Extract resource_metadata, scope, and error from WWW-Authenticate header.
817
+ */
818
+ function extractWWWAuthenticateParams(res) {
819
+ const authenticateHeader = res.headers.get("WWW-Authenticate");
820
+ if (!authenticateHeader) return {};
821
+ const [type, scheme] = authenticateHeader.split(" ");
822
+ if (type.toLowerCase() !== "bearer" || !scheme) return {};
823
+ const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
824
+ let resourceMetadataUrl;
825
+ if (resourceMetadataMatch) try {
826
+ resourceMetadataUrl = new URL(resourceMetadataMatch);
827
+ } catch {}
828
+ const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
829
+ const error = extractFieldFromWwwAuth(res, "error") || void 0;
830
+ return {
831
+ resourceMetadataUrl,
832
+ scope,
833
+ error
834
+ };
835
+ }
836
+ /**
837
+ * Extracts a specific field's value from the WWW-Authenticate header string.
838
+ *
839
+ * @param response The HTTP response object containing the headers.
840
+ * @param fieldName The name of the field to extract (e.g., "realm", "nonce").
841
+ * @returns The field value
842
+ */
843
+ function extractFieldFromWwwAuth(response, fieldName) {
844
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
845
+ if (!wwwAuthHeader) return null;
846
+ const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
847
+ const match = wwwAuthHeader.match(pattern);
848
+ if (match) return match[1] || match[2];
849
+ return null;
850
+ }
851
+ /**
852
+ * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.
853
+ *
854
+ * If the server returns a 404 for the well-known endpoint, this function will
855
+ * return `undefined`. Any other errors will be thrown as exceptions.
856
+ */
857
+ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
858
+ const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
859
+ protocolVersion: opts?.protocolVersion,
860
+ metadataUrl: opts?.resourceMetadataUrl
861
+ });
862
+ if (!response || response.status === 404) {
863
+ await response?.body?.cancel();
864
+ throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
865
+ }
866
+ if (!response.ok) {
867
+ await response.body?.cancel();
868
+ throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
869
+ }
870
+ return OAuthProtectedResourceMetadataSchema.parse(await response.json());
871
+ }
872
+ /**
873
+ * Helper function to handle fetch with CORS retry logic
874
+ */
875
+ async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
876
+ try {
877
+ return await fetchFn(url, { headers });
878
+ } catch (error) {
879
+ if (error instanceof TypeError) if (headers) return fetchWithCorsRetry(url, void 0, fetchFn);
880
+ else return;
881
+ throw error;
882
+ }
883
+ }
884
+ /**
885
+ * Constructs the well-known path for auth-related metadata discovery
886
+ */
887
+ function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
888
+ if (pathname.endsWith("/")) pathname = pathname.slice(0, -1);
889
+ return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
890
+ }
891
+ /**
892
+ * Tries to discover OAuth metadata at a specific URL
893
+ */
894
+ async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
895
+ return await fetchWithCorsRetry(url, { "MCP-Protocol-Version": protocolVersion }, fetchFn);
896
+ }
897
+ /**
898
+ * Determines if fallback to root discovery should be attempted
899
+ */
900
+ function shouldAttemptFallback(response, pathname) {
901
+ return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
902
+ }
903
+ /**
904
+ * Generic function for discovering OAuth metadata with fallback support
905
+ */
906
+ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
907
+ const issuer = new URL(serverUrl);
908
+ const protocolVersion = opts?.protocolVersion ?? "2025-11-25";
909
+ let url;
910
+ if (opts?.metadataUrl) url = new URL(opts.metadataUrl);
911
+ else {
912
+ const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
913
+ url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
914
+ url.search = issuer.search;
915
+ }
916
+ let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);
917
+ if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) response = await tryMetadataDiscovery(new URL(`/.well-known/${wellKnownType}`, issuer), protocolVersion, fetchFn);
918
+ return response;
919
+ }
920
+ /**
921
+ * Builds a list of discovery URLs to try for authorization server metadata.
922
+ * URLs are returned in priority order:
923
+ * 1. OAuth metadata at the given URL
924
+ * 2. OIDC metadata endpoints at the given URL
925
+ */
926
+ function buildDiscoveryUrls(authorizationServerUrl) {
927
+ const url = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
928
+ const hasPath = url.pathname !== "/";
929
+ const urlsToTry = [];
930
+ if (!hasPath) {
931
+ urlsToTry.push({
932
+ url: new URL("/.well-known/oauth-authorization-server", url.origin),
933
+ type: "oauth"
934
+ });
935
+ urlsToTry.push({
936
+ url: new URL(`/.well-known/openid-configuration`, url.origin),
937
+ type: "oidc"
938
+ });
939
+ return urlsToTry;
940
+ }
941
+ let pathname = url.pathname;
942
+ if (pathname.endsWith("/")) pathname = pathname.slice(0, -1);
943
+ urlsToTry.push({
944
+ url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),
945
+ type: "oauth"
946
+ });
947
+ urlsToTry.push({
948
+ url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),
949
+ type: "oidc"
950
+ });
951
+ urlsToTry.push({
952
+ url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),
953
+ type: "oidc"
954
+ });
955
+ return urlsToTry;
956
+ }
957
+ /**
958
+ * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata
959
+ * and OpenID Connect Discovery 1.0 specifications.
960
+ *
961
+ * This function implements a fallback strategy for authorization server discovery:
962
+ * 1. Attempts RFC 8414 OAuth metadata discovery first
963
+ * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery
964
+ *
965
+ * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's
966
+ * protected resource metadata, or the MCP server's URL if the
967
+ * metadata was not found.
968
+ * @param options - Configuration options
969
+ * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch
970
+ * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION
971
+ * @returns Promise resolving to authorization server metadata, or undefined if discovery fails
972
+ */
973
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
974
+ const headers = {
975
+ "MCP-Protocol-Version": protocolVersion,
976
+ Accept: "application/json"
977
+ };
978
+ const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
979
+ for (const { url: endpointUrl, type } of urlsToTry) {
980
+ const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
981
+ if (!response)
982
+ /**
983
+ * CORS error occurred - don't throw as the endpoint may not allow CORS,
984
+ * continue trying other possible endpoints
985
+ */
986
+ continue;
987
+ if (!response.ok) {
988
+ await response.body?.cancel();
989
+ if (response.status >= 400 && response.status < 500) continue;
990
+ throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
991
+ }
992
+ if (type === "oauth") return OAuthMetadataSchema.parse(await response.json());
993
+ else return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
994
+ }
995
+ }
996
+ /**
997
+ * Discovers the authorization server for an MCP server following
998
+ * {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected
999
+ * Resource Metadata), with fallback to treating the server URL as the
1000
+ * authorization server.
1001
+ *
1002
+ * This function combines two discovery steps into one call:
1003
+ * 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the
1004
+ * authorization server URL (RFC 9728).
1005
+ * 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).
1006
+ *
1007
+ * Use this when you need the authorization server metadata for operations outside the
1008
+ * {@linkcode auth} orchestrator, such as token refresh or token revocation.
1009
+ *
1010
+ * @param serverUrl - The MCP resource server URL
1011
+ * @param opts - Optional configuration
1012
+ * @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint
1013
+ * @param opts.fetchFn - Custom fetch function for HTTP requests
1014
+ * @returns Authorization server URL, metadata, and resource metadata (if available)
1015
+ */
1016
+ async function discoverOAuthServerInfo(serverUrl, opts) {
1017
+ let resourceMetadata;
1018
+ let authorizationServerUrl;
1019
+ try {
1020
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
1021
+ if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) authorizationServerUrl = resourceMetadata.authorization_servers[0];
1022
+ } catch {}
1023
+ if (!authorizationServerUrl) authorizationServerUrl = String(new URL("/", serverUrl));
1024
+ const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
1025
+ return {
1026
+ authorizationServerUrl,
1027
+ authorizationServerMetadata,
1028
+ resourceMetadata
1029
+ };
1030
+ }
1031
+ /**
1032
+ * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.
1033
+ */
1034
+ async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
1035
+ let authorizationUrl;
1036
+ if (metadata) {
1037
+ authorizationUrl = new URL(metadata.authorization_endpoint);
1038
+ if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
1039
+ if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
1040
+ } else authorizationUrl = new URL("/authorize", authorizationServerUrl);
1041
+ const challenge = await pkceChallenge();
1042
+ const codeVerifier = challenge.code_verifier;
1043
+ const codeChallenge = challenge.code_challenge;
1044
+ authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE);
1045
+ authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
1046
+ authorizationUrl.searchParams.set("code_challenge", codeChallenge);
1047
+ authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
1048
+ authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
1049
+ if (state) authorizationUrl.searchParams.set("state", state);
1050
+ if (scope) authorizationUrl.searchParams.set("scope", scope);
1051
+ if (scope?.includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent");
1052
+ if (resource) authorizationUrl.searchParams.set("resource", resource.href);
1053
+ return {
1054
+ authorizationUrl,
1055
+ codeVerifier
1056
+ };
1057
+ }
1058
+ /**
1059
+ * Prepares token request parameters for an authorization code exchange.
1060
+ *
1061
+ * This is the default implementation used by fetchToken when the provider
1062
+ * doesn't implement prepareTokenRequest.
1063
+ *
1064
+ * @param authorizationCode - The authorization code received from the authorization endpoint
1065
+ * @param codeVerifier - The PKCE code verifier
1066
+ * @param redirectUri - The redirect URI used in the authorization request
1067
+ * @returns URLSearchParams for the authorization_code grant
1068
+ */
1069
+ function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
1070
+ return new URLSearchParams({
1071
+ grant_type: "authorization_code",
1072
+ code: authorizationCode,
1073
+ code_verifier: codeVerifier,
1074
+ redirect_uri: String(redirectUri)
1075
+ });
1076
+ }
1077
+ /**
1078
+ * Internal helper to execute a token request with the given parameters.
1079
+ * Used by exchangeAuthorization, refreshAuthorization, and fetchToken.
1080
+ */
1081
+ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
1082
+ const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
1083
+ const headers = new Headers({
1084
+ "Content-Type": "application/x-www-form-urlencoded",
1085
+ Accept: "application/json"
1086
+ });
1087
+ if (resource) tokenRequestParams.set("resource", resource.href);
1088
+ if (addClientAuthentication) await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
1089
+ else if (clientInformation) applyClientAuthentication(selectClientAuthMethod(clientInformation, metadata?.token_endpoint_auth_methods_supported ?? []), clientInformation, headers, tokenRequestParams);
1090
+ const response = await (fetchFn ?? fetch)(tokenUrl, {
1091
+ method: "POST",
1092
+ headers,
1093
+ body: tokenRequestParams
1094
+ });
1095
+ if (!response.ok) throw await parseErrorResponse(response);
1096
+ return OAuthTokensSchema.parse(await response.json());
1097
+ }
1098
+ /**
1099
+ * Exchange a refresh token for an updated access token.
1100
+ *
1101
+ * Supports multiple client authentication methods as specified in OAuth 2.1:
1102
+ * - Automatically selects the best authentication method based on server support
1103
+ * - Preserves the original refresh token if a new one is not returned
1104
+ *
1105
+ * @param authorizationServerUrl - The authorization server's base URL
1106
+ * @param options - Configuration object containing client info, refresh token, etc.
1107
+ * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)
1108
+ * @throws {Error} When token refresh fails or authentication is invalid
1109
+ */
1110
+ async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
1111
+ return {
1112
+ refresh_token: refreshToken,
1113
+ ...await executeTokenRequest(authorizationServerUrl, {
1114
+ metadata,
1115
+ tokenRequestParams: new URLSearchParams({
1116
+ grant_type: "refresh_token",
1117
+ refresh_token: refreshToken
1118
+ }),
1119
+ clientInformation,
1120
+ addClientAuthentication,
1121
+ resource,
1122
+ fetchFn
1123
+ })
1124
+ };
1125
+ }
1126
+ /**
1127
+ * Unified token fetching that works with any grant type via provider.prepareTokenRequest().
1128
+ *
1129
+ * This function provides a single entry point for obtaining tokens regardless of the
1130
+ * OAuth grant type. The provider's prepareTokenRequest() method determines which grant
1131
+ * to use and supplies the grant-specific parameters.
1132
+ *
1133
+ * @param provider - OAuth client provider that implements prepareTokenRequest()
1134
+ * @param authorizationServerUrl - The authorization server's base URL
1135
+ * @param options - Configuration for the token request
1136
+ * @returns Promise resolving to OAuth tokens
1137
+ * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails
1138
+ *
1139
+ * @example
1140
+ * // Provider for client_credentials:
1141
+ * class MyProvider implements OAuthClientProvider {
1142
+ * prepareTokenRequest(scope) {
1143
+ * const params = new URLSearchParams({ grant_type: 'client_credentials' });
1144
+ * if (scope) params.set('scope', scope);
1145
+ * return params;
1146
+ * }
1147
+ * // ... other methods
1148
+ * }
1149
+ *
1150
+ * const tokens = await fetchToken(provider, authServerUrl, { metadata });
1151
+ */
1152
+ async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
1153
+ const scope = provider.clientMetadata.scope;
1154
+ let tokenRequestParams;
1155
+ if (provider.prepareTokenRequest) tokenRequestParams = await provider.prepareTokenRequest(scope);
1156
+ if (!tokenRequestParams) {
1157
+ if (!authorizationCode) throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
1158
+ if (!provider.redirectUrl) throw new Error("redirectUrl is required for authorization_code flow");
1159
+ tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, await provider.codeVerifier(), provider.redirectUrl);
1160
+ }
1161
+ const clientInformation = await provider.clientInformation();
1162
+ return executeTokenRequest(authorizationServerUrl, {
1163
+ metadata,
1164
+ tokenRequestParams,
1165
+ clientInformation: clientInformation ?? void 0,
1166
+ addClientAuthentication: provider.addClientAuthentication,
1167
+ resource,
1168
+ fetchFn
1169
+ });
1170
+ }
1171
+ /**
1172
+ * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.
1173
+ *
1174
+ * If `scope` is provided, it overrides `clientMetadata.scope` in the registration
1175
+ * request body. This allows callers to apply the Scope Selection Strategy (SEP-835)
1176
+ * consistently across both DCR and the subsequent authorization request.
1177
+ */
1178
+ async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {
1179
+ let registrationUrl;
1180
+ if (metadata) {
1181
+ if (!metadata.registration_endpoint) throw new Error("Incompatible auth server: does not support dynamic client registration");
1182
+ registrationUrl = new URL(metadata.registration_endpoint);
1183
+ } else registrationUrl = new URL("/register", authorizationServerUrl);
1184
+ const response = await (fetchFn ?? fetch)(registrationUrl, {
1185
+ method: "POST",
1186
+ headers: { "Content-Type": "application/json" },
1187
+ body: JSON.stringify({
1188
+ ...clientMetadata,
1189
+ ...scope !== void 0 ? { scope } : {}
1190
+ })
1191
+ });
1192
+ if (!response.ok) throw await parseErrorResponse(response);
1193
+ return OAuthClientInformationFullSchema.parse(await response.json());
1194
+ }
1195
+ //#endregion
1196
+ export { normalizeHeaders as a, createFetchWithInit as i, auth as n, createParser as o, extractWWWAuthenticateParams as r, UnauthorizedError as t };