@mcp-z/client 1.2.1 → 1.3.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 (95) hide show
  1. package/README.md +22 -0
  2. package/dist/cjs/auth/capability-discovery.js +16 -6
  3. package/dist/cjs/auth/capability-discovery.js.map +1 -1
  4. package/dist/cjs/auth/discovery-fetch.d.cts +22 -2
  5. package/dist/cjs/auth/discovery-fetch.d.ts +22 -2
  6. package/dist/cjs/auth/discovery-fetch.js +440 -124
  7. package/dist/cjs/auth/discovery-fetch.js.map +1 -1
  8. package/dist/cjs/auth/interactive-oauth-flow.d.cts +9 -2
  9. package/dist/cjs/auth/interactive-oauth-flow.d.ts +9 -2
  10. package/dist/cjs/auth/interactive-oauth-flow.js +29 -11
  11. package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
  12. package/dist/cjs/auth/oauth-callback-listener.js +4 -0
  13. package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
  14. package/dist/cjs/auth/types.d.cts +29 -4
  15. package/dist/cjs/auth/types.d.ts +29 -4
  16. package/dist/cjs/auth/types.js.map +1 -1
  17. package/dist/cjs/client-helpers.d.cts +5 -6
  18. package/dist/cjs/client-helpers.d.ts +5 -6
  19. package/dist/cjs/client-helpers.js +8 -8
  20. package/dist/cjs/client-helpers.js.map +1 -1
  21. package/dist/cjs/connection/connect-client.d.cts +12 -11
  22. package/dist/cjs/connection/connect-client.d.ts +12 -11
  23. package/dist/cjs/connection/connect-client.js +31 -47
  24. package/dist/cjs/connection/connect-client.js.map +1 -1
  25. package/dist/cjs/connection/existing-process-transport.d.cts +1 -2
  26. package/dist/cjs/connection/existing-process-transport.d.ts +1 -2
  27. package/dist/cjs/connection/existing-process-transport.js +3 -3
  28. package/dist/cjs/connection/existing-process-transport.js.map +1 -1
  29. package/dist/cjs/dcr/dcr-authenticator.d.cts +36 -5
  30. package/dist/cjs/dcr/dcr-authenticator.d.ts +36 -5
  31. package/dist/cjs/dcr/dcr-authenticator.js +473 -62
  32. package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
  33. package/dist/cjs/dcr/dynamic-client-registrar.d.cts +2 -2
  34. package/dist/cjs/dcr/dynamic-client-registrar.d.ts +2 -2
  35. package/dist/cjs/dcr/dynamic-client-registrar.js +10 -11
  36. package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
  37. package/dist/cjs/index.d.cts +2 -0
  38. package/dist/cjs/index.d.ts +2 -0
  39. package/dist/cjs/index.js +8 -2
  40. package/dist/cjs/index.js.map +1 -1
  41. package/dist/cjs/lib/url-utils.d.cts +17 -0
  42. package/dist/cjs/lib/url-utils.d.ts +17 -0
  43. package/dist/cjs/lib/url-utils.js +22 -2
  44. package/dist/cjs/lib/url-utils.js.map +1 -1
  45. package/dist/cjs/response-wrappers.d.cts +1 -1
  46. package/dist/cjs/response-wrappers.d.ts +1 -1
  47. package/dist/cjs/response-wrappers.js.map +1 -1
  48. package/dist/cjs/search/search.d.cts +1 -1
  49. package/dist/cjs/search/search.d.ts +1 -1
  50. package/dist/cjs/search/search.js.map +1 -1
  51. package/dist/esm/auth/capability-discovery.js +16 -6
  52. package/dist/esm/auth/capability-discovery.js.map +1 -1
  53. package/dist/esm/auth/discovery-fetch.d.ts +22 -2
  54. package/dist/esm/auth/discovery-fetch.js +234 -54
  55. package/dist/esm/auth/discovery-fetch.js.map +1 -1
  56. package/dist/esm/auth/interactive-oauth-flow.d.ts +9 -2
  57. package/dist/esm/auth/interactive-oauth-flow.js +28 -10
  58. package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
  59. package/dist/esm/auth/oauth-callback-listener.js +4 -0
  60. package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
  61. package/dist/esm/auth/types.d.ts +29 -4
  62. package/dist/esm/auth/types.js.map +1 -1
  63. package/dist/esm/client-helpers.d.ts +5 -6
  64. package/dist/esm/client-helpers.js +8 -8
  65. package/dist/esm/client-helpers.js.map +1 -1
  66. package/dist/esm/connection/connect-client.d.ts +12 -11
  67. package/dist/esm/connection/connect-client.js +32 -38
  68. package/dist/esm/connection/connect-client.js.map +1 -1
  69. package/dist/esm/connection/existing-process-transport.d.ts +1 -2
  70. package/dist/esm/connection/existing-process-transport.js +1 -1
  71. package/dist/esm/connection/existing-process-transport.js.map +1 -1
  72. package/dist/esm/dcr/dcr-authenticator.d.ts +36 -5
  73. package/dist/esm/dcr/dcr-authenticator.js +129 -58
  74. package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
  75. package/dist/esm/dcr/dynamic-client-registrar.d.ts +2 -2
  76. package/dist/esm/dcr/dynamic-client-registrar.js +7 -6
  77. package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
  78. package/dist/esm/index.d.ts +2 -0
  79. package/dist/esm/index.js +4 -1
  80. package/dist/esm/index.js.map +1 -1
  81. package/dist/esm/lib/url-utils.d.ts +17 -0
  82. package/dist/esm/lib/url-utils.js +34 -2
  83. package/dist/esm/lib/url-utils.js.map +1 -1
  84. package/dist/esm/response-wrappers.d.ts +1 -1
  85. package/dist/esm/response-wrappers.js.map +1 -1
  86. package/dist/esm/search/search.d.ts +1 -1
  87. package/dist/esm/search/search.js.map +1 -1
  88. package/package.json +13 -13
  89. package/dist/cjs/monkey-patches.d.cts +0 -6
  90. package/dist/cjs/monkey-patches.d.ts +0 -6
  91. package/dist/cjs/monkey-patches.js +0 -233
  92. package/dist/cjs/monkey-patches.js.map +0 -1
  93. package/dist/esm/monkey-patches.d.ts +0 -6
  94. package/dist/esm/monkey-patches.js +0 -32
  95. package/dist/esm/monkey-patches.js.map +0 -1
@@ -17,8 +17,62 @@ var _keyv = /*#__PURE__*/ _interop_require_default(require("keyv"));
17
17
  var _keyvfile = require("keyv-file");
18
18
  var _discoveryfetchts = require("../auth/discovery-fetch.js");
19
19
  var _interactiveoauthflowts = require("../auth/interactive-oauth-flow.js");
20
+ var _urlutilsts = require("../lib/url-utils.js");
20
21
  var _loggerts = require("../utils/logger.js");
21
22
  var _dynamicclientregistrarts = require("./dynamic-client-registrar.js");
23
+ function _array_like_to_array(arr, len) {
24
+ if (len == null || len > arr.length) len = arr.length;
25
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
26
+ return arr2;
27
+ }
28
+ function _array_with_holes(arr) {
29
+ if (Array.isArray(arr)) return arr;
30
+ }
31
+ function _assert_this_initialized(self) {
32
+ if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
33
+ return self;
34
+ }
35
+ function _async_iterator(iterable) {
36
+ var method, async, sync, retry = 2;
37
+ for("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;){
38
+ if (async && null != (method = iterable[async])) return method.call(iterable);
39
+ if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable));
40
+ async = "@@asyncIterator", sync = "@@iterator";
41
+ }
42
+ throw new TypeError("Object is not async iterable");
43
+ }
44
+ function AsyncFromSyncIterator(s) {
45
+ function AsyncFromSyncIteratorContinuation(r) {
46
+ if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
47
+ var done = r.done;
48
+ return Promise.resolve(r.value).then(function(value) {
49
+ return {
50
+ value: value,
51
+ done: done
52
+ };
53
+ });
54
+ }
55
+ return AsyncFromSyncIterator = function(s) {
56
+ this.s = s, this.n = s.next;
57
+ }, AsyncFromSyncIterator.prototype = {
58
+ s: null,
59
+ n: null,
60
+ next: function() {
61
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
62
+ },
63
+ return: function(value) {
64
+ var ret = this.s.return;
65
+ return void 0 === ret ? Promise.resolve({
66
+ value: value,
67
+ done: !0
68
+ }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));
69
+ },
70
+ throw: function(value) {
71
+ var thr = this.s.return;
72
+ return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
73
+ }
74
+ }, new AsyncFromSyncIterator(s);
75
+ }
22
76
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
23
77
  try {
24
78
  var info = gen[key](arg);
@@ -45,9 +99,59 @@ function _async_to_generator(fn) {
45
99
  });
46
100
  };
47
101
  }
102
+ function _call_super(_this, derived, args) {
103
+ derived = _get_prototype_of(derived);
104
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
105
+ }
48
106
  function _class_call_check(instance, Constructor) {
49
107
  if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
50
108
  }
109
+ function _construct(Parent, args, Class) {
110
+ if (_is_native_reflect_construct()) _construct = Reflect.construct;
111
+ else {
112
+ _construct = function construct(Parent, args, Class) {
113
+ var a = [
114
+ null
115
+ ];
116
+ a.push.apply(a, args);
117
+ var Constructor = Function.bind.apply(Parent, a);
118
+ var instance = new Constructor();
119
+ if (Class) _set_prototype_of(instance, Class.prototype);
120
+ return instance;
121
+ };
122
+ }
123
+ return _construct.apply(null, arguments);
124
+ }
125
+ function _define_property(obj, key, value) {
126
+ if (key in obj) {
127
+ Object.defineProperty(obj, key, {
128
+ value: value,
129
+ enumerable: true,
130
+ configurable: true,
131
+ writable: true
132
+ });
133
+ } else obj[key] = value;
134
+ return obj;
135
+ }
136
+ function _get_prototype_of(o) {
137
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
138
+ return o.__proto__ || Object.getPrototypeOf(o);
139
+ };
140
+ return _get_prototype_of(o);
141
+ }
142
+ function _inherits(subClass, superClass) {
143
+ if (typeof superClass !== "function" && superClass !== null) {
144
+ throw new TypeError("Super expression must either be null or a function");
145
+ }
146
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
147
+ constructor: {
148
+ value: subClass,
149
+ writable: true,
150
+ configurable: true
151
+ }
152
+ });
153
+ if (superClass) _set_prototype_of(subClass, superClass);
154
+ }
51
155
  function _instanceof(left, right) {
52
156
  "@swc/helpers - instanceof";
53
157
  if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
@@ -89,6 +193,96 @@ function _interop_require_wildcard(obj, nodeInterop) {
89
193
  if (cache) cache.set(obj, newObj);
90
194
  return newObj;
91
195
  }
196
+ function _is_native_function(fn) {
197
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
198
+ }
199
+ function _is_native_reflect_construct() {
200
+ try {
201
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
202
+ } catch (_) {}
203
+ return (_is_native_reflect_construct = function() {
204
+ return !!result;
205
+ })();
206
+ }
207
+ function _iterable_to_array_limit(arr, i) {
208
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
209
+ if (_i == null) return;
210
+ var _arr = [];
211
+ var _n = true;
212
+ var _d = false;
213
+ var _s, _e;
214
+ try {
215
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
216
+ _arr.push(_s.value);
217
+ if (i && _arr.length === i) break;
218
+ }
219
+ } catch (err) {
220
+ _d = true;
221
+ _e = err;
222
+ } finally{
223
+ try {
224
+ if (!_n && _i["return"] != null) _i["return"]();
225
+ } finally{
226
+ if (_d) throw _e;
227
+ }
228
+ }
229
+ return _arr;
230
+ }
231
+ function _non_iterable_rest() {
232
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
233
+ }
234
+ function _object_spread(target) {
235
+ for(var i = 1; i < arguments.length; i++){
236
+ var source = arguments[i] != null ? arguments[i] : {};
237
+ var ownKeys = Object.keys(source);
238
+ if (typeof Object.getOwnPropertySymbols === "function") {
239
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
240
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
241
+ }));
242
+ }
243
+ ownKeys.forEach(function(key) {
244
+ _define_property(target, key, source[key]);
245
+ });
246
+ }
247
+ return target;
248
+ }
249
+ function ownKeys(object, enumerableOnly) {
250
+ var keys = Object.keys(object);
251
+ if (Object.getOwnPropertySymbols) {
252
+ var symbols = Object.getOwnPropertySymbols(object);
253
+ if (enumerableOnly) {
254
+ symbols = symbols.filter(function(sym) {
255
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
256
+ });
257
+ }
258
+ keys.push.apply(keys, symbols);
259
+ }
260
+ return keys;
261
+ }
262
+ function _object_spread_props(target, source) {
263
+ source = source != null ? source : {};
264
+ if (Object.getOwnPropertyDescriptors) Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
265
+ else {
266
+ ownKeys(Object(source)).forEach(function(key) {
267
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
268
+ });
269
+ }
270
+ return target;
271
+ }
272
+ function _possible_constructor_return(self, call) {
273
+ if (call && (_type_of(call) === "object" || typeof call === "function")) return call;
274
+ return _assert_this_initialized(self);
275
+ }
276
+ function _set_prototype_of(o, p) {
277
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
278
+ o.__proto__ = p;
279
+ return o;
280
+ };
281
+ return _set_prototype_of(o, p);
282
+ }
283
+ function _sliced_to_array(arr, i) {
284
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
285
+ }
92
286
  function _ts_generator(thisArg, body) {
93
287
  var f, y, t, _ = {
94
288
  label: 0,
@@ -188,9 +382,68 @@ function _ts_generator(thisArg, body) {
188
382
  };
189
383
  }
190
384
  }
385
+ function _type_of(obj) {
386
+ "@swc/helpers - typeof";
387
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
388
+ }
389
+ function _unsupported_iterable_to_array(o, minLen) {
390
+ if (!o) return;
391
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
392
+ var n = Object.prototype.toString.call(o).slice(8, -1);
393
+ if (n === "Object" && o.constructor) n = o.constructor.name;
394
+ if (n === "Map" || n === "Set") return Array.from(n);
395
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
396
+ }
397
+ function _wrap_native_super(Class) {
398
+ var _cache = typeof Map === "function" ? new Map() : undefined;
399
+ _wrap_native_super = function(Class) {
400
+ if (Class === null || !_is_native_function(Class)) return Class;
401
+ if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
402
+ if (typeof _cache !== "undefined") {
403
+ if (_cache.has(Class)) return _cache.get(Class);
404
+ _cache.set(Class, Wrapper);
405
+ }
406
+ function Wrapper() {
407
+ return _construct(Class, arguments, _get_prototype_of(this).constructor);
408
+ }
409
+ Wrapper.prototype = Object.create(Class.prototype, {
410
+ constructor: {
411
+ value: Wrapper,
412
+ enumerable: false,
413
+ writable: true,
414
+ configurable: true
415
+ }
416
+ });
417
+ return _set_prototype_of(Wrapper, Class);
418
+ };
419
+ return _wrap_native_super(Class);
420
+ }
191
421
  /**
192
422
  * Buffer time before token expiry to trigger proactive refresh (5 minutes)
193
423
  */ var REFRESH_BUFFER_MS = 5 * 60 * 1000;
424
+ /** Raised when a credential cannot be bound to, or looked up by, an issuer. */ var CredentialBindingError = /*#__PURE__*/ function(Error1) {
425
+ "use strict";
426
+ _inherits(CredentialBindingError, Error1);
427
+ function CredentialBindingError(message) {
428
+ _class_call_check(this, CredentialBindingError);
429
+ var _this;
430
+ _this = _call_super(this, CredentialBindingError, [
431
+ message
432
+ ]);
433
+ _this.name = 'CredentialBindingError';
434
+ return _this;
435
+ }
436
+ return CredentialBindingError;
437
+ }(_wrap_native_super(Error));
438
+ /**
439
+ * The issuer credentials are keyed by, so they can never be presented to a
440
+ * different authorization server even when the resource keeps its URL (SEP-2352).
441
+ */ function requireIssuer(capabilities) {
442
+ if (!capabilities.issuer) {
443
+ throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');
444
+ }
445
+ return capabilities.issuer;
446
+ }
194
447
  var DcrAuthenticator = /*#__PURE__*/ function() {
195
448
  "use strict";
196
449
  function DcrAuthenticator(options) {
@@ -221,17 +474,17 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
221
474
  /**
222
475
  * Detect if server is self-hosted DCR (vs external OAuth provider)
223
476
  * Self-hosted servers have their own OAuth endpoints and manage token storage
224
- */ _proto.detectSelfHostedMode = function detectSelfHostedMode(baseUrl) {
477
+ */ _proto.detectSelfHostedMode = function detectSelfHostedMode(mcpServerUrl) {
225
478
  return _async_to_generator(function() {
226
479
  return _ts_generator(this, function(_state) {
227
480
  try {
228
481
  // Self-hosted DCR servers typically run their own OAuth server
229
482
  // Check if this is a self-hosted instance by testing OAuth metadata
230
- // For now, assume self-hosted if baseUrl matches common localhost patterns
483
+ // For now, assume self-hosted if the URL matches common localhost patterns
231
484
  // TODO: Implement proper self-hosted detection logic
232
485
  return [
233
486
  2,
234
- baseUrl.includes('localhost') || baseUrl.includes('127.0.0.1')
487
+ mcpServerUrl.includes('localhost') || mcpServerUrl.includes('127.0.0.1')
235
488
  ];
236
489
  } catch (_error) {
237
490
  return [
@@ -249,7 +502,9 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
249
502
  * Ensure server is authenticated, performing DCR and OAuth if needed
250
503
  * Proactively refreshes tokens if they're within 5 minutes of expiry
251
504
  *
252
- * @param baseUrl - Base URL of the server (e.g., https://example.com)
505
+ * @param mcpServerUrl - The MCP server's canonical URL, exactly as configured,
506
+ * with its path intact (`https://example.com/mcp`). Not a deployment root:
507
+ * the path is what identifies the resource an issued token is bound to.
253
508
  * @param capabilities - Auth capabilities from .well-known endpoint
254
509
  * @returns Valid token set ready to use
255
510
  *
@@ -258,10 +513,10 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
258
513
  * @example
259
514
  * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });
260
515
  * const tokens = await authenticator.ensureAuthenticated(
261
- * 'https://example.com',
516
+ * 'https://example.com/mcp',
262
517
  * capabilities
263
518
  * );
264
- */ _proto.ensureAuthenticated = function ensureAuthenticated(baseUrl, capabilities) {
519
+ */ _proto.ensureAuthenticated = function ensureAuthenticated(mcpServerUrl, capabilities) {
265
520
  return _async_to_generator(function() {
266
521
  var isSelfHosted;
267
522
  return _ts_generator(this, function(_state) {
@@ -269,40 +524,68 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
269
524
  case 0:
270
525
  return [
271
526
  4,
272
- this.detectSelfHostedMode(baseUrl)
527
+ this.detectSelfHostedMode(mcpServerUrl)
273
528
  ];
274
529
  case 1:
275
530
  isSelfHosted = _state.sent();
276
531
  if (isSelfHosted) {
277
532
  return [
278
533
  2,
279
- this.ensureAuthenticatedSelfHosted(baseUrl, capabilities)
534
+ this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities)
280
535
  ];
281
536
  }
282
537
  return [
283
538
  2,
284
- this.ensureAuthenticatedExternal(baseUrl, capabilities)
539
+ this.ensureAuthenticatedExternal(mcpServerUrl, capabilities)
285
540
  ];
286
541
  }
287
542
  });
288
543
  }).call(this);
289
544
  };
290
545
  /**
546
+ * The three things a server URL is used for here, kept apart on purpose.
547
+ *
548
+ * They were one value once, and collapsing them is what sent an authorization
549
+ * server the wrong audience: `resource` was derived from the deployment root,
550
+ * so a server at `https://host/mcp` was asked to mint a token for
551
+ * `https://host`, and any server that validates the indicator answered
552
+ * `invalid_target`.
553
+ *
554
+ * - `serverBaseUrl` builds the server's own endpoints (`/oauth/verify`), so a
555
+ * trailing `/mcp` comes off.
556
+ * - `resource` is the RFC 8707 audience. The resource server names itself in
557
+ * its RFC 9728 metadata; that name wins. Only when no such document exists
558
+ * do we fall back to the URL we were configured with.
559
+ * - `storeKey` identifies the credential locally. It stays the configured URL
560
+ * rather than the discovered `resource`, so it can be computed without a
561
+ * network round trip - `deleteTokens` has only the URL to work from.
562
+ */ _proto.resolveUrls = function resolveUrls(mcpServerUrl, capabilities) {
563
+ var _capabilities_resource;
564
+ var storeKey = (0, _urlutilsts.normalizeUrl)(mcpServerUrl);
565
+ return {
566
+ serverBaseUrl: (0, _urlutilsts.extractBaseUrl)(mcpServerUrl),
567
+ resource: (_capabilities_resource = capabilities.resource) !== null && _capabilities_resource !== void 0 ? _capabilities_resource : storeKey,
568
+ storeKey: storeKey
569
+ };
570
+ };
571
+ /**
291
572
  * Handle authentication for self-hosted DCR servers
292
573
  * Self-hosted servers manage their own token storage via /oauth/verify
293
- */ _proto.ensureAuthenticatedSelfHosted = function ensureAuthenticatedSelfHosted(baseUrl, capabilities) {
574
+ */ _proto.ensureAuthenticatedSelfHosted = function ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities) {
294
575
  return _async_to_generator(function() {
295
- var allowLoopback, dcrTokenKey, tokens, verifyUrl, verifyResponse, verifyData, _error, port, client, flowOptions, verifyUrl1, verifyResponse1, verifyData1, error;
576
+ var allowLoopback, issuer, _this_resolveUrls, serverBaseUrl, resource, storeKey, dcrTokenKey, tokens, verifyUrl, verifyResponse, verifyData, _error, port, client, flowOptions, verifyUrl1, verifyResponse1, verifyData1, error;
296
577
  return _ts_generator(this, function(_state) {
297
578
  switch(_state.label){
298
579
  case 0:
299
580
  // Loopback trust for every discovery-derived fetch below, computed from
300
581
  // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).
301
- allowLoopback = (0, _discoveryfetchts.isLoopbackUrl)(baseUrl);
302
- dcrTokenKey = "dcr-tokens:".concat(baseUrl);
582
+ allowLoopback = (0, _discoveryfetchts.isLoopbackUrl)(mcpServerUrl);
583
+ issuer = requireIssuer(capabilities);
584
+ _this_resolveUrls = this.resolveUrls(mcpServerUrl, capabilities), serverBaseUrl = _this_resolveUrls.serverBaseUrl, resource = _this_resolveUrls.resource, storeKey = _this_resolveUrls.storeKey;
585
+ dcrTokenKey = "dcr-tokens:".concat(issuer, ":").concat(storeKey);
303
586
  return [
304
587
  4,
305
- this.tokenStore.get(dcrTokenKey)
588
+ this.loadTokens(dcrTokenKey, issuer)
306
589
  ];
307
590
  case 1:
308
591
  tokens = _state.sent();
@@ -318,7 +601,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
318
601
  ,
319
602
  7
320
603
  ]);
321
- verifyUrl = "".concat(baseUrl, "/oauth/verify");
604
+ verifyUrl = "".concat(serverBaseUrl, "/oauth/verify");
322
605
  return [
323
606
  4,
324
607
  fetch(verifyUrl, {
@@ -389,17 +672,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
389
672
  case 10:
390
673
  client = _state.sent();
391
674
  // Perform OAuth authorization flow with PKCE (RFC 7636)
392
- flowOptions = {
393
- port: port,
394
- headless: this.headless,
395
- redirectUri: this.redirectUri,
396
- pkce: true,
397
- logger: this.logger,
398
- allowLoopback: allowLoopback
399
- };
400
- if (capabilities.scopes) {
401
- flowOptions.scopes = capabilities.scopes;
402
- }
675
+ flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
403
676
  return [
404
677
  4,
405
678
  this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions)
@@ -414,7 +687,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
414
687
  ,
415
688
  16
416
689
  ]);
417
- verifyUrl1 = "".concat(baseUrl, "/oauth/verify");
690
+ verifyUrl1 = "".concat(serverBaseUrl, "/oauth/verify");
418
691
  return [
419
692
  4,
420
693
  fetch(verifyUrl1, {
@@ -451,7 +724,9 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
451
724
  // Save tokens for future use
452
725
  return [
453
726
  4,
454
- this.tokenStore.set(dcrTokenKey, tokens)
727
+ this.tokenStore.set(dcrTokenKey, _object_spread_props(_object_spread({}, tokens), {
728
+ issuer: issuer
729
+ }))
455
730
  ];
456
731
  case 17:
457
732
  _state.sent();
@@ -464,18 +739,20 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
464
739
  });
465
740
  }).call(this);
466
741
  };
467
- /** Handles authentication for external (non-self-hosted) OAuth providers. */ _proto.ensureAuthenticatedExternal = function ensureAuthenticatedExternal(baseUrl, capabilities) {
742
+ /** Handles authentication for external (non-self-hosted) OAuth providers. */ _proto.ensureAuthenticatedExternal = function ensureAuthenticatedExternal(mcpServerUrl, capabilities) {
468
743
  return _async_to_generator(function() {
469
- var allowLoopback, tokenKey, tokens, _error, port, client, flowOptions;
744
+ var allowLoopback, issuer, _this_resolveUrls, resource, storeKey, tokenKey, tokens, _error, port, client, flowOptions;
470
745
  return _ts_generator(this, function(_state) {
471
746
  switch(_state.label){
472
747
  case 0:
473
748
  // See ensureAuthenticatedSelfHosted - same loopback trust rule.
474
- allowLoopback = (0, _discoveryfetchts.isLoopbackUrl)(baseUrl);
475
- tokenKey = "tokens:".concat(baseUrl);
749
+ allowLoopback = (0, _discoveryfetchts.isLoopbackUrl)(mcpServerUrl);
750
+ issuer = requireIssuer(capabilities);
751
+ _this_resolveUrls = this.resolveUrls(mcpServerUrl, capabilities), resource = _this_resolveUrls.resource, storeKey = _this_resolveUrls.storeKey;
752
+ tokenKey = "tokens:".concat(issuer, ":").concat(storeKey);
476
753
  return [
477
754
  4,
478
- this.tokenStore.get(tokenKey)
755
+ this.loadTokens(tokenKey, issuer)
479
756
  ];
480
757
  case 1:
481
758
  tokens = _state.sent();
@@ -498,13 +775,15 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
498
775
  ]);
499
776
  return [
500
777
  4,
501
- this.refreshTokens(tokens, capabilities.tokenEndpoint, allowLoopback)
778
+ this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback)
502
779
  ];
503
780
  case 3:
504
781
  tokens = _state.sent();
505
782
  return [
506
783
  4,
507
- this.tokenStore.set(tokenKey, tokens)
784
+ this.tokenStore.set(tokenKey, _object_spread_props(_object_spread({}, tokens), {
785
+ issuer: issuer
786
+ }))
508
787
  ];
509
788
  case 4:
510
789
  _state.sent();
@@ -556,17 +835,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
556
835
  case 9:
557
836
  client = _state.sent();
558
837
  // Perform OAuth authorization flow with PKCE (RFC 7636)
559
- flowOptions = {
560
- port: port,
561
- headless: this.headless,
562
- redirectUri: this.redirectUri,
563
- pkce: true,
564
- logger: this.logger,
565
- allowLoopback: allowLoopback
566
- };
567
- if (capabilities.scopes) {
568
- flowOptions.scopes = capabilities.scopes;
569
- }
838
+ flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
570
839
  return [
571
840
  4,
572
841
  this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions)
@@ -576,7 +845,9 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
576
845
  // Save tokens for future use
577
846
  return [
578
847
  4,
579
- this.tokenStore.set(tokenKey, tokens)
848
+ this.tokenStore.set(tokenKey, _object_spread_props(_object_spread({}, tokens), {
849
+ issuer: issuer
850
+ }))
580
851
  ];
581
852
  case 11:
582
853
  _state.sent();
@@ -591,9 +862,10 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
591
862
  };
592
863
  /**
593
864
  * Refreshes an access token using a refresh token.
865
+ * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).
594
866
  * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.
595
- */ _proto.refreshTokens = function refreshTokens(tokens, tokenEndpoint) {
596
- var allowLoopback = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
867
+ */ _proto.refreshTokens = function refreshTokens(tokens, tokenEndpoint, resource) {
868
+ var allowLoopback = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
597
869
  return _async_to_generator(function() {
598
870
  return _ts_generator(this, function(_state) {
599
871
  switch(_state.label){
@@ -609,7 +881,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
609
881
  }
610
882
  return [
611
883
  4,
612
- this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, allowLoopback)
884
+ this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback)
613
885
  ];
614
886
  case 1:
615
887
  return [
@@ -621,26 +893,112 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
621
893
  }).call(this);
622
894
  };
623
895
  /**
624
- * Delete stored tokens for a server
625
- */ _proto.deleteTokens = function deleteTokens(baseUrl) {
896
+ * Deletes both stored token families for a server, across every issuer they were bound to.
897
+ *
898
+ * Takes the same `mcpServerUrl` that {@link DcrAuthenticator.ensureAuthenticated}
899
+ * was given - keys are built from the configured URL, never from the discovered
900
+ * RFC 8707 resource, precisely so this can find them without doing discovery.
901
+ *
902
+ * @throws CredentialBindingError if the configured store cannot enumerate keys.
903
+ */ _proto.deleteTokens = function deleteTokens(mcpServerUrl) {
626
904
  return _async_to_generator(function() {
905
+ var suffix, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, _value1, key, err;
627
906
  return _ts_generator(this, function(_state) {
628
907
  switch(_state.label){
629
908
  case 0:
630
- // Both families this class writes: `tokens:` from the external OAuth path
631
- // (line ~213) and `dcr-tokens:` from the self-hosted DCR path (line ~119).
632
- // Deleting only one leaves a usable credential behind for a caller that
633
- // believes it revoked them.
909
+ suffix = ":".concat((0, _urlutilsts.normalizeUrl)(mcpServerUrl));
910
+ if (!this.tokenStore.iterator) {
911
+ throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');
912
+ }
913
+ _iteratorAbruptCompletion = false, _didIteratorError = false;
914
+ _state.label = 1;
915
+ case 1:
916
+ _state.trys.push([
917
+ 1,
918
+ 7,
919
+ 8,
920
+ 13
921
+ ]);
922
+ _iterator = _async_iterator(this.tokenStore.iterator(this.tokenStore.namespace));
923
+ _state.label = 2;
924
+ case 2:
634
925
  return [
635
926
  4,
636
- Promise.all([
637
- this.tokenStore.delete("tokens:".concat(baseUrl)),
638
- this.tokenStore.delete("dcr-tokens:".concat(baseUrl))
639
- ])
927
+ _iterator.next()
640
928
  ];
641
- case 1:
929
+ case 3:
930
+ if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
931
+ 3,
932
+ 6
933
+ ];
934
+ _value = _step.value;
935
+ _value1 = _sliced_to_array(_value, 1), key = _value1[0];
936
+ if (!(typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix))) return [
937
+ 3,
938
+ 5
939
+ ];
940
+ return [
941
+ 4,
942
+ this.tokenStore.delete(key)
943
+ ];
944
+ case 4:
642
945
  _state.sent();
643
- this.logger.debug("\uD83D\uDDD1️ Deleted tokens for ".concat(baseUrl));
946
+ _state.label = 5;
947
+ case 5:
948
+ _iteratorAbruptCompletion = false;
949
+ return [
950
+ 3,
951
+ 2
952
+ ];
953
+ case 6:
954
+ return [
955
+ 3,
956
+ 13
957
+ ];
958
+ case 7:
959
+ err = _state.sent();
960
+ _didIteratorError = true;
961
+ _iteratorError = err;
962
+ return [
963
+ 3,
964
+ 13
965
+ ];
966
+ case 8:
967
+ _state.trys.push([
968
+ 8,
969
+ ,
970
+ 11,
971
+ 12
972
+ ]);
973
+ if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
974
+ 3,
975
+ 10
976
+ ];
977
+ return [
978
+ 4,
979
+ _iterator.return()
980
+ ];
981
+ case 9:
982
+ _state.sent();
983
+ _state.label = 10;
984
+ case 10:
985
+ return [
986
+ 3,
987
+ 12
988
+ ];
989
+ case 11:
990
+ if (_didIteratorError) {
991
+ throw _iteratorError;
992
+ }
993
+ return [
994
+ 7
995
+ ];
996
+ case 12:
997
+ return [
998
+ 7
999
+ ];
1000
+ case 13:
1001
+ this.logger.debug("\uD83D\uDDD1️ Deleted tokens for ".concat(mcpServerUrl));
644
1002
  return [
645
1003
  2
646
1004
  ];
@@ -648,6 +1006,59 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
648
1006
  });
649
1007
  }).call(this);
650
1008
  };
1009
+ /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */ _proto.loadTokens = function loadTokens(key, issuer) {
1010
+ return _async_to_generator(function() {
1011
+ var tokens;
1012
+ return _ts_generator(this, function(_state) {
1013
+ switch(_state.label){
1014
+ case 0:
1015
+ return [
1016
+ 4,
1017
+ this.tokenStore.get(key)
1018
+ ];
1019
+ case 1:
1020
+ tokens = _state.sent();
1021
+ if (!tokens) return [
1022
+ 2,
1023
+ undefined
1024
+ ];
1025
+ if (tokens.issuer === issuer) return [
1026
+ 2,
1027
+ tokens
1028
+ ];
1029
+ this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');
1030
+ return [
1031
+ 4,
1032
+ this.tokenStore.delete(key)
1033
+ ];
1034
+ case 2:
1035
+ _state.sent();
1036
+ return [
1037
+ 2,
1038
+ undefined
1039
+ ];
1040
+ }
1041
+ });
1042
+ }).call(this);
1043
+ };
1044
+ _proto.buildFlowOptions = function buildFlowOptions(port, capabilities, issuer, resource, allowLoopback) {
1045
+ var _capabilities_authorizationResponseIssSupported;
1046
+ var flowOptions = {
1047
+ port: port,
1048
+ issuer: issuer,
1049
+ resource: resource,
1050
+ headless: this.headless,
1051
+ redirectUri: this.redirectUri,
1052
+ pkce: true,
1053
+ logger: this.logger,
1054
+ allowLoopback: allowLoopback,
1055
+ authorizationResponseIssSupported: (_capabilities_authorizationResponseIssSupported = capabilities.authorizationResponseIssSupported) !== null && _capabilities_authorizationResponseIssSupported !== void 0 ? _capabilities_authorizationResponseIssSupported : false
1056
+ };
1057
+ if (capabilities.scopes) {
1058
+ flowOptions.scopes = capabilities.scopes;
1059
+ }
1060
+ return flowOptions;
1061
+ };
651
1062
  return DcrAuthenticator;
652
1063
  }();
653
1064
  /* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }