@vite-hub/source 0.0.2 → 0.0.4

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