@mcp-z/client 1.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +5 -1
  2. package/dist/cjs/auth/capability-discovery.js +18 -8
  3. package/dist/cjs/auth/capability-discovery.js.map +1 -1
  4. package/dist/cjs/auth/discovery-fetch.d.cts +35 -0
  5. package/dist/cjs/auth/discovery-fetch.d.ts +35 -0
  6. package/dist/cjs/auth/discovery-fetch.js +658 -0
  7. package/dist/cjs/auth/discovery-fetch.js.map +1 -0
  8. package/dist/cjs/auth/index.d.cts +1 -0
  9. package/dist/cjs/auth/index.d.ts +1 -0
  10. package/dist/cjs/auth/index.js +7 -0
  11. package/dist/cjs/auth/index.js.map +1 -1
  12. package/dist/cjs/auth/interactive-oauth-flow.d.cts +20 -13
  13. package/dist/cjs/auth/interactive-oauth-flow.d.ts +20 -13
  14. package/dist/cjs/auth/interactive-oauth-flow.js +48 -24
  15. package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
  16. package/dist/cjs/auth/oauth-callback-listener.js +4 -0
  17. package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
  18. package/dist/cjs/auth/rfc9728-discovery.d.cts +12 -25
  19. package/dist/cjs/auth/rfc9728-discovery.d.ts +12 -25
  20. package/dist/cjs/auth/rfc9728-discovery.js +59 -48
  21. package/dist/cjs/auth/rfc9728-discovery.js.map +1 -1
  22. package/dist/cjs/auth/types.d.cts +34 -4
  23. package/dist/cjs/auth/types.d.ts +34 -4
  24. package/dist/cjs/auth/types.js.map +1 -1
  25. package/dist/cjs/dcr/dcr-authenticator.d.cts +9 -5
  26. package/dist/cjs/dcr/dcr-authenticator.d.ts +9 -5
  27. package/dist/cjs/dcr/dcr-authenticator.js +436 -43
  28. package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
  29. package/dist/cjs/dcr/dynamic-client-registrar.d.cts +7 -18
  30. package/dist/cjs/dcr/dynamic-client-registrar.d.ts +7 -18
  31. package/dist/cjs/dcr/dynamic-client-registrar.js +18 -25
  32. package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
  33. package/dist/cjs/index.d.cts +1 -0
  34. package/dist/cjs/index.d.ts +1 -0
  35. package/dist/cjs/index.js +7 -0
  36. package/dist/cjs/index.js.map +1 -1
  37. package/dist/cjs/lib/url-utils.js +2 -2
  38. package/dist/cjs/lib/url-utils.js.map +1 -1
  39. package/dist/esm/auth/capability-discovery.js +17 -7
  40. package/dist/esm/auth/capability-discovery.js.map +1 -1
  41. package/dist/esm/auth/discovery-fetch.d.ts +35 -0
  42. package/dist/esm/auth/discovery-fetch.js +184 -0
  43. package/dist/esm/auth/discovery-fetch.js.map +1 -0
  44. package/dist/esm/auth/index.d.ts +1 -0
  45. package/dist/esm/auth/index.js +1 -0
  46. package/dist/esm/auth/index.js.map +1 -1
  47. package/dist/esm/auth/interactive-oauth-flow.d.ts +20 -13
  48. package/dist/esm/auth/interactive-oauth-flow.js +50 -23
  49. package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
  50. package/dist/esm/auth/oauth-callback-listener.js +4 -0
  51. package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
  52. package/dist/esm/auth/rfc9728-discovery.d.ts +12 -25
  53. package/dist/esm/auth/rfc9728-discovery.js +49 -56
  54. package/dist/esm/auth/rfc9728-discovery.js.map +1 -1
  55. package/dist/esm/auth/types.d.ts +34 -4
  56. package/dist/esm/auth/types.js.map +1 -1
  57. package/dist/esm/dcr/dcr-authenticator.d.ts +9 -5
  58. package/dist/esm/dcr/dcr-authenticator.js +92 -39
  59. package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
  60. package/dist/esm/dcr/dynamic-client-registrar.d.ts +7 -18
  61. package/dist/esm/dcr/dynamic-client-registrar.js +19 -23
  62. package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
  63. package/dist/esm/index.d.ts +1 -0
  64. package/dist/esm/index.js +1 -0
  65. package/dist/esm/index.js.map +1 -1
  66. package/dist/esm/lib/url-utils.js +2 -2
  67. package/dist/esm/lib/url-utils.js.map +1 -1
  68. package/package.json +3 -8
@@ -58,16 +58,20 @@ export declare class DcrAuthenticator {
58
58
  * Self-hosted servers manage their own token storage via /oauth/verify
59
59
  */
60
60
  private ensureAuthenticatedSelfHosted;
61
- /**
62
- * Handle authentication for external OAuth providers (original implementation)
63
- */
61
+ /** Handles authentication for external (non-self-hosted) OAuth providers. */
64
62
  private ensureAuthenticatedExternal;
65
63
  /**
66
- * Refresh access token using refresh token
64
+ * Refreshes an access token using a refresh token.
65
+ * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).
66
+ * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.
67
67
  */
68
68
  private refreshTokens;
69
69
  /**
70
- * Delete stored tokens for a server
70
+ * Deletes both stored token families for a server, across every issuer they were bound to.
71
+ * @throws CredentialBindingError if the configured store cannot enumerate keys.
71
72
  */
72
73
  deleteTokens(baseUrl: string): Promise<void>;
74
+ /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */
75
+ private loadTokens;
76
+ private buildFlowOptions;
73
77
  }
@@ -15,9 +15,64 @@ var _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
15
15
  var _fs = /*#__PURE__*/ _interop_require_wildcard(require("fs"));
16
16
  var _keyv = /*#__PURE__*/ _interop_require_default(require("keyv"));
17
17
  var _keyvfile = require("keyv-file");
18
+ var _discoveryfetchts = require("../auth/discovery-fetch.js");
18
19
  var _interactiveoauthflowts = require("../auth/interactive-oauth-flow.js");
20
+ var _urlutilsts = require("../lib/url-utils.js");
19
21
  var _loggerts = require("../utils/logger.js");
20
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
+ }
21
76
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
22
77
  try {
23
78
  var info = gen[key](arg);
@@ -44,9 +99,59 @@ function _async_to_generator(fn) {
44
99
  });
45
100
  };
46
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
+ }
47
106
  function _class_call_check(instance, Constructor) {
48
107
  if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
49
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
+ }
50
155
  function _instanceof(left, right) {
51
156
  "@swc/helpers - instanceof";
52
157
  if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
@@ -88,6 +193,96 @@ function _interop_require_wildcard(obj, nodeInterop) {
88
193
  if (cache) cache.set(obj, newObj);
89
194
  return newObj;
90
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
+ }
91
286
  function _ts_generator(thisArg, body) {
92
287
  var f, y, t, _ = {
93
288
  label: 0,
@@ -187,9 +382,68 @@ function _ts_generator(thisArg, body) {
187
382
  };
188
383
  }
189
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
+ }
190
421
  /**
191
422
  * Buffer time before token expiry to trigger proactive refresh (5 minutes)
192
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
+ }
193
447
  var DcrAuthenticator = /*#__PURE__*/ function() {
194
448
  "use strict";
195
449
  function DcrAuthenticator(options) {
@@ -291,14 +545,19 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
291
545
  * Self-hosted servers manage their own token storage via /oauth/verify
292
546
  */ _proto.ensureAuthenticatedSelfHosted = function ensureAuthenticatedSelfHosted(baseUrl, capabilities) {
293
547
  return _async_to_generator(function() {
294
- var dcrTokenKey, tokens, verifyUrl, verifyResponse, verifyData, _error, port, client, flowOptions, verifyUrl1, verifyResponse1, verifyData1, error;
548
+ var allowLoopback, issuer, resource, dcrTokenKey, tokens, verifyUrl, verifyResponse, verifyData, _error, port, client, flowOptions, verifyUrl1, verifyResponse1, verifyData1, error;
295
549
  return _ts_generator(this, function(_state) {
296
550
  switch(_state.label){
297
551
  case 0:
298
- dcrTokenKey = "dcr-tokens:".concat(baseUrl);
552
+ // Loopback trust for every discovery-derived fetch below, computed from
553
+ // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).
554
+ allowLoopback = (0, _discoveryfetchts.isLoopbackUrl)(baseUrl);
555
+ issuer = requireIssuer(capabilities);
556
+ resource = (0, _urlutilsts.normalizeUrl)(baseUrl);
557
+ dcrTokenKey = "dcr-tokens:".concat(issuer, ":").concat(resource);
299
558
  return [
300
559
  4,
301
- this.tokenStore.get(dcrTokenKey)
560
+ this.loadTokens(dcrTokenKey, issuer)
302
561
  ];
303
562
  case 1:
304
563
  tokens = _state.sent();
@@ -378,22 +637,14 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
378
637
  return [
379
638
  4,
380
639
  this.dcrClient.registerClient(capabilities.registrationEndpoint, {
381
- redirectUri: this.redirectUri
640
+ redirectUri: this.redirectUri,
641
+ allowLoopback: allowLoopback
382
642
  })
383
643
  ];
384
644
  case 10:
385
645
  client = _state.sent();
386
646
  // Perform OAuth authorization flow with PKCE (RFC 7636)
387
- flowOptions = {
388
- port: port,
389
- headless: this.headless,
390
- redirectUri: this.redirectUri,
391
- pkce: true,
392
- logger: this.logger
393
- };
394
- if (capabilities.scopes) {
395
- flowOptions.scopes = capabilities.scopes;
396
- }
647
+ flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
397
648
  return [
398
649
  4,
399
650
  this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions)
@@ -445,7 +696,9 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
445
696
  // Save tokens for future use
446
697
  return [
447
698
  4,
448
- this.tokenStore.set(dcrTokenKey, tokens)
699
+ this.tokenStore.set(dcrTokenKey, _object_spread_props(_object_spread({}, tokens), {
700
+ issuer: issuer
701
+ }))
449
702
  ];
450
703
  case 17:
451
704
  _state.sent();
@@ -458,18 +711,20 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
458
711
  });
459
712
  }).call(this);
460
713
  };
461
- /**
462
- * Handle authentication for external OAuth providers (original implementation)
463
- */ _proto.ensureAuthenticatedExternal = function ensureAuthenticatedExternal(baseUrl, capabilities) {
714
+ /** Handles authentication for external (non-self-hosted) OAuth providers. */ _proto.ensureAuthenticatedExternal = function ensureAuthenticatedExternal(baseUrl, capabilities) {
464
715
  return _async_to_generator(function() {
465
- var tokenKey, tokens, _error, port, client, flowOptions;
716
+ var allowLoopback, issuer, resource, tokenKey, tokens, _error, port, client, flowOptions;
466
717
  return _ts_generator(this, function(_state) {
467
718
  switch(_state.label){
468
719
  case 0:
469
- tokenKey = "tokens:".concat(baseUrl);
720
+ // See ensureAuthenticatedSelfHosted - same loopback trust rule.
721
+ allowLoopback = (0, _discoveryfetchts.isLoopbackUrl)(baseUrl);
722
+ issuer = requireIssuer(capabilities);
723
+ resource = (0, _urlutilsts.normalizeUrl)(baseUrl);
724
+ tokenKey = "tokens:".concat(issuer, ":").concat(resource);
470
725
  return [
471
726
  4,
472
- this.tokenStore.get(tokenKey)
727
+ this.loadTokens(tokenKey, issuer)
473
728
  ];
474
729
  case 1:
475
730
  tokens = _state.sent();
@@ -492,13 +747,15 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
492
747
  ]);
493
748
  return [
494
749
  4,
495
- this.refreshTokens(tokens, capabilities.tokenEndpoint)
750
+ this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback)
496
751
  ];
497
752
  case 3:
498
753
  tokens = _state.sent();
499
754
  return [
500
755
  4,
501
- this.tokenStore.set(tokenKey, tokens)
756
+ this.tokenStore.set(tokenKey, _object_spread_props(_object_spread({}, tokens), {
757
+ issuer: issuer
758
+ }))
502
759
  ];
503
760
  case 4:
504
761
  _state.sent();
@@ -543,22 +800,14 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
543
800
  return [
544
801
  4,
545
802
  this.dcrClient.registerClient(capabilities.registrationEndpoint, {
546
- redirectUri: this.redirectUri
803
+ redirectUri: this.redirectUri,
804
+ allowLoopback: allowLoopback
547
805
  })
548
806
  ];
549
807
  case 9:
550
808
  client = _state.sent();
551
809
  // Perform OAuth authorization flow with PKCE (RFC 7636)
552
- flowOptions = {
553
- port: port,
554
- headless: this.headless,
555
- redirectUri: this.redirectUri,
556
- pkce: true,
557
- logger: this.logger
558
- };
559
- if (capabilities.scopes) {
560
- flowOptions.scopes = capabilities.scopes;
561
- }
810
+ flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
562
811
  return [
563
812
  4,
564
813
  this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions)
@@ -568,7 +817,9 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
568
817
  // Save tokens for future use
569
818
  return [
570
819
  4,
571
- this.tokenStore.set(tokenKey, tokens)
820
+ this.tokenStore.set(tokenKey, _object_spread_props(_object_spread({}, tokens), {
821
+ issuer: issuer
822
+ }))
572
823
  ];
573
824
  case 11:
574
825
  _state.sent();
@@ -582,8 +833,11 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
582
833
  }).call(this);
583
834
  };
584
835
  /**
585
- * Refresh access token using refresh token
586
- */ _proto.refreshTokens = function refreshTokens(tokens, tokenEndpoint) {
836
+ * Refreshes an access token using a refresh token.
837
+ * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).
838
+ * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.
839
+ */ _proto.refreshTokens = function refreshTokens(tokens, tokenEndpoint, resource) {
840
+ var allowLoopback = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
587
841
  return _async_to_generator(function() {
588
842
  return _ts_generator(this, function(_state) {
589
843
  switch(_state.label){
@@ -599,7 +853,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
599
853
  }
600
854
  return [
601
855
  4,
602
- this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret)
856
+ this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback)
603
857
  ];
604
858
  case 1:
605
859
  return [
@@ -611,20 +865,106 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
611
865
  }).call(this);
612
866
  };
613
867
  /**
614
- * Delete stored tokens for a server
868
+ * Deletes both stored token families for a server, across every issuer they were bound to.
869
+ * @throws CredentialBindingError if the configured store cannot enumerate keys.
615
870
  */ _proto.deleteTokens = function deleteTokens(baseUrl) {
616
871
  return _async_to_generator(function() {
617
- var tokenKey;
872
+ var suffix, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, _value1, key, err;
618
873
  return _ts_generator(this, function(_state) {
619
874
  switch(_state.label){
620
875
  case 0:
621
- tokenKey = "tokens:".concat(baseUrl);
876
+ suffix = ":".concat((0, _urlutilsts.normalizeUrl)(baseUrl));
877
+ if (!this.tokenStore.iterator) {
878
+ throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');
879
+ }
880
+ _iteratorAbruptCompletion = false, _didIteratorError = false;
881
+ _state.label = 1;
882
+ case 1:
883
+ _state.trys.push([
884
+ 1,
885
+ 7,
886
+ 8,
887
+ 13
888
+ ]);
889
+ _iterator = _async_iterator(this.tokenStore.iterator(this.tokenStore.namespace));
890
+ _state.label = 2;
891
+ case 2:
622
892
  return [
623
893
  4,
624
- this.tokenStore.delete(tokenKey)
894
+ _iterator.next()
625
895
  ];
626
- case 1:
896
+ case 3:
897
+ if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
898
+ 3,
899
+ 6
900
+ ];
901
+ _value = _step.value;
902
+ _value1 = _sliced_to_array(_value, 1), key = _value1[0];
903
+ if (!(typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix))) return [
904
+ 3,
905
+ 5
906
+ ];
907
+ return [
908
+ 4,
909
+ this.tokenStore.delete(key)
910
+ ];
911
+ case 4:
912
+ _state.sent();
913
+ _state.label = 5;
914
+ case 5:
915
+ _iteratorAbruptCompletion = false;
916
+ return [
917
+ 3,
918
+ 2
919
+ ];
920
+ case 6:
921
+ return [
922
+ 3,
923
+ 13
924
+ ];
925
+ case 7:
926
+ err = _state.sent();
927
+ _didIteratorError = true;
928
+ _iteratorError = err;
929
+ return [
930
+ 3,
931
+ 13
932
+ ];
933
+ case 8:
934
+ _state.trys.push([
935
+ 8,
936
+ ,
937
+ 11,
938
+ 12
939
+ ]);
940
+ if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
941
+ 3,
942
+ 10
943
+ ];
944
+ return [
945
+ 4,
946
+ _iterator.return()
947
+ ];
948
+ case 9:
627
949
  _state.sent();
950
+ _state.label = 10;
951
+ case 10:
952
+ return [
953
+ 3,
954
+ 12
955
+ ];
956
+ case 11:
957
+ if (_didIteratorError) {
958
+ throw _iteratorError;
959
+ }
960
+ return [
961
+ 7
962
+ ];
963
+ case 12:
964
+ return [
965
+ 7
966
+ ];
967
+ case 13:
628
968
  this.logger.debug("\uD83D\uDDD1️ Deleted tokens for ".concat(baseUrl));
629
969
  return [
630
970
  2
@@ -633,6 +973,59 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
633
973
  });
634
974
  }).call(this);
635
975
  };
976
+ /** 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) {
977
+ return _async_to_generator(function() {
978
+ var tokens;
979
+ return _ts_generator(this, function(_state) {
980
+ switch(_state.label){
981
+ case 0:
982
+ return [
983
+ 4,
984
+ this.tokenStore.get(key)
985
+ ];
986
+ case 1:
987
+ tokens = _state.sent();
988
+ if (!tokens) return [
989
+ 2,
990
+ undefined
991
+ ];
992
+ if (tokens.issuer === issuer) return [
993
+ 2,
994
+ tokens
995
+ ];
996
+ this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');
997
+ return [
998
+ 4,
999
+ this.tokenStore.delete(key)
1000
+ ];
1001
+ case 2:
1002
+ _state.sent();
1003
+ return [
1004
+ 2,
1005
+ undefined
1006
+ ];
1007
+ }
1008
+ });
1009
+ }).call(this);
1010
+ };
1011
+ _proto.buildFlowOptions = function buildFlowOptions(port, capabilities, issuer, resource, allowLoopback) {
1012
+ var _capabilities_authorizationResponseIssSupported;
1013
+ var flowOptions = {
1014
+ port: port,
1015
+ issuer: issuer,
1016
+ resource: resource,
1017
+ headless: this.headless,
1018
+ redirectUri: this.redirectUri,
1019
+ pkce: true,
1020
+ logger: this.logger,
1021
+ allowLoopback: allowLoopback,
1022
+ authorizationResponseIssSupported: (_capabilities_authorizationResponseIssSupported = capabilities.authorizationResponseIssSupported) !== null && _capabilities_authorizationResponseIssSupported !== void 0 ? _capabilities_authorizationResponseIssSupported : false
1023
+ };
1024
+ if (capabilities.scopes) {
1025
+ flowOptions.scopes = capabilities.scopes;
1026
+ }
1027
+ return flowOptions;
1028
+ };
636
1029
  return DcrAuthenticator;
637
1030
  }();
638
1031
  /* 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; }