@vite-hub/source 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +219 -82
  2. package/dist/{auth-Ddw55OUG.js → auth-B-tX_rp0.js} +255 -90
  3. package/dist/{client-CDfTmtQu.js → client-BwstxtdY.js} +584 -207
  4. package/dist/client.d.ts +27 -10
  5. package/dist/client.js +71 -13
  6. package/dist/collection-B_4w_J8h.d.ts +257 -0
  7. package/dist/{collection-B8pXGM2d.js → collection-cursor-WzV1Jd6v.js} +37 -54
  8. package/dist/collection-route-BplWPxHR.js +10 -0
  9. package/dist/drizzle.d.ts +41 -0
  10. package/dist/drizzle.js +89 -0
  11. package/dist/error-diagnostics-X0kuFjBT.js +51 -0
  12. package/dist/file-BX0FSvgE.js +60 -0
  13. package/dist/{file-EQ3AjVM6.d.ts → file-DadN9dbN.d.ts} +2 -3
  14. package/dist/file.d.ts +1 -1
  15. package/dist/file.js +1 -1
  16. package/dist/files.d.ts +15 -0
  17. package/dist/files.js +38 -0
  18. package/dist/github.d.ts +8 -5
  19. package/dist/github.js +725 -426
  20. package/dist/glob-BmFqTvJY.js +993 -0
  21. package/dist/glob.d.ts +12 -4
  22. package/dist/glob.js +1 -894
  23. package/dist/index.d.ts +118 -27
  24. package/dist/index.js +623 -14
  25. package/dist/markdown.d.ts +4 -6
  26. package/dist/markdown.js +2 -2
  27. package/dist/mcp.d.ts +3 -4
  28. package/dist/mcp.js +302 -5920
  29. package/dist/{file-BSWQg9Qv.js → mrmime-40h5OOIp.js} +1 -56
  30. package/dist/{path-CUhvUREm.js → path-BS8rYm0n.js} +60 -40
  31. package/dist/{path-BzmU4Eni.js → path-DOBpV8ol.js} +3 -7
  32. package/dist/server.d.ts +256 -6
  33. package/dist/server.js +90 -12
  34. package/dist/{sse-CE9Q2JqM.js → sse-D9gqqNPj.js} +50 -9
  35. package/dist/{streamableHttp-BszaXLmg.js → streamableHttp-BL-E7pl5.js} +40 -22
  36. package/dist/types-BigOktIj.d.ts +93 -0
  37. package/dist/{types-AIBmt_m6.js → types-CoWcW8oz.js} +2502 -1187
  38. package/dist/vite.d.ts +134 -13
  39. package/dist/vite.js +1734 -79
  40. package/package.json +55 -36
  41. package/dist/collection-CF2ON__k.d.ts +0 -92
  42. package/dist/collection-route-Dw7QLFyx.js +0 -6
  43. package/dist/content/client.d.ts +0 -3
  44. package/dist/content/client.js +0 -2
  45. package/dist/content.d.ts +0 -44
  46. package/dist/content.js +0 -157
  47. package/dist/registry-C8skfCSV.js +0 -120
  48. package/dist/types-Bu3WvNX9.d.ts +0 -71
@@ -1,5 +1,5 @@
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
1
+ import { $ as number$1, J as any, Q as looseObject, S as LATEST_PROTOCOL_VERSION, X as boolean, Y as array, Z as literal, at as NEVER, et as object, nt as url, q as ZodNumber, rt as _coercedNumber, tt as string } from "./types-CoWcW8oz.js";
2
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/compat.js
3
3
  /** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
4
4
  const ZodIssueCode = {
5
5
  invalid_type: "invalid_type",
@@ -18,18 +18,20 @@ const ZodIssueCode = {
18
18
  var ZodFirstPartyTypeKind;
19
19
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
20
20
  //#endregion
21
- //#region ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js
21
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/coerce.js
22
22
  function number(params) {
23
23
  return _coercedNumber(ZodNumber, params);
24
24
  }
25
25
  //#endregion
26
- //#region ../../node_modules/.pnpm/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/index.js
26
+ //#region ../../node_modules/.pnpm/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/index.js
27
27
  var ParseError = class extends Error {
28
28
  constructor(message, options) {
29
29
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
30
30
  }
31
31
  };
32
- const LF = 10, CR = 13, SPACE = 32;
32
+ const LF = 10;
33
+ const CR = 13;
34
+ const SPACE = 32;
33
35
  function noop(_arg) {}
34
36
  function createParser(config) {
35
37
  if (typeof config == "function") throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
@@ -118,11 +120,14 @@ ${value2}`, dataLines++;
118
120
  }
119
121
  if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
120
122
  const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
121
- id = value2.includes("\0") ? void 0 : value2;
123
+ value2.includes("\0") || (id = value2);
122
124
  return;
123
125
  }
124
126
  if (firstCharCode === 58) {
125
- if (onComment) onComment(chunk.slice(start, end).slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
127
+ if (onComment) {
128
+ const line2 = chunk.slice(start, end);
129
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
130
+ }
126
131
  return;
127
132
  }
128
133
  const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
@@ -143,7 +148,7 @@ ${value2}`, dataLines++;
143
148
  ${value}`, dataLines++;
144
149
  break;
145
150
  case "id":
146
- id = value.includes("\0") ? void 0 : value;
151
+ value.includes("\0") || (id = value);
147
152
  break;
148
153
  case "retry":
149
154
  /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
@@ -152,14 +157,12 @@ ${value}`, dataLines++;
152
157
  line
153
158
  }));
154
159
  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;
160
+ default: onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
161
+ type: "unknown-field",
162
+ field,
163
+ value,
164
+ line
165
+ }));
163
166
  }
164
167
  }
165
168
  function dispatchEvent() {
@@ -188,7 +191,7 @@ function isEventPrefix(chunk, i, firstCharCode) {
188
191
  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
192
  }
190
193
  //#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
194
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
192
195
  /**
193
196
  * Normalizes HeadersInit to a plain Record<string, string> for manipulation.
194
197
  * Handles Headers objects, arrays of tuples, and plain objects.
@@ -220,6 +223,70 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
220
223
  });
221
224
  };
222
225
  }
226
+ const MAX_REDIRECTS = 5;
227
+ const REDIRECT_STATUSES = [
228
+ 301,
229
+ 302,
230
+ 303,
231
+ 307,
232
+ 308
233
+ ];
234
+ /** @internal Whether `to` has the scheme, host and port of `from`, or is its https form with both on default ports. */
235
+ function isWithinOrigin(from, to) {
236
+ if (from.protocol === to.protocol && from.hostname === to.hostname && from.port === to.port) return true;
237
+ return from.hostname === to.hostname && from.protocol === "http:" && from.port === "" && to.protocol === "https:" && to.port === "";
238
+ }
239
+ function redirectTarget(response, requestUrl) {
240
+ const location = REDIRECT_STATUSES.includes(response.status) ? response.headers.get("location") : null;
241
+ try {
242
+ return location ? new URL(location, requestUrl) : void 0;
243
+ } catch {
244
+ return;
245
+ }
246
+ }
247
+ /** @internal Follows the redirect in `response` while it stays within the origin of `url`; undefined when `response` is to be used as is. */
248
+ function followWithinOrigin(baseFetch, url, init, response, followed = 0) {
249
+ const target = redirectTarget(response, url);
250
+ const keepsMethod = response.status === 307 || response.status === 308 || (init?.method ?? "GET").toUpperCase() === "GET";
251
+ if (!target || followed === MAX_REDIRECTS || !keepsMethod) return;
252
+ const from = new URL(url);
253
+ if ((target.username || target.password) && (target.username !== from.username || target.password !== from.password) || !isWithinOrigin(from, target)) return;
254
+ return Promise.resolve(response.body?.cancel()).then(() => baseFetch(target, {
255
+ ...init,
256
+ redirect: "manual"
257
+ })).then((next) => followWithinOrigin(baseFetch, target, init, next, followed + 1) ?? next);
258
+ }
259
+ const followingFetches = /* @__PURE__ */ new WeakSet();
260
+ /** @internal Wraps a fetch for `redirectPolicy: 'follow'`: `fetchWithinOrigin` returns the result as it is, so redirects are left to the fetch. */
261
+ function fetchLeavingRedirects(baseFetch) {
262
+ const following = (url, init) => (baseFetch ?? fetch)(url, init);
263
+ followingFetches.add(following);
264
+ return following;
265
+ }
266
+ /** @internal Wraps a fetch so it follows a redirect only within the request's origin; any other redirect response is returned as is. */
267
+ function fetchWithinOrigin(baseFetch = fetch) {
268
+ if (followingFetches.has(baseFetch)) return baseFetch;
269
+ return (url, init) => {
270
+ if (init?.redirect === "error" || init?.redirect === "manual") return baseFetch(url, init);
271
+ return Promise.resolve(baseFetch(url, {
272
+ ...init,
273
+ redirect: "manual"
274
+ })).then((response) => followWithinOrigin(baseFetch, url, init, response) ?? response);
275
+ };
276
+ }
277
+ /** @internal Describes a redirect that `fetchWithinOrigin` returned unfollowed, naming its target without userinfo, query or fragment. */
278
+ function unfollowedRedirect(response, requestUrl) {
279
+ if (response.type === "opaqueredirect") return "Redirect not followed: this runtime does not expose the redirect target";
280
+ const from = response.url || requestUrl;
281
+ const target = redirectTarget(response, from);
282
+ if (!target) return;
283
+ target.username = target.password = target.search = target.hash = "";
284
+ if (target.protocol === "http:" && new URL(from).protocol === "https:") {
285
+ target.protocol = "https:";
286
+ return `Redirect to plain http not followed; try ${target.href} instead`;
287
+ }
288
+ return `Redirect to ${target.href} not followed`;
289
+ }
223
290
  //#endregion
224
291
  //#region ../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
225
292
  let crypto;
@@ -275,7 +342,7 @@ async function pkceChallenge(length) {
275
342
  };
276
343
  }
277
344
  //#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
345
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
279
346
  /**
280
347
  * Reusable URL validation that disallows javascript: scheme
281
348
  */
@@ -336,49 +403,54 @@ const OAuthMetadataSchema = looseObject({
336
403
  client_id_metadata_document_supported: boolean().optional()
337
404
  });
338
405
  /**
406
+ * OpenID Connect Discovery 1.0 Provider Metadata
407
+ * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
408
+ */
409
+ const OpenIdProviderMetadataSchema = looseObject({
410
+ issuer: string(),
411
+ authorization_endpoint: SafeUrlSchema,
412
+ token_endpoint: SafeUrlSchema,
413
+ userinfo_endpoint: SafeUrlSchema.optional(),
414
+ jwks_uri: SafeUrlSchema,
415
+ registration_endpoint: SafeUrlSchema.optional(),
416
+ scopes_supported: array(string()).optional(),
417
+ response_types_supported: array(string()),
418
+ response_modes_supported: array(string()).optional(),
419
+ grant_types_supported: array(string()).optional(),
420
+ acr_values_supported: array(string()).optional(),
421
+ subject_types_supported: array(string()),
422
+ id_token_signing_alg_values_supported: array(string()),
423
+ id_token_encryption_alg_values_supported: array(string()).optional(),
424
+ id_token_encryption_enc_values_supported: array(string()).optional(),
425
+ userinfo_signing_alg_values_supported: array(string()).optional(),
426
+ userinfo_encryption_alg_values_supported: array(string()).optional(),
427
+ userinfo_encryption_enc_values_supported: array(string()).optional(),
428
+ request_object_signing_alg_values_supported: array(string()).optional(),
429
+ request_object_encryption_alg_values_supported: array(string()).optional(),
430
+ request_object_encryption_enc_values_supported: array(string()).optional(),
431
+ token_endpoint_auth_methods_supported: array(string()).optional(),
432
+ token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
433
+ display_values_supported: array(string()).optional(),
434
+ claim_types_supported: array(string()).optional(),
435
+ claims_supported: array(string()).optional(),
436
+ service_documentation: string().optional(),
437
+ claims_locales_supported: array(string()).optional(),
438
+ ui_locales_supported: array(string()).optional(),
439
+ claims_parameter_supported: boolean().optional(),
440
+ request_parameter_supported: boolean().optional(),
441
+ request_uri_parameter_supported: boolean().optional(),
442
+ require_request_uri_registration: boolean().optional(),
443
+ op_policy_uri: SafeUrlSchema.optional(),
444
+ op_tos_uri: SafeUrlSchema.optional(),
445
+ client_id_metadata_document_supported: boolean().optional()
446
+ });
447
+ /**
339
448
  * OpenID Connect Discovery metadata that may include OAuth 2.0 fields
340
449
  * This schema represents the real-world scenario where OIDC providers
341
450
  * return a mix of OpenID Connect and OAuth 2.0 metadata fields
342
451
  */
343
452
  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,
453
+ ...OpenIdProviderMetadataSchema.shape,
382
454
  ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape
383
455
  });
384
456
  /**
@@ -390,7 +462,12 @@ const OAuthTokensSchema = object({
390
462
  token_type: string(),
391
463
  expires_in: number().optional(),
392
464
  scope: string().optional(),
393
- refresh_token: string().optional()
465
+ refresh_token: string().optional(),
466
+ /**
467
+ * Not part of the wire format: the authorization server this value was obtained from, added by
468
+ * the client's `auth()` before it is stored and compared when it is read back.
469
+ */
470
+ issuer: string().optional().catch(void 0)
394
471
  }).strip();
395
472
  /**
396
473
  * OAuth 2.1 error response
@@ -432,7 +509,12 @@ const OAuthClientInformationSchema = object({
432
509
  client_id: string(),
433
510
  client_secret: string().optional(),
434
511
  client_id_issued_at: number$1().optional(),
435
- client_secret_expires_at: number$1().optional()
512
+ client_secret_expires_at: number$1().optional(),
513
+ /**
514
+ * Not part of the wire format: the authorization server this value was obtained from, added by
515
+ * the client's `auth()` before it is stored and compared when it is read back.
516
+ */
517
+ issuer: string().optional().catch(void 0)
436
518
  }).strip();
437
519
  /**
438
520
  * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)
@@ -447,7 +529,7 @@ object({
447
529
  token_type_hint: string().optional()
448
530
  }).strip();
449
531
  //#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
532
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
451
533
  /**
452
534
  * Utilities for handling OAuth resource URIs.
453
535
  */
@@ -480,7 +562,7 @@ function checkResourceAllowed({ requestedResource, configuredResource }) {
480
562
  return requestedPath.startsWith(configuredPath);
481
563
  }
482
564
  //#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
565
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
484
566
  /**
485
567
  * Base class for all OAuth errors
486
568
  */
@@ -630,7 +712,7 @@ const OAUTH_ERRORS = {
630
712
  [InvalidTargetError.errorCode]: InvalidTargetError
631
713
  };
632
714
  //#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
715
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
634
716
  var UnauthorizedError = class extends Error {
635
717
  constructor(message) {
636
718
  super(message ?? "Unauthorized");
@@ -734,10 +816,42 @@ async function parseErrorResponse(input) {
734
816
  const { error, error_description, error_uri } = OAuthErrorResponseSchema.parse(JSON.parse(body));
735
817
  return new (OAUTH_ERRORS[error] || ServerError)(error_description || "", error_uri);
736
818
  } catch (error) {
737
- return new ServerError(`${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`);
819
+ const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
820
+ return new ServerError(`${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error}. Raw body: ${body}`}`);
738
821
  }
739
822
  }
740
823
  /**
824
+ * Compares two authorization server identifiers, tolerating a single trailing `/`
825
+ * difference (`String(new URL(...))` is slash-suffixed, advertised values often are not).
826
+ */
827
+ function issuersMatch(a, b) {
828
+ let [x, y] = [a, b];
829
+ try {
830
+ [x, y] = [new URL(a).href, new URL(b).href];
831
+ } catch {}
832
+ return x === y || x.endsWith("/") && x.slice(0, -1) === y || y.endsWith("/") && y.slice(0, -1) === x;
833
+ }
834
+ /**
835
+ * {@linkcode auth} stamps everything it passes to `saveClientInformation` / `saveTokens` with
836
+ * `issuer`, the authorization server URL used for discovery. This returns `stored` unless its
837
+ * stamp names a different authorization server, in which case the caller behaves as if nothing
838
+ * were stored. A value without a stamp (saved by an earlier version) is returned as-is, and
839
+ * is stamped once this authorization server has accepted it.
840
+ */
841
+ function discardIfIssuerMismatch(stored, issuer) {
842
+ if (!stored) return void 0;
843
+ if (typeof stored.issuer !== "string") return stored.issuer == null ? stored : {
844
+ ...stored,
845
+ issuer: void 0
846
+ };
847
+ return issuersMatch(stored.issuer, issuer) ? stored : void 0;
848
+ }
849
+ const TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });
850
+ const RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });
851
+ function boundElsewhereError(stored, issuer) {
852
+ return /* @__PURE__ */ new Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`);
853
+ }
854
+ /**
741
855
  * Orchestrates the full auth flow with a server.
742
856
  *
743
857
  * This can be used as a single entry point for all authorization functionality,
@@ -792,27 +906,46 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
792
906
  authorizationServerMetadata: metadata
793
907
  });
794
908
  }
795
- const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
909
+ const issuer = String(authorizationServerUrl);
910
+ const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
911
+ const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
796
912
  const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
797
- let clientInformation = await Promise.resolve(provider.clientInformation());
913
+ const storedClientInformation = await Promise.resolve(provider.clientInformation());
914
+ let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);
915
+ const canRegisterAgain = provider.saveClientInformation !== void 0 && !!provider.redirectUrl;
916
+ if (storedClientInformation && !clientInformation && !canRegisterAgain) throw boundElsewhereError(storedClientInformation, issuer);
917
+ const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : void 0;
918
+ const bindClientInformation = async () => {
919
+ try {
920
+ if (unstampedClientInformation) await provider.saveClientInformation?.({
921
+ ...unstampedClientInformation,
922
+ issuer
923
+ });
924
+ } catch {}
925
+ };
798
926
  if (!clientInformation) {
799
927
  if (authorizationCode !== void 0) throw new Error("Existing OAuth client information is required when exchanging an authorization code");
800
928
  const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
801
929
  const clientMetadataUrl = provider.clientMetadataUrl;
802
930
  if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
803
931
  if (supportsUrlBasedClientId && clientMetadataUrl) {
804
- clientInformation = { client_id: clientMetadataUrl };
932
+ clientInformation = {
933
+ client_id: clientMetadataUrl,
934
+ issuer
935
+ };
805
936
  await provider.saveClientInformation?.(clientInformation);
806
937
  } else {
807
938
  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;
939
+ clientInformation = {
940
+ ...await registerClient(authorizationServerUrl, {
941
+ metadata,
942
+ clientMetadata: provider.clientMetadata,
943
+ scope: resolvedScope,
944
+ fetchFn
945
+ }),
946
+ issuer
947
+ };
948
+ await provider.saveClientInformation(clientInformation);
816
949
  }
817
950
  }
818
951
  const nonInteractiveFlow = !provider.redirectUrl;
@@ -823,10 +956,15 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
823
956
  authorizationCode,
824
957
  fetchFn
825
958
  });
826
- await provider.saveTokens(tokens);
959
+ await bindClientInformation();
960
+ await provider.saveTokens({
961
+ ...tokens,
962
+ issuer
963
+ });
827
964
  return "AUTHORIZED";
828
965
  }
829
- const tokens = await provider.tokens();
966
+ const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
967
+ if (tokens?.refresh_token && tokens.issuer == null) console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");
830
968
  if (tokens?.refresh_token) try {
831
969
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
832
970
  metadata,
@@ -836,7 +974,11 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
836
974
  addClientAuthentication: provider.addClientAuthentication,
837
975
  fetchFn
838
976
  });
839
- await provider.saveTokens(newTokens);
977
+ await bindClientInformation();
978
+ await provider.saveTokens({
979
+ ...newTokens,
980
+ issuer
981
+ });
840
982
  return "AUTHORIZED";
841
983
  } catch (error) {
842
984
  if (!(error instanceof OAuthError) || error instanceof ServerError) {} else throw error;
@@ -867,6 +1009,17 @@ function isHttpsUrl(value) {
867
1009
  return false;
868
1010
  }
869
1011
  }
1012
+ /**
1013
+ * Selects the RFC 8707 resource indicator for an MCP server: the provider's
1014
+ * {@linkcode OAuthClientProvider.validateResourceURL | validateResourceURL} result when
1015
+ * implemented, otherwise the protected resource metadata's `resource` (checked against the
1016
+ * server URL with `checkResourceAllowed`), or `undefined` when there is no metadata.
1017
+ *
1018
+ * The result is a parsed `URL`, so a pathless indicator such as `https://example.com` has
1019
+ * the `href` `https://example.com/`. {@linkcode auth} therefore sends the metadata string
1020
+ * verbatim instead of this URL's `href` (#1968); callers that emit the `resource`
1021
+ * parameter themselves should do the same.
1022
+ */
870
1023
  async function selectResourceURL(serverUrl, provider, resourceMetadata) {
871
1024
  const defaultResource = resourceUrlFromServerUrl(serverUrl);
872
1025
  if (provider.validateResourceURL) return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
@@ -939,10 +1092,12 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
939
1092
  */
940
1093
  async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
941
1094
  try {
942
- return await fetchFn(url, { headers });
1095
+ return await fetchWithinOrigin(fetchFn)(url, { headers });
943
1096
  } catch (error) {
944
- if (error instanceof TypeError) if (headers) return fetchWithCorsRetry(url, void 0, fetchFn);
945
- else return;
1097
+ if (error instanceof TypeError) {
1098
+ if (headers) return fetchWithCorsRetry(url, void 0, fetchFn);
1099
+ else return;
1100
+ }
946
1101
  throw error;
947
1102
  }
948
1103
  }
@@ -963,7 +1118,7 @@ async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
963
1118
  * Determines if fallback to root discovery should be attempted
964
1119
  */
965
1120
  function shouldAttemptFallback(response, pathname) {
966
- return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
1121
+ return !response || !response.ok && response.status < 500 && pathname !== "/";
967
1122
  }
968
1123
  /**
969
1124
  * Generic function for discovering OAuth metadata with fallback support
@@ -1051,7 +1206,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
1051
1206
  continue;
1052
1207
  if (!response.ok) {
1053
1208
  await response.body?.cancel();
1054
- if (response.status >= 400 && response.status < 500) continue;
1209
+ if (response.status < 500) continue;
1055
1210
  throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
1056
1211
  }
1057
1212
  if (type === "oauth") return OAuthMetadataSchema.parse(await response.json());
@@ -1093,6 +1248,9 @@ async function discoverOAuthServerInfo(serverUrl, opts) {
1093
1248
  resourceMetadata
1094
1249
  };
1095
1250
  }
1251
+ function resourceIndicatorToString(resource) {
1252
+ return typeof resource === "string" ? resource : resource.href;
1253
+ }
1096
1254
  /**
1097
1255
  * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.
1098
1256
  */
@@ -1114,7 +1272,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
1114
1272
  if (state) authorizationUrl.searchParams.set("state", state);
1115
1273
  if (scope) authorizationUrl.searchParams.set("scope", scope);
1116
1274
  if (scope?.includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent");
1117
- if (resource) authorizationUrl.searchParams.set("resource", resource.href);
1275
+ if (resource) authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
1118
1276
  return {
1119
1277
  authorizationUrl,
1120
1278
  codeVerifier
@@ -1149,16 +1307,16 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
1149
1307
  "Content-Type": "application/x-www-form-urlencoded",
1150
1308
  Accept: "application/json"
1151
1309
  });
1152
- if (resource) tokenRequestParams.set("resource", resource.href);
1310
+ if (resource) tokenRequestParams.set("resource", resourceIndicatorToString(resource));
1153
1311
  if (addClientAuthentication) await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
1154
1312
  else if (clientInformation) applyClientAuthentication(selectClientAuthMethod(clientInformation, metadata?.token_endpoint_auth_methods_supported ?? []), clientInformation, headers, tokenRequestParams);
1155
- const response = await (fetchFn ?? fetch)(tokenUrl, {
1313
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {
1156
1314
  method: "POST",
1157
1315
  headers,
1158
1316
  body: tokenRequestParams
1159
1317
  });
1160
1318
  if (!response.ok) throw await parseErrorResponse(response);
1161
- return OAuthTokensSchema.parse(await response.json());
1319
+ return TokenResponseSchema.parse(await response.json());
1162
1320
  }
1163
1321
  /**
1164
1322
  * Exchange a refresh token for an updated access token.
@@ -1215,6 +1373,13 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
1215
1373
  * const tokens = await fetchToken(provider, authServerUrl, { metadata });
1216
1374
  */
1217
1375
  async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
1376
+ const readClientInformation = async () => {
1377
+ const storedClientInformation = await provider.clientInformation();
1378
+ const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
1379
+ if (storedClientInformation && !checked) throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
1380
+ return checked;
1381
+ };
1382
+ let clientInformation = await readClientInformation();
1218
1383
  const scope = provider.clientMetadata.scope;
1219
1384
  let tokenRequestParams;
1220
1385
  if (provider.prepareTokenRequest) tokenRequestParams = await provider.prepareTokenRequest(scope);
@@ -1223,11 +1388,11 @@ async function fetchToken(provider, authorizationServerUrl, { metadata, resource
1223
1388
  if (!provider.redirectUrl) throw new Error("redirectUrl is required for authorization_code flow");
1224
1389
  tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, await provider.codeVerifier(), provider.redirectUrl);
1225
1390
  }
1226
- const clientInformation = await provider.clientInformation();
1391
+ clientInformation ?? (clientInformation = await readClientInformation());
1227
1392
  return executeTokenRequest(authorizationServerUrl, {
1228
1393
  metadata,
1229
1394
  tokenRequestParams,
1230
- clientInformation: clientInformation ?? void 0,
1395
+ clientInformation,
1231
1396
  addClientAuthentication: provider.addClientAuthentication,
1232
1397
  resource,
1233
1398
  fetchFn
@@ -1246,7 +1411,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
1246
1411
  if (!metadata.registration_endpoint) throw new Error("Incompatible auth server: does not support dynamic client registration");
1247
1412
  registrationUrl = new URL(metadata.registration_endpoint);
1248
1413
  } else registrationUrl = new URL("/register", authorizationServerUrl);
1249
- const response = await (fetchFn ?? fetch)(registrationUrl, {
1414
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {
1250
1415
  method: "POST",
1251
1416
  headers: { "Content-Type": "application/json" },
1252
1417
  body: JSON.stringify({
@@ -1255,7 +1420,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
1255
1420
  })
1256
1421
  });
1257
1422
  if (!response.ok) throw await parseErrorResponse(response);
1258
- return OAuthClientInformationFullSchema.parse(await response.json());
1423
+ return RegistrationResponseSchema.parse(await response.json());
1259
1424
  }
1260
1425
  //#endregion
1261
- export { normalizeHeaders as a, createFetchWithInit as i, auth as n, createParser as o, extractWWWAuthenticateParams as r, UnauthorizedError as t };
1426
+ export { fetchLeavingRedirects as a, normalizeHeaders as c, createFetchWithInit as i, unfollowedRedirect as l, auth as n, fetchWithinOrigin as o, extractWWWAuthenticateParams as r, followWithinOrigin as s, UnauthorizedError as t, createParser as u };