solid-ui 2.4.27-9d7e618e → 2.4.27-9f7a01da

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.
package/dist/solid-ui.js CHANGED
@@ -2655,7 +2655,7 @@ var ChatChannel = /*#__PURE__*/function () {
2655
2655
  var oldMsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2656
2656
  var deleteIt = arguments.length > 2 ? arguments[2] : undefined;
2657
2657
  return /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
2658
- var sts, now, timestamp, dateStamp, chatDocument, message, me, msg, oldMsgMaker, errMsg, privateKey, _errMsg;
2658
+ var sts, now, timestamp, dateStamp, chatDocument, message, me, msg, oldMsgMaker, errMsg, privateKey, pubKey, sig, _errMsg;
2659
2659
  return _regenerator["default"].wrap(function _callee2$(_context2) {
2660
2660
  while (1) switch (_context2.prev = _context2.next) {
2661
2661
  case 0:
@@ -2666,8 +2666,8 @@ var ChatChannel = /*#__PURE__*/function () {
2666
2666
  chatDocument = oldMsg ? oldMsg.doc() : _this.dateFolder.leafDocumentFromDate(now);
2667
2667
  message = _solidLogic.store.sym(chatDocument.uri + '#' + 'Msg' + timestamp); // const content = store.literal(text)
2668
2668
  me = _solidLogic.authn.currentUser(); // If already logged on
2669
- msg = _signature.getBlankMsg;
2670
- msg.id = message;
2669
+ msg = (0, _signature.getBlankMsg)();
2670
+ msg.id = message.uri;
2671
2671
  if (!oldMsg) {
2672
2672
  _context2.next = 22;
2673
2673
  break;
@@ -2682,7 +2682,7 @@ var ChatChannel = /*#__PURE__*/function () {
2682
2682
  if (deleteIt) {
2683
2683
  // we need to add a specific signature, else anyone can delete a msg ?
2684
2684
  sts.push($rdf.st(message, ns.schema('dateDeleted'), dateStamp, chatDocument));
2685
- msg.dateDeleted = dateStamp;
2685
+ // msg.dateDeleted = dateStamp
2686
2686
  }
2687
2687
  _context2.next = 20;
2688
2688
  break;
@@ -2701,40 +2701,48 @@ var ChatChannel = /*#__PURE__*/function () {
2701
2701
  sts.push($rdf.st(message, ns.sioc('content'), _solidLogic.store.literal(text), chatDocument));
2702
2702
  msg.content = text;
2703
2703
  sts.push($rdf.st(message, ns.dct('created'), dateStamp, chatDocument));
2704
- msg.created = dateStamp;
2704
+ msg.created = dateStamp.value;
2705
2705
  if (!me) {
2706
- _context2.next = 34;
2706
+ _context2.next = 36;
2707
2707
  break;
2708
2708
  }
2709
2709
  sts.push($rdf.st(message, ns.foaf('maker'), me, chatDocument));
2710
- msg.maker = me;
2711
- // privateKey the cached private key of me, cache should be deleted after a certain time
2710
+ msg.maker = me.uri;
2711
+ // privateKey the cached private key of me, cached in store
2712
2712
  _context2.next = 32;
2713
- return (0, _keys.getPrivateKey)(me);
2713
+ return (0, _keys.getPrivateKey)(me.uri);
2714
2714
  case 32:
2715
2715
  privateKey = _context2.sent;
2716
- sts.push($rdf.st(message, $rdf.sym("".concat(_signature.SEC, "Proof")), $rdf.sym((0, _signature.signMsg)(msg, privateKey), chatDocument)));
2717
- case 34:
2718
- _context2.prev = 34;
2719
- _context2.next = 37;
2716
+ // const privateKey0 = 'a11bc5d2eee6cdb3b37f5473a712cad905ccfb13fb2ccdbf1be0a1ac4fdc7d2a'
2717
+ // const pubKey0 = '023a9da707bee1302f66083c9d95673ff969b41607a66f52686fa774d64ceb87'
2718
+ pubKey = (0, _keys.getPublicKey)(me.uri);
2719
+ sig = (0, _signature.signMsg)(msg, privateKey);
2720
+ /* const verify = verifySignature(sig, msg, pubKey) // alain to remove
2721
+ debug.warn('sig ' + sig)
2722
+ debug.warn('verifySign ' + verify)
2723
+ debug.warn(msg) */
2724
+ sts.push($rdf.st(message, $rdf.sym("".concat(_signature.SEC, "Proof")), $rdf.lit(sig), chatDocument));
2725
+ case 36:
2726
+ _context2.prev = 36;
2727
+ _context2.next = 39;
2720
2728
  return _solidLogic.store.updater.update([], sts);
2721
- case 37:
2722
- _context2.next = 45;
2723
- break;
2724
2729
  case 39:
2725
- _context2.prev = 39;
2726
- _context2.t0 = _context2["catch"](34);
2730
+ _context2.next = 47;
2731
+ break;
2732
+ case 41:
2733
+ _context2.prev = 41;
2734
+ _context2.t0 = _context2["catch"](36);
2727
2735
  _errMsg = 'Error saving chat message: ' + _context2.t0;
2728
2736
  debug.warn(_errMsg);
2729
2737
  alert(_errMsg);
2730
2738
  throw new Error(_errMsg);
2731
- case 45:
2739
+ case 47:
2732
2740
  return _context2.abrupt("return", message);
2733
- case 46:
2741
+ case 48:
2734
2742
  case "end":
2735
2743
  return _context2.stop();
2736
2744
  }
2737
- }, _callee2, null, [[34, 39]]);
2745
+ }, _callee2, null, [[36, 41]]);
2738
2746
  })();
2739
2747
  });
2740
2748
  function updateMessage(_x2) {
@@ -4045,107 +4053,156 @@ function generatePublicKey(privateKey) {
4045
4053
  }
4046
4054
  function getPublicKey(webId) {
4047
4055
  var publicKey = publicKeyExists(webId);
4048
- return publicKey === null || publicKey === void 0 ? void 0 : publicKey.uri;
4056
+ return publicKey;
4049
4057
  }
4050
- function publicKeyExists(webId) {
4051
- // find publickey
4058
+ var pubKeyUrl = function pubKeyUrl(webId) {
4052
4059
  var url = new URL(webId);
4053
- url.hash = '';
4054
- _solidLogic.store.fetcher.load(url.href);
4055
- var publicKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'publicKey'));
4056
- return publicKey;
4060
+ var publicKeyUrl = url.origin + '/profile/keys/publicKey.ttl';
4061
+ return publicKeyUrl;
4062
+ };
4063
+ function publicKeyExists(_x) {
4064
+ return _publicKeyExists.apply(this, arguments);
4057
4065
  }
4058
- function privateKeyExists(_x) {
4066
+ function _publicKeyExists() {
4067
+ _publicKeyExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4068
+ var publicKey;
4069
+ return _regenerator["default"].wrap(function _callee$(_context) {
4070
+ while (1) switch (_context.prev = _context.next) {
4071
+ case 0:
4072
+ _context.next = 2;
4073
+ return _solidLogic.store.fetcher.load(pubKeyUrl(webId));
4074
+ case 2:
4075
+ // url.href)
4076
+ publicKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'PublicKey'));
4077
+ return _context.abrupt("return", publicKey === null || publicKey === void 0 ? void 0 : publicKey.value);
4078
+ case 4:
4079
+ case "end":
4080
+ return _context.stop();
4081
+ }
4082
+ }, _callee);
4083
+ }));
4084
+ return _publicKeyExists.apply(this, arguments);
4085
+ }
4086
+ var privKeyUrl = function privKeyUrl(webId) {
4087
+ var url = new URL(webId);
4088
+ var privateKeyUrl = url.origin + '/profile/keys/privateKey.ttl';
4089
+ return privateKeyUrl;
4090
+ };
4091
+ function privateKeyExists(_x2) {
4059
4092
  return _privateKeyExists.apply(this, arguments);
4060
4093
  }
4061
4094
  function _privateKeyExists() {
4062
- _privateKeyExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4063
- var url, privateKeyUrl, privateKey, _err$response, data, contentType, response;
4064
- return _regenerator["default"].wrap(function _callee$(_context) {
4065
- while (1) switch (_context.prev = _context.next) {
4095
+ _privateKeyExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
4096
+ var privateKeyUrl, privateKey, _err$response, data, contentType, response;
4097
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
4098
+ while (1) switch (_context2.prev = _context2.next) {
4066
4099
  case 0:
4067
- url = new URL(webId);
4068
- privateKeyUrl = url.hostname + '/profile/privateKey.ttl';
4069
- _context.prev = 2;
4070
- _solidLogic.store.fetcher.load(privateKeyUrl);
4071
- privateKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'privateKey'));
4072
- return _context.abrupt("return", privateKey);
4100
+ /* const url = new URL(webId)
4101
+ const privateKeyUrl = url.protocol + '//' + url.host + '/profile/privateKey.ttl' */
4102
+ privateKeyUrl = privKeyUrl(webId);
4103
+ /* debug.warn('Alain privateKeyExists')
4104
+ debug.warn(webId)
4105
+ debug.warn(privateKeyUrl) */
4106
+ _context2.prev = 1;
4107
+ _context2.next = 4;
4108
+ return _solidLogic.store.fetcher.load(privateKeyUrl);
4109
+ case 4:
4110
+ privateKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'PrivateKey'));
4111
+ return _context2.abrupt("return", privateKey === null || privateKey === void 0 ? void 0 : privateKey.value);
4073
4112
  case 8:
4074
- _context.prev = 8;
4075
- _context.t0 = _context["catch"](2);
4076
- if (!((_context.t0 === null || _context.t0 === void 0 ? void 0 : (_err$response = _context.t0.response) === null || _err$response === void 0 ? void 0 : _err$response.status) === 404)) {
4077
- _context.next = 25;
4113
+ _context2.prev = 8;
4114
+ _context2.t0 = _context2["catch"](1);
4115
+ if (!((_context2.t0 === null || _context2.t0 === void 0 ? void 0 : (_err$response = _context2.t0.response) === null || _err$response === void 0 ? void 0 : _err$response.status) === 404)) {
4116
+ _context2.next = 25;
4078
4117
  break;
4079
4118
  }
4080
- _context.prev = 11;
4119
+ _context2.prev = 11;
4081
4120
  // create privateKey resource
4082
4121
  data = '';
4083
4122
  contentType = 'text/ttl';
4084
- _context.next = 16;
4123
+ _context2.next = 16;
4085
4124
  return _solidLogic.store.fetcher.webOperation('PUT', privateKeyUrl, {
4086
4125
  data: data,
4087
4126
  contentType: contentType
4088
4127
  });
4089
4128
  case 16:
4090
- response = _context.sent;
4091
- _context.next = 23;
4129
+ response = _context2.sent;
4130
+ _context2.next = 23;
4092
4131
  break;
4093
4132
  case 19:
4094
- _context.prev = 19;
4095
- _context.t1 = _context["catch"](11);
4096
- debug.log('createIfNotExists doc FAILED: ' + privateKeyUrl + ': ' + _context.t1);
4097
- throw _context.t1;
4133
+ _context2.prev = 19;
4134
+ _context2.t1 = _context2["catch"](11);
4135
+ debug.log('createIfNotExists doc FAILED: ' + privateKeyUrl + ': ' + _context2.t1);
4136
+ throw _context2.t1;
4098
4137
  case 23:
4099
4138
  delete _solidLogic.store.fetcher.requested[privateKeyUrl]; // delete cached 404 error
4100
- return _context.abrupt("return", undefined);
4139
+ return _context2.abrupt("return", undefined);
4101
4140
  case 25:
4102
- debug.log('createIfNotExists doc FAILED: ' + privateKeyUrl + ': ' + _context.t0);
4103
- throw _context.t0;
4141
+ debug.log('createIfNotExists doc FAILED: ' + privateKeyUrl + ': ' + _context2.t0);
4142
+ throw _context2.t0;
4104
4143
  case 27:
4105
4144
  case "end":
4106
- return _context.stop();
4145
+ return _context2.stop();
4107
4146
  }
4108
- }, _callee, null, [[2, 8], [11, 19]]);
4147
+ }, _callee2, null, [[1, 8], [11, 19]]);
4109
4148
  }));
4110
4149
  return _privateKeyExists.apply(this, arguments);
4111
4150
  }
4112
- function getPrivateKey(_x2) {
4151
+ function getPrivateKey(_x3) {
4113
4152
  return _getPrivateKey.apply(this, arguments);
4114
4153
  }
4115
4154
  function _getPrivateKey() {
4116
- _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
4117
- var url, privateKeyUrl, publicKey, privateKey, del, add;
4118
- return _regenerator["default"].wrap(function _callee2$(_context2) {
4119
- while (1) switch (_context2.prev = _context2.next) {
4155
+ _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(webId) {
4156
+ var publicKeyUrl, privateKeyUrl, publicKey, privateKey, del, add;
4157
+ return _regenerator["default"].wrap(function _callee3$(_context3) {
4158
+ while (1) switch (_context3.prev = _context3.next) {
4120
4159
  case 0:
4121
- url = new URL(webId);
4122
- privateKeyUrl = url.hostname + '/profile/privateKey.ttl'; // find publickey
4123
- publicKey = publicKeyExists(webId); // find privateKey
4124
- _context2.next = 5;
4160
+ /* const url = new URL(webId)
4161
+ url.hash = '' */
4162
+ /* const privateKeyUrl = url.protocol + '//' + url.host + '/profile/privateKey.ttl' */
4163
+ publicKeyUrl = pubKeyUrl(webId);
4164
+ privateKeyUrl = privKeyUrl(webId); // find publickey
4165
+ _context3.next = 4;
4166
+ return publicKeyExists(webId);
4167
+ case 4:
4168
+ publicKey = _context3.sent;
4169
+ _context3.next = 7;
4125
4170
  return privateKeyExists(webId);
4126
- case 5:
4127
- privateKey = _context2.sent;
4171
+ case 7:
4172
+ privateKey = _context3.sent;
4173
+ // debug.warn('privateKey ' + privateKey)
4174
+ if (privateKey && publicKey !== generatePublicKey(privateKey)) debug.warn('publicKey is not valid');
4175
+
4176
+ // simulate new key pair
4177
+ /* const newPrivateKey = generatePrivateKey()
4178
+ const newPublicKey = generatePublicKey(newPrivateKey)
4179
+ debug.log('newPrivateKey ' + newPrivateKey)
4180
+ debug.log('newPublicKey ' + newPublicKey) */
4181
+
4182
+ // create key pair
4128
4183
  if (!(!privateKey || !publicKey)) {
4129
- _context2.next = 17;
4184
+ _context3.next = 20;
4130
4185
  break;
4131
4186
  }
4132
4187
  del = [];
4133
4188
  add = [];
4134
- if (privateKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'privateKey'), privateKey, $rdf.sym(privateKeyUrl)));
4135
- if (publicKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'publicKey'), publicKey, $rdf.sym(url.href)));
4136
- privateKey = _solidLogic.store.sym(generatePrivateKey());
4137
- publicKey = _solidLogic.store.sym(generatePublicKey(privateKey.uri));
4138
- add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'privateKey'), $rdf.literal(privateKey.uri), $rdf.sym(privateKeyUrl)));
4139
- add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'publicKey'), $rdf.literal(publicKey.uri), $rdf.sym(url.href)));
4140
- _context2.next = 17;
4189
+ if (privateKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'PrivateKey'), $rdf.lit(privateKey), $rdf.sym(privateKeyUrl)));
4190
+ if (publicKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'PublicKey'), $rdf.lit(publicKey), $rdf.sym(publicKeyUrl)));
4191
+ privateKey = generatePrivateKey();
4192
+ publicKey = generatePublicKey(privateKey);
4193
+ /* debug.log('newPrivateKey-1 ' + privateKey)
4194
+ debug.log('newPublicKey-1 ' + publicKey) */
4195
+ add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'PrivateKey'), $rdf.literal(privateKey), $rdf.sym(privateKeyUrl)));
4196
+ add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'PublicKey'), $rdf.literal(publicKey), $rdf.sym(publicKeyUrl)));
4197
+ _context3.next = 20;
4141
4198
  return _solidLogic.store.updater.updateMany(del, add);
4142
- case 17:
4143
- return _context2.abrupt("return", privateKey.uri);
4144
- case 18:
4199
+ case 20:
4200
+ return _context3.abrupt("return", privateKey);
4201
+ case 21:
4145
4202
  case "end":
4146
- return _context2.stop();
4203
+ return _context3.stop();
4147
4204
  }
4148
- }, _callee2);
4205
+ }, _callee3);
4149
4206
  }));
4150
4207
  return _getPrivateKey.apply(this, arguments);
4151
4208
  }
@@ -4277,21 +4334,46 @@ function renderMessageRow(channelObject, message, fresh, options, userContext) {
4277
4334
  var creator = _solidLogic.store.any(message, ns.foaf('maker'));
4278
4335
  var date = _solidLogic.store.any(message, ns.dct('created'));
4279
4336
  var latestVersion = (0, _chatLogic.mostRecentVersion)(message);
4280
- var content = _solidLogic.store.any(latestVersion, ns.sioc('content'));
4281
- var signature = _solidLogic.store.any(message, $rdf.sym("".concat(_signature.SEC, "Proof")));
4337
+ var latestVersionCreator = _solidLogic.store.any(latestVersion, ns.foaf('maker'));
4338
+ // use latest content if same owner, else use original
4339
+ var msgId = creator.uri === latestVersionCreator.uri ? latestVersion : message;
4340
+ var content = _solidLogic.store.any(msgId, ns.sioc('content'));
4341
+ var signature = _solidLogic.store.any(msgId, $rdf.sym("".concat(_signature.SEC, "Proof")));
4342
+ debug.log('alain ' + (signature === null || signature === void 0 ? void 0 : signature.value));
4282
4343
 
4283
4344
  // verify signature
4284
4345
  var msg = (0, _signature.getBlankMsg)();
4285
- msg.id = message;
4286
- msg.created = date;
4287
- // this is not correct.
4288
- // If the message has been edited/deleted we must verify the latest message and may be the intermediate ones
4289
- msg.content = content;
4290
- msg.maker = creator;
4291
-
4292
- // pubKey could be store in a cache for all makers
4293
- var pubKey = (0, _keys.getPublicKey)(creator); // alain no
4294
- if (!(0, _signature.verifySignature)(signature, msg, pubKey)) throw new Error();
4346
+ msg.id = msgId.uri;
4347
+ msg.created = _solidLogic.store.any(msgId, ns.dct('created')).value;
4348
+ msg.content = content.value;
4349
+ msg.maker = creator.uri;
4350
+ try {
4351
+ var publicKey = function publicKey(webId) {
4352
+ var pubKey;
4353
+ (0, _keys.getPublicKey)(webId).then(function (publicKey) {
4354
+ debug.log('alain publicKey ' + publicKey);
4355
+ pubKey = publicKey;
4356
+ });
4357
+ return pubKey;
4358
+ };
4359
+ var pubKey = publicKey(creator.uri); // await getPublicKey(creator.uri)
4360
+ debug.log('alain pubKey ' + pubKey);
4361
+ debug.log(creator.uri);
4362
+ } catch (err) {
4363
+ debug.warn(err);
4364
+ }
4365
+ try {
4366
+ // pubKey could be store in a cache for all makers
4367
+ /* const pubKey0 = '023a9da707bee1302f66083c9d95673ff969b41607a66f52686fa774d64ceb87'
4368
+ debug.warn('publicKeys\n' + pubKey0 + '\n' + pubKey)
4369
+ const privKey0 = getPrivateKey(creator.uri) // alain to remove
4370
+ // unsigned messages should be signaled as unsecured
4371
+ debug.warn(msg)
4372
+ debug.warn(signature?.value) */
4373
+ if (signature !== null && signature !== void 0 && signature.value && !(0, _signature.verifySignature)(signature.value, msg, pubKey)) throw new Error('invalid signature');
4374
+ } catch (err) {
4375
+ debug.log(err);
4376
+ }
4295
4377
  var originalMessage = (0, _chatLogic.originalVersion)(message);
4296
4378
  var edited = !message.sameTerm(originalMessage);
4297
4379
  var sortDate = _solidLogic.store.the(originalMessage, ns.dct('created'), null, originalMessage.doc()); // In message
@@ -5105,7 +5187,7 @@ var utf8Encoder = new TextEncoder();
5105
5187
  exports.utf8Encoder = utf8Encoder;
5106
5188
  var SEC = 'https://w3id.org/security#'; // Proof, VerificationMethod
5107
5189
  exports.SEC = SEC;
5108
- var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivatKey, PublicKey
5190
+ var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivateKey, PublicKey
5109
5191
 
5110
5192
  /* eslint-disable no-unused-vars */
5111
5193
  /* export enum Kind {
@@ -13238,8 +13320,8 @@ Object.defineProperty(exports, "__esModule", ({
13238
13320
  }));
13239
13321
  exports.versionInfo = void 0;
13240
13322
  var versionInfo = {
13241
- buildTime: '2023-04-19T18:00:23Z',
13242
- commit: '9d7e618ee7fcecf32422bd474b50a9bd5f142647',
13323
+ buildTime: '2023-04-25T08:53:43Z',
13324
+ commit: '9f7a01da36a7e5e6b71dafcecf7bc9393366980e',
13243
13325
  npmInfo: {
13244
13326
  'solid-ui': '2.4.27',
13245
13327
  npm: '8.19.4',
@@ -25402,6 +25484,8 @@ __webpack_require__.r(__webpack_exports__);
25402
25484
  /* harmony import */ var _inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @inrupt/oidc-client */ "./node_modules/@inrupt/oidc-client/lib/oidc-client.min.js");
25403
25485
  /* harmony import */ var _inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0__);
25404
25486
  /* harmony import */ var _inrupt_solid_client_authn_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.mjs");
25487
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
25488
+
25405
25489
 
25406
25490
 
25407
25491
 
@@ -25555,7 +25639,7 @@ async function getTokens(issuer, client, data, dpop) {
25555
25639
  headers,
25556
25640
  body: new URLSearchParams(requestBody).toString(),
25557
25641
  };
25558
- const rawTokenResponse = await await fetch(issuer.tokenEndpoint, tokenRequestInit);
25642
+ const rawTokenResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, tokenRequestInit);
25559
25643
  const jsonTokenResponse = (await rawTokenResponse.json());
25560
25644
  const tokenResponse = validateTokenEndpointResponse(jsonTokenResponse, dpop);
25561
25645
  const webId = await (0,_inrupt_solid_client_authn_core__WEBPACK_IMPORTED_MODULE_1__.getWebidFromTokenPayload)(tokenResponse.id_token, issuer.jwksUri, issuer.issuer, client.clientId);
@@ -25639,7 +25723,7 @@ async function refresh(refreshToken, issuer, client, dpopKey) {
25639
25723
  else if (isValidUrl(client.clientId)) {
25640
25724
  requestBody.client_id = client.clientId;
25641
25725
  }
25642
- const rawResponse = await fetch(issuer.tokenEndpoint, {
25726
+ const rawResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, {
25643
25727
  method: "POST",
25644
25728
  body: new URLSearchParams(requestBody).toString(),
25645
25729
  headers: {
@@ -25754,8 +25838,9 @@ e.read=function(t,e,r,n,i){var o,s,a=8*i-n-1,u=(1<<a)-1,c=u>>1,h=-7,l=r?i-1:0,f=
25754
25838
 
25755
25839
  Object.defineProperty(exports, "__esModule", ({ value: true }));
25756
25840
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
25841
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
25757
25842
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
25758
- const globalFetch = (request, init) => window.fetch(request, init);
25843
+ const globalFetch = (request, init) => (0, universal_fetch_1.fetch)(request, init);
25759
25844
  class ClientAuthentication {
25760
25845
  constructor(loginHandler, redirectHandler, logoutHandler, sessionInfoManager, issuerConfigFetcher) {
25761
25846
  this.loginHandler = loginHandler;
@@ -26249,6 +26334,7 @@ exports["default"] = ClientRegistrar;
26249
26334
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26250
26335
  exports.WELL_KNOWN_OPENID_CONFIG = void 0;
26251
26336
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26337
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26252
26338
  exports.WELL_KNOWN_OPENID_CONFIG = ".well-known/openid-configuration";
26253
26339
  const issuerConfigKeyMap = {
26254
26340
  issuer: {
@@ -26355,7 +26441,7 @@ class IssuerConfigFetcher {
26355
26441
  async fetchConfig(issuer) {
26356
26442
  let issuerConfig;
26357
26443
  const openIdConfigUrl = new URL(exports.WELL_KNOWN_OPENID_CONFIG, issuer.endsWith("/") ? issuer : `${issuer}/`).href;
26358
- const issuerConfigRequestBody = await window.fetch(openIdConfigUrl);
26444
+ const issuerConfigRequestBody = await (0, universal_fetch_1.fetch)(openIdConfigUrl);
26359
26445
  try {
26360
26446
  issuerConfig = processConfig(await issuerConfigRequestBody.json());
26361
26447
  }
@@ -26458,6 +26544,7 @@ exports["default"] = Redirector;
26458
26544
 
26459
26545
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26460
26546
  exports.AuthCodeRedirectHandler = void 0;
26547
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26461
26548
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26462
26549
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
26463
26550
  class AuthCodeRedirectHandler {
@@ -26521,7 +26608,7 @@ class AuthCodeRedirectHandler {
26521
26608
  tokenRefresher: this.tokerRefresher,
26522
26609
  };
26523
26610
  }
26524
- const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(fetch, tokens.accessToken, {
26611
+ const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(universal_fetch_1.fetch, tokens.accessToken, {
26525
26612
  dpopKey: tokens.dpopKey,
26526
26613
  refreshOptions,
26527
26614
  eventEmitter,
@@ -26759,11 +26846,12 @@ exports.SessionInfoManager = exports.clear = exports.getUnauthenticatedSession =
26759
26846
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26760
26847
  const uuid_1 = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-browser/node_modules/uuid/dist/commonjs-browser/index.js");
26761
26848
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
26849
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26762
26850
  function getUnauthenticatedSession() {
26763
26851
  return {
26764
26852
  isLoggedIn: false,
26765
26853
  sessionId: (0, uuid_1.v4)(),
26766
- fetch,
26854
+ fetch: universal_fetch_1.fetch,
26767
26855
  };
26768
26856
  }
26769
26857
  exports.getUnauthenticatedSession = getUnauthenticatedSession;
@@ -27916,513 +28004,513 @@ exports["default"] = _default;
27916
28004
 
27917
28005
 
27918
28006
  var events = __webpack_require__(/*! events */ "./node_modules/events/events.js");
27919
- var crossFetch = __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js");
28007
+ var universalFetch = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
27920
28008
  var jose = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
27921
28009
  var uuid = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-core/node_modules/uuid/dist/commonjs-browser/index.js");
27922
28010
 
27923
- const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
27924
- const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
27925
- const EVENTS = {
27926
- ERROR: "error",
27927
- LOGIN: "login",
27928
- LOGOUT: "logout",
27929
- NEW_REFRESH_TOKEN: "newRefreshToken",
27930
- SESSION_EXPIRED: "sessionExpired",
27931
- SESSION_EXTENDED: "sessionExtended",
27932
- SESSION_RESTORED: "sessionRestore",
27933
- TIMEOUT_SET: "timeoutSet",
27934
- };
27935
- const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
27936
- const SCOPE_OPENID = "openid";
27937
- const SCOPE_OFFLINE = "offline_access";
27938
- const SCOPE_WEBID = "webid";
28011
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
28012
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
28013
+ const EVENTS = {
28014
+ ERROR: "error",
28015
+ LOGIN: "login",
28016
+ LOGOUT: "logout",
28017
+ NEW_REFRESH_TOKEN: "newRefreshToken",
28018
+ SESSION_EXPIRED: "sessionExpired",
28019
+ SESSION_EXTENDED: "sessionExtended",
28020
+ SESSION_RESTORED: "sessionRestore",
28021
+ TIMEOUT_SET: "timeoutSet",
28022
+ };
28023
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
28024
+ const SCOPE_OPENID = "openid";
28025
+ const SCOPE_OFFLINE = "offline_access";
28026
+ const SCOPE_WEBID = "webid";
27939
28027
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
27940
28028
 
27941
- const buildProxyHandler = (toExclude, errorMessage) => ({
27942
- get(target, prop, receiver) {
27943
- if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&
27944
- Object.getOwnPropertyNames(toExclude).includes(prop)) {
27945
- throw new Error(`${errorMessage}: [${prop}] is not supported`);
27946
- }
27947
- return Reflect.get(target, prop, receiver);
27948
- },
28029
+ const buildProxyHandler = (toExclude, errorMessage) => ({
28030
+ get(target, prop, receiver) {
28031
+ if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&
28032
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
28033
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
28034
+ }
28035
+ return Reflect.get(target, prop, receiver);
28036
+ },
27949
28037
  });
27950
28038
 
27951
- class AggregateHandler {
27952
- constructor(handleables) {
27953
- this.handleables = handleables;
27954
- }
27955
- async getProperHandler(params) {
27956
- const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
27957
- for (let i = 0; i < canHandleList.length; i += 1) {
27958
- if (canHandleList[i]) {
27959
- return this.handleables[i];
27960
- }
27961
- }
27962
- return null;
27963
- }
27964
- async canHandle(...params) {
27965
- return (await this.getProperHandler(params)) !== null;
27966
- }
27967
- async handle(...params) {
27968
- const handler = await this.getProperHandler(params);
27969
- if (handler) {
27970
- return handler.handle(...params);
27971
- }
27972
- throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
27973
- .map((param) => {
27974
- try {
27975
- return JSON.stringify(param);
27976
- }
27977
- catch (err) {
27978
- return param.toString();
27979
- }
27980
- })
27981
- .join(", ")}`);
27982
- }
28039
+ class AggregateHandler {
28040
+ constructor(handleables) {
28041
+ this.handleables = handleables;
28042
+ }
28043
+ async getProperHandler(params) {
28044
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
28045
+ for (let i = 0; i < canHandleList.length; i += 1) {
28046
+ if (canHandleList[i]) {
28047
+ return this.handleables[i];
28048
+ }
28049
+ }
28050
+ return null;
28051
+ }
28052
+ async canHandle(...params) {
28053
+ return (await this.getProperHandler(params)) !== null;
28054
+ }
28055
+ async handle(...params) {
28056
+ const handler = await this.getProperHandler(params);
28057
+ if (handler) {
28058
+ return handler.handle(...params);
28059
+ }
28060
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
28061
+ .map((param) => {
28062
+ try {
28063
+ return JSON.stringify(param);
28064
+ }
28065
+ catch (err) {
28066
+ return param.toString();
28067
+ }
28068
+ })
28069
+ .join(", ")}`);
28070
+ }
27983
28071
  }
27984
28072
 
27985
- async function fetchJwks(jwksIri, issuerIri) {
27986
- const jwksResponse = await crossFetch.fetch(jwksIri);
27987
- if (jwksResponse.status !== 200) {
27988
- throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
27989
- }
27990
- let jwk;
27991
- try {
27992
- jwk = (await jwksResponse.json()).keys[0];
27993
- }
27994
- catch (e) {
27995
- throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
27996
- }
27997
- return jwk;
27998
- }
27999
- async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
28000
- const jwk = await fetchJwks(jwksIri, issuerIri);
28001
- let payload;
28002
- try {
28003
- const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {
28004
- issuer: issuerIri,
28005
- audience: clientId,
28006
- });
28007
- payload = verifiedPayload;
28008
- }
28009
- catch (e) {
28010
- throw new Error(`Token verification failed: ${e.stack}`);
28011
- }
28012
- if (typeof payload.webid === "string") {
28013
- return payload.webid;
28014
- }
28015
- if (typeof payload.sub !== "string") {
28016
- throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
28017
- }
28018
- try {
28019
- new URL(payload.sub);
28020
- return payload.sub;
28021
- }
28022
- catch (e) {
28023
- throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
28024
- }
28073
+ async function fetchJwks(jwksIri, issuerIri) {
28074
+ const jwksResponse = await universalFetch.fetch(jwksIri);
28075
+ if (jwksResponse.status !== 200) {
28076
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
28077
+ }
28078
+ let jwk;
28079
+ try {
28080
+ jwk = (await jwksResponse.json()).keys[0];
28081
+ }
28082
+ catch (e) {
28083
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
28084
+ }
28085
+ return jwk;
28086
+ }
28087
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
28088
+ const jwk = await fetchJwks(jwksIri, issuerIri);
28089
+ let payload;
28090
+ try {
28091
+ const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {
28092
+ issuer: issuerIri,
28093
+ audience: clientId,
28094
+ });
28095
+ payload = verifiedPayload;
28096
+ }
28097
+ catch (e) {
28098
+ throw new Error(`Token verification failed: ${e.stack}`);
28099
+ }
28100
+ if (typeof payload.webid === "string") {
28101
+ return payload.webid;
28102
+ }
28103
+ if (typeof payload.sub !== "string") {
28104
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
28105
+ }
28106
+ try {
28107
+ new URL(payload.sub);
28108
+ return payload.sub;
28109
+ }
28110
+ catch (e) {
28111
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
28112
+ }
28025
28113
  }
28026
28114
 
28027
- function isValidRedirectUrl(redirectUrl) {
28028
- try {
28029
- const urlObject = new URL(redirectUrl);
28030
- return urlObject.hash === "";
28031
- }
28032
- catch (e) {
28033
- return false;
28034
- }
28115
+ function isValidRedirectUrl(redirectUrl) {
28116
+ try {
28117
+ const urlObject = new URL(redirectUrl);
28118
+ return urlObject.hash === "";
28119
+ }
28120
+ catch (e) {
28121
+ return false;
28122
+ }
28035
28123
  }
28036
28124
 
28037
- function isSupportedTokenType(token) {
28038
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
28125
+ function isSupportedTokenType(token) {
28126
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
28039
28127
  }
28040
28128
 
28041
28129
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
28042
28130
 
28043
- function isValidUrl(url) {
28044
- try {
28045
- new URL(url);
28046
- return true;
28047
- }
28048
- catch (_a) {
28049
- return false;
28050
- }
28051
- }
28052
- function determineSigningAlg(supported, preferred) {
28053
- var _a;
28054
- return ((_a = preferred.find((signingAlg) => {
28055
- return supported.includes(signingAlg);
28056
- })) !== null && _a !== void 0 ? _a : null);
28057
- }
28058
- function determineClientType(options, issuerConfig) {
28059
- if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
28060
- return "static";
28061
- }
28062
- if (issuerConfig.scopesSupported.includes("webid") &&
28063
- options.clientId !== undefined &&
28064
- isValidUrl(options.clientId)) {
28065
- return "solid-oidc";
28066
- }
28067
- return "dynamic";
28068
- }
28069
- async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
28070
- const clientType = determineClientType(options, issuerConfig);
28071
- if (clientType === "dynamic") {
28072
- return clientRegistrar.getClient({
28073
- sessionId: options.sessionId,
28074
- clientName: options.clientName,
28075
- redirectUrl: options.redirectUrl,
28076
- }, issuerConfig);
28077
- }
28078
- await storageUtility.setForUser(options.sessionId, {
28079
- clientId: options.clientId,
28080
- });
28081
- if (options.clientSecret) {
28082
- await storageUtility.setForUser(options.sessionId, {
28083
- clientSecret: options.clientSecret,
28084
- });
28085
- }
28086
- if (options.clientName) {
28087
- await storageUtility.setForUser(options.sessionId, {
28088
- clientName: options.clientName,
28089
- });
28090
- }
28091
- return {
28092
- clientId: options.clientId,
28093
- clientSecret: options.clientSecret,
28094
- clientName: options.clientName,
28095
- clientType,
28096
- };
28131
+ function isValidUrl(url) {
28132
+ try {
28133
+ new URL(url);
28134
+ return true;
28135
+ }
28136
+ catch (_a) {
28137
+ return false;
28138
+ }
28139
+ }
28140
+ function determineSigningAlg(supported, preferred) {
28141
+ var _a;
28142
+ return ((_a = preferred.find((signingAlg) => {
28143
+ return supported.includes(signingAlg);
28144
+ })) !== null && _a !== void 0 ? _a : null);
28145
+ }
28146
+ function determineClientType(options, issuerConfig) {
28147
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
28148
+ return "static";
28149
+ }
28150
+ if (issuerConfig.scopesSupported.includes("webid") &&
28151
+ options.clientId !== undefined &&
28152
+ isValidUrl(options.clientId)) {
28153
+ return "solid-oidc";
28154
+ }
28155
+ return "dynamic";
28156
+ }
28157
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
28158
+ const clientType = determineClientType(options, issuerConfig);
28159
+ if (clientType === "dynamic") {
28160
+ return clientRegistrar.getClient({
28161
+ sessionId: options.sessionId,
28162
+ clientName: options.clientName,
28163
+ redirectUrl: options.redirectUrl,
28164
+ }, issuerConfig);
28165
+ }
28166
+ await storageUtility.setForUser(options.sessionId, {
28167
+ clientId: options.clientId,
28168
+ });
28169
+ if (options.clientSecret) {
28170
+ await storageUtility.setForUser(options.sessionId, {
28171
+ clientSecret: options.clientSecret,
28172
+ });
28173
+ }
28174
+ if (options.clientName) {
28175
+ await storageUtility.setForUser(options.sessionId, {
28176
+ clientName: options.clientName,
28177
+ });
28178
+ }
28179
+ return {
28180
+ clientId: options.clientId,
28181
+ clientSecret: options.clientSecret,
28182
+ clientName: options.clientName,
28183
+ clientType,
28184
+ };
28097
28185
  }
28098
28186
 
28099
- async function getSessionIdFromOauthState(storageUtility, oauthState) {
28100
- return storageUtility.getForUser(oauthState, "sessionId");
28101
- }
28102
- async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
28103
- try {
28104
- const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
28105
- storageUtility.getForUser(sessionId, "issuer", {
28106
- errorIfNull: true,
28107
- }),
28108
- storageUtility.getForUser(sessionId, "codeVerifier"),
28109
- storageUtility.getForUser(sessionId, "redirectUrl"),
28110
- storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
28111
- ]);
28112
- await storageUtility.deleteForUser(sessionId, "codeVerifier");
28113
- const issuerConfig = await configFetcher.fetchConfig(issuerIri);
28114
- return {
28115
- codeVerifier,
28116
- redirectUrl: storedRedirectIri,
28117
- issuerConfig,
28118
- dpop: dpop === "true",
28119
- };
28120
- }
28121
- catch (e) {
28122
- throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
28123
- }
28124
- }
28125
- async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
28126
- if (refreshToken !== undefined) {
28127
- await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
28128
- }
28129
- if (webId !== undefined) {
28130
- await storageUtility.setForUser(sessionId, { webId }, { secure });
28131
- }
28132
- if (isLoggedIn !== undefined) {
28133
- await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
28134
- }
28135
- if (dpopKey !== undefined) {
28136
- await storageUtility.setForUser(sessionId, {
28137
- publicKey: JSON.stringify(dpopKey.publicKey),
28138
- privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),
28139
- }, { secure });
28140
- }
28141
- }
28142
- class StorageUtility {
28143
- constructor(secureStorage, insecureStorage) {
28144
- this.secureStorage = secureStorage;
28145
- this.insecureStorage = insecureStorage;
28146
- }
28147
- getKey(userId) {
28148
- return `solidClientAuthenticationUser:${userId}`;
28149
- }
28150
- async getUserData(userId, secure) {
28151
- const stored = await (secure
28152
- ? this.secureStorage
28153
- : this.insecureStorage).get(this.getKey(userId));
28154
- if (stored === undefined) {
28155
- return {};
28156
- }
28157
- try {
28158
- return JSON.parse(stored);
28159
- }
28160
- catch (err) {
28161
- throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
28162
- }
28163
- }
28164
- async setUserData(userId, data, secure) {
28165
- await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
28166
- }
28167
- async get(key, options) {
28168
- const value = await ((options === null || options === void 0 ? void 0 : options.secure)
28169
- ? this.secureStorage
28170
- : this.insecureStorage).get(key);
28171
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28172
- throw new Error(`[${key}] is not stored`);
28173
- }
28174
- return value;
28175
- }
28176
- async set(key, value, options) {
28177
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
28178
- }
28179
- async delete(key, options) {
28180
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
28181
- }
28182
- async getForUser(userId, key, options) {
28183
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28184
- let value;
28185
- if (!userData || !userData[key]) {
28186
- value = undefined;
28187
- }
28188
- value = userData[key];
28189
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28190
- throw new Error(`Field [${key}] for user [${userId}] is not stored`);
28191
- }
28192
- return value || undefined;
28193
- }
28194
- async setForUser(userId, values, options) {
28195
- let userData;
28196
- try {
28197
- userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28198
- }
28199
- catch (_a) {
28200
- userData = {};
28201
- }
28202
- await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
28203
- }
28204
- async deleteForUser(userId, key, options) {
28205
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28206
- delete userData[key];
28207
- await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
28208
- }
28209
- async deleteAllUserData(userId, options) {
28210
- await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
28211
- }
28187
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
28188
+ return storageUtility.getForUser(oauthState, "sessionId");
28189
+ }
28190
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
28191
+ try {
28192
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
28193
+ storageUtility.getForUser(sessionId, "issuer", {
28194
+ errorIfNull: true,
28195
+ }),
28196
+ storageUtility.getForUser(sessionId, "codeVerifier"),
28197
+ storageUtility.getForUser(sessionId, "redirectUrl"),
28198
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
28199
+ ]);
28200
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
28201
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
28202
+ return {
28203
+ codeVerifier,
28204
+ redirectUrl: storedRedirectIri,
28205
+ issuerConfig,
28206
+ dpop: dpop === "true",
28207
+ };
28208
+ }
28209
+ catch (e) {
28210
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
28211
+ }
28212
+ }
28213
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
28214
+ if (refreshToken !== undefined) {
28215
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
28216
+ }
28217
+ if (webId !== undefined) {
28218
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
28219
+ }
28220
+ if (isLoggedIn !== undefined) {
28221
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
28222
+ }
28223
+ if (dpopKey !== undefined) {
28224
+ await storageUtility.setForUser(sessionId, {
28225
+ publicKey: JSON.stringify(dpopKey.publicKey),
28226
+ privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),
28227
+ }, { secure });
28228
+ }
28229
+ }
28230
+ class StorageUtility {
28231
+ constructor(secureStorage, insecureStorage) {
28232
+ this.secureStorage = secureStorage;
28233
+ this.insecureStorage = insecureStorage;
28234
+ }
28235
+ getKey(userId) {
28236
+ return `solidClientAuthenticationUser:${userId}`;
28237
+ }
28238
+ async getUserData(userId, secure) {
28239
+ const stored = await (secure
28240
+ ? this.secureStorage
28241
+ : this.insecureStorage).get(this.getKey(userId));
28242
+ if (stored === undefined) {
28243
+ return {};
28244
+ }
28245
+ try {
28246
+ return JSON.parse(stored);
28247
+ }
28248
+ catch (err) {
28249
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
28250
+ }
28251
+ }
28252
+ async setUserData(userId, data, secure) {
28253
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
28254
+ }
28255
+ async get(key, options) {
28256
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
28257
+ ? this.secureStorage
28258
+ : this.insecureStorage).get(key);
28259
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28260
+ throw new Error(`[${key}] is not stored`);
28261
+ }
28262
+ return value;
28263
+ }
28264
+ async set(key, value, options) {
28265
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
28266
+ }
28267
+ async delete(key, options) {
28268
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
28269
+ }
28270
+ async getForUser(userId, key, options) {
28271
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28272
+ let value;
28273
+ if (!userData || !userData[key]) {
28274
+ value = undefined;
28275
+ }
28276
+ value = userData[key];
28277
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28278
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
28279
+ }
28280
+ return value || undefined;
28281
+ }
28282
+ async setForUser(userId, values, options) {
28283
+ let userData;
28284
+ try {
28285
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28286
+ }
28287
+ catch (_a) {
28288
+ userData = {};
28289
+ }
28290
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
28291
+ }
28292
+ async deleteForUser(userId, key, options) {
28293
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28294
+ delete userData[key];
28295
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
28296
+ }
28297
+ async deleteAllUserData(userId, options) {
28298
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
28299
+ }
28212
28300
  }
28213
28301
 
28214
- class InMemoryStorage {
28215
- constructor() {
28216
- this.map = {};
28217
- }
28218
- async get(key) {
28219
- return this.map[key] || undefined;
28220
- }
28221
- async set(key, value) {
28222
- this.map[key] = value;
28223
- }
28224
- async delete(key) {
28225
- delete this.map[key];
28226
- }
28302
+ class InMemoryStorage {
28303
+ constructor() {
28304
+ this.map = {};
28305
+ }
28306
+ async get(key) {
28307
+ return this.map[key] || undefined;
28308
+ }
28309
+ async set(key, value) {
28310
+ this.map[key] = value;
28311
+ }
28312
+ async delete(key) {
28313
+ delete this.map[key];
28314
+ }
28227
28315
  }
28228
28316
 
28229
- class ConfigurationError extends Error {
28230
- constructor(message) {
28231
- super(message);
28232
- }
28317
+ class ConfigurationError extends Error {
28318
+ constructor(message) {
28319
+ super(message);
28320
+ }
28233
28321
  }
28234
28322
 
28235
- class NotImplementedError extends Error {
28236
- constructor(methodName) {
28237
- super(`[${methodName}] is not implemented`);
28238
- }
28323
+ class NotImplementedError extends Error {
28324
+ constructor(methodName) {
28325
+ super(`[${methodName}] is not implemented`);
28326
+ }
28239
28327
  }
28240
28328
 
28241
- class InvalidResponseError extends Error {
28242
- constructor(missingFields) {
28243
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28244
- this.missingFields = missingFields;
28245
- }
28329
+ class InvalidResponseError extends Error {
28330
+ constructor(missingFields) {
28331
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28332
+ this.missingFields = missingFields;
28333
+ }
28246
28334
  }
28247
28335
 
28248
- class OidcProviderError extends Error {
28249
- constructor(message, error, errorDescription) {
28250
- super(message);
28251
- this.error = error;
28252
- this.errorDescription = errorDescription;
28253
- }
28336
+ class OidcProviderError extends Error {
28337
+ constructor(message, error, errorDescription) {
28338
+ super(message);
28339
+ this.error = error;
28340
+ this.errorDescription = errorDescription;
28341
+ }
28254
28342
  }
28255
28343
 
28256
- function normalizeHTU(audience) {
28257
- const audienceUrl = new URL(audience);
28258
- return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
28259
- }
28260
- async function createDpopHeader(audience, method, dpopKey) {
28261
- return new jose.SignJWT({
28262
- htu: normalizeHTU(audience),
28263
- htm: method.toUpperCase(),
28264
- jti: uuid.v4(),
28265
- })
28266
- .setProtectedHeader({
28267
- alg: PREFERRED_SIGNING_ALG[0],
28268
- jwk: dpopKey.publicKey,
28269
- typ: "dpop+jwt",
28270
- })
28271
- .setIssuedAt()
28272
- .sign(dpopKey.privateKey, {});
28273
- }
28274
- async function generateDpopKeyPair() {
28275
- const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);
28276
- const dpopKeyPair = {
28277
- privateKey,
28278
- publicKey: await jose.exportJWK(publicKey),
28279
- };
28280
- [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
28281
- return dpopKeyPair;
28344
+ function normalizeHTU(audience) {
28345
+ const audienceUrl = new URL(audience);
28346
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
28347
+ }
28348
+ async function createDpopHeader(audience, method, dpopKey) {
28349
+ return new jose.SignJWT({
28350
+ htu: normalizeHTU(audience),
28351
+ htm: method.toUpperCase(),
28352
+ jti: uuid.v4(),
28353
+ })
28354
+ .setProtectedHeader({
28355
+ alg: PREFERRED_SIGNING_ALG[0],
28356
+ jwk: dpopKey.publicKey,
28357
+ typ: "dpop+jwt",
28358
+ })
28359
+ .setIssuedAt()
28360
+ .sign(dpopKey.privateKey, {});
28361
+ }
28362
+ async function generateDpopKeyPair() {
28363
+ const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);
28364
+ const dpopKeyPair = {
28365
+ privateKey,
28366
+ publicKey: await jose.exportJWK(publicKey),
28367
+ };
28368
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
28369
+ return dpopKeyPair;
28282
28370
  }
28283
28371
 
28284
- const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
28285
- function isExpectedAuthError(statusCode) {
28286
- return [401, 403].includes(statusCode);
28287
- }
28288
- async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
28289
- var _a;
28290
- const headers = new crossFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28291
- headers.set("Authorization", `DPoP ${authToken}`);
28292
- headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
28293
- return {
28294
- ...defaultOptions,
28295
- headers,
28296
- };
28297
- }
28298
- async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
28299
- if (dpopKey !== undefined) {
28300
- return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
28301
- }
28302
- const headers = new crossFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28303
- headers.set("Authorization", `Bearer ${authToken}`);
28304
- return {
28305
- ...defaultOptions,
28306
- headers,
28307
- };
28308
- }
28309
- async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
28310
- return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
28311
- }
28312
- async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
28313
- var _a;
28314
- const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
28315
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
28316
- if (typeof tokenSet.refreshToken === "string") {
28317
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
28318
- }
28319
- return {
28320
- accessToken: tokenSet.accessToken,
28321
- refreshToken: tokenSet.refreshToken,
28322
- expiresIn: tokenSet.expiresIn,
28323
- };
28324
- }
28325
- const computeRefreshDelay = (expiresIn) => {
28326
- if (expiresIn !== undefined) {
28327
- return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
28328
- ?
28329
- expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
28330
- : expiresIn;
28331
- }
28332
- return DEFAULT_EXPIRATION_TIME_SECONDS;
28333
- };
28334
- async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
28335
- var _a;
28336
- let currentAccessToken = accessToken;
28337
- let latestTimeout;
28338
- const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
28339
- if (currentRefreshOptions !== undefined) {
28340
- const proactivelyRefreshToken = async () => {
28341
- var _a, _b, _c, _d;
28342
- try {
28343
- const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
28344
- currentAccessToken = refreshedAccessToken;
28345
- if (refreshToken !== undefined) {
28346
- currentRefreshOptions.refreshToken = refreshToken;
28347
- }
28348
- clearTimeout(latestTimeout);
28349
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
28350
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28351
- }
28352
- catch (e) {
28353
- if (e instanceof OidcProviderError) {
28354
- (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
28355
- (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
28356
- }
28357
- if (e instanceof InvalidResponseError &&
28358
- e.missingFields.includes("access_token")) {
28359
- (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
28360
- }
28361
- }
28362
- };
28363
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
28364
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28365
- }
28366
- else if (options !== undefined && options.eventEmitter !== undefined) {
28367
- const expirationTimeout = setTimeout(() => {
28368
- options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
28369
- }, computeRefreshDelay(options.expiresIn) * 1000);
28370
- options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
28371
- }
28372
- return async (url, requestInit) => {
28373
- let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
28374
- const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
28375
- if (response.ok || failedButNotExpectedAuthError) {
28376
- return response;
28377
- }
28378
- const hasBeenRedirected = response.url !== url;
28379
- if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
28380
- response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
28381
- }
28382
- return response;
28383
- };
28372
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
28373
+ function isExpectedAuthError(statusCode) {
28374
+ return [401, 403].includes(statusCode);
28375
+ }
28376
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
28377
+ var _a;
28378
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28379
+ headers.set("Authorization", `DPoP ${authToken}`);
28380
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
28381
+ return {
28382
+ ...defaultOptions,
28383
+ headers,
28384
+ };
28385
+ }
28386
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
28387
+ if (dpopKey !== undefined) {
28388
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
28389
+ }
28390
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28391
+ headers.set("Authorization", `Bearer ${authToken}`);
28392
+ return {
28393
+ ...defaultOptions,
28394
+ headers,
28395
+ };
28396
+ }
28397
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
28398
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
28399
+ }
28400
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
28401
+ var _a;
28402
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
28403
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
28404
+ if (typeof tokenSet.refreshToken === "string") {
28405
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
28406
+ }
28407
+ return {
28408
+ accessToken: tokenSet.accessToken,
28409
+ refreshToken: tokenSet.refreshToken,
28410
+ expiresIn: tokenSet.expiresIn,
28411
+ };
28412
+ }
28413
+ const computeRefreshDelay = (expiresIn) => {
28414
+ if (expiresIn !== undefined) {
28415
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
28416
+ ?
28417
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
28418
+ : expiresIn;
28419
+ }
28420
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
28421
+ };
28422
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
28423
+ var _a;
28424
+ let currentAccessToken = accessToken;
28425
+ let latestTimeout;
28426
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
28427
+ if (currentRefreshOptions !== undefined) {
28428
+ const proactivelyRefreshToken = async () => {
28429
+ var _a, _b, _c, _d;
28430
+ try {
28431
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
28432
+ currentAccessToken = refreshedAccessToken;
28433
+ if (refreshToken !== undefined) {
28434
+ currentRefreshOptions.refreshToken = refreshToken;
28435
+ }
28436
+ clearTimeout(latestTimeout);
28437
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
28438
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28439
+ }
28440
+ catch (e) {
28441
+ if (e instanceof OidcProviderError) {
28442
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
28443
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
28444
+ }
28445
+ if (e instanceof InvalidResponseError &&
28446
+ e.missingFields.includes("access_token")) {
28447
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
28448
+ }
28449
+ }
28450
+ };
28451
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
28452
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28453
+ }
28454
+ else if (options !== undefined && options.eventEmitter !== undefined) {
28455
+ const expirationTimeout = setTimeout(() => {
28456
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
28457
+ }, computeRefreshDelay(options.expiresIn) * 1000);
28458
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
28459
+ }
28460
+ return async (url, requestInit) => {
28461
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
28462
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
28463
+ if (response.ok || failedButNotExpectedAuthError) {
28464
+ return response;
28465
+ }
28466
+ const hasBeenRedirected = response.url !== url;
28467
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
28468
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
28469
+ }
28470
+ return response;
28471
+ };
28384
28472
  }
28385
28473
 
28386
- const StorageUtilityGetResponse = "getResponse";
28387
- const StorageUtilityMock = {
28388
- get: async (key, options) => StorageUtilityGetResponse,
28389
- set: async (key, value) => {
28390
- },
28391
- delete: async (key) => {
28392
- },
28393
- getForUser: async (userId, key, options) => StorageUtilityGetResponse,
28394
- setForUser: async (userId, values, options) => {
28395
- },
28396
- deleteForUser: async (userId, key, options) => {
28397
- },
28398
- deleteAllUserData: async (userId, options) => {
28399
- },
28400
- };
28401
- const mockStorage = (stored) => {
28402
- const store = stored;
28403
- return {
28404
- get: async (key) => {
28405
- if (store[key] === undefined) {
28406
- return undefined;
28407
- }
28408
- if (typeof store[key] === "string") {
28409
- return store[key];
28410
- }
28411
- return JSON.stringify(store[key]);
28412
- },
28413
- set: async (key, value) => {
28414
- store[key] = value;
28415
- },
28416
- delete: async (key) => {
28417
- delete store[key];
28418
- },
28419
- };
28420
- };
28421
- const mockStorageUtility = (stored, isSecure = false) => {
28422
- if (isSecure) {
28423
- return new StorageUtility(mockStorage(stored), mockStorage({}));
28424
- }
28425
- return new StorageUtility(mockStorage({}), mockStorage(stored));
28474
+ const StorageUtilityGetResponse = "getResponse";
28475
+ const StorageUtilityMock = {
28476
+ get: async (key, options) => StorageUtilityGetResponse,
28477
+ set: async (key, value) => {
28478
+ },
28479
+ delete: async (key) => {
28480
+ },
28481
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
28482
+ setForUser: async (userId, values, options) => {
28483
+ },
28484
+ deleteForUser: async (userId, key, options) => {
28485
+ },
28486
+ deleteAllUserData: async (userId, options) => {
28487
+ },
28488
+ };
28489
+ const mockStorage = (stored) => {
28490
+ const store = stored;
28491
+ return {
28492
+ get: async (key) => {
28493
+ if (store[key] === undefined) {
28494
+ return undefined;
28495
+ }
28496
+ if (typeof store[key] === "string") {
28497
+ return store[key];
28498
+ }
28499
+ return JSON.stringify(store[key]);
28500
+ },
28501
+ set: async (key, value) => {
28502
+ store[key] = value;
28503
+ },
28504
+ delete: async (key) => {
28505
+ delete store[key];
28506
+ },
28507
+ };
28508
+ };
28509
+ const mockStorageUtility = (stored, isSecure = false) => {
28510
+ if (isSecure) {
28511
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
28512
+ }
28513
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
28426
28514
  };
28427
28515
 
28428
28516
  exports.AggregateHandler = AggregateHandler;
@@ -29646,6 +29734,29 @@ function validate(uuid) {
29646
29734
 
29647
29735
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validate);
29648
29736
 
29737
+ /***/ }),
29738
+
29739
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js":
29740
+ /*!********************************************************************!*\
29741
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.js ***!
29742
+ \********************************************************************/
29743
+ /***/ ((__unused_webpack_module, exports) => {
29744
+
29745
+ "use strict";
29746
+
29747
+
29748
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
29749
+
29750
+ var indexBrowser = globalThis.fetch;
29751
+ const { fetch, Response, Request, Headers } = globalThis;
29752
+
29753
+ exports.Headers = Headers;
29754
+ exports.Request = Request;
29755
+ exports.Response = Response;
29756
+ exports["default"] = indexBrowser;
29757
+ exports.fetch = fetch;
29758
+
29759
+
29649
29760
  /***/ }),
29650
29761
 
29651
29762
  /***/ "./node_modules/@noble/curves/_shortw_utils.js":
@@ -60290,518 +60401,541 @@ __webpack_require__.r(__webpack_exports__);
60290
60401
  /* harmony export */ "saveSessionInfoToStorage": () => (/* binding */ saveSessionInfoToStorage)
60291
60402
  /* harmony export */ });
60292
60403
  /* harmony import */ var events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js");
60293
- /* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js");
60294
- /* harmony import */ var jose__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
60404
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
60405
+ /* harmony import */ var jose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
60295
60406
  /* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-core/node_modules/uuid/dist/esm-browser/v4.js");
60296
60407
 
60297
60408
 
60298
60409
 
60299
60410
 
60300
60411
 
60301
- const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
60302
- const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
60303
- const EVENTS = {
60304
- ERROR: "error",
60305
- LOGIN: "login",
60306
- LOGOUT: "logout",
60307
- NEW_REFRESH_TOKEN: "newRefreshToken",
60308
- SESSION_EXPIRED: "sessionExpired",
60309
- SESSION_EXTENDED: "sessionExtended",
60310
- SESSION_RESTORED: "sessionRestore",
60311
- TIMEOUT_SET: "timeoutSet",
60312
- };
60313
- const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
60314
- const SCOPE_OPENID = "openid";
60315
- const SCOPE_OFFLINE = "offline_access";
60316
- const SCOPE_WEBID = "webid";
60412
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
60413
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
60414
+ const EVENTS = {
60415
+ ERROR: "error",
60416
+ LOGIN: "login",
60417
+ LOGOUT: "logout",
60418
+ NEW_REFRESH_TOKEN: "newRefreshToken",
60419
+ SESSION_EXPIRED: "sessionExpired",
60420
+ SESSION_EXTENDED: "sessionExtended",
60421
+ SESSION_RESTORED: "sessionRestore",
60422
+ TIMEOUT_SET: "timeoutSet",
60423
+ };
60424
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
60425
+ const SCOPE_OPENID = "openid";
60426
+ const SCOPE_OFFLINE = "offline_access";
60427
+ const SCOPE_WEBID = "webid";
60317
60428
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
60318
60429
 
60319
- const buildProxyHandler = (toExclude, errorMessage) => ({
60320
- get(target, prop, receiver) {
60321
- if (!Object.getOwnPropertyNames(events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter).includes(prop) &&
60322
- Object.getOwnPropertyNames(toExclude).includes(prop)) {
60323
- throw new Error(`${errorMessage}: [${prop}] is not supported`);
60324
- }
60325
- return Reflect.get(target, prop, receiver);
60326
- },
60430
+ const buildProxyHandler = (toExclude, errorMessage) => ({
60431
+ get(target, prop, receiver) {
60432
+ if (!Object.getOwnPropertyNames(events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter).includes(prop) &&
60433
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
60434
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
60435
+ }
60436
+ return Reflect.get(target, prop, receiver);
60437
+ },
60327
60438
  });
60328
60439
 
60329
- class AggregateHandler {
60330
- constructor(handleables) {
60331
- this.handleables = handleables;
60332
- }
60333
- async getProperHandler(params) {
60334
- const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
60335
- for (let i = 0; i < canHandleList.length; i += 1) {
60336
- if (canHandleList[i]) {
60337
- return this.handleables[i];
60338
- }
60339
- }
60340
- return null;
60341
- }
60342
- async canHandle(...params) {
60343
- return (await this.getProperHandler(params)) !== null;
60344
- }
60345
- async handle(...params) {
60346
- const handler = await this.getProperHandler(params);
60347
- if (handler) {
60348
- return handler.handle(...params);
60349
- }
60350
- throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
60351
- .map((param) => {
60352
- try {
60353
- return JSON.stringify(param);
60354
- }
60355
- catch (err) {
60356
- return param.toString();
60357
- }
60358
- })
60359
- .join(", ")}`);
60360
- }
60440
+ class AggregateHandler {
60441
+ constructor(handleables) {
60442
+ this.handleables = handleables;
60443
+ }
60444
+ async getProperHandler(params) {
60445
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
60446
+ for (let i = 0; i < canHandleList.length; i += 1) {
60447
+ if (canHandleList[i]) {
60448
+ return this.handleables[i];
60449
+ }
60450
+ }
60451
+ return null;
60452
+ }
60453
+ async canHandle(...params) {
60454
+ return (await this.getProperHandler(params)) !== null;
60455
+ }
60456
+ async handle(...params) {
60457
+ const handler = await this.getProperHandler(params);
60458
+ if (handler) {
60459
+ return handler.handle(...params);
60460
+ }
60461
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
60462
+ .map((param) => {
60463
+ try {
60464
+ return JSON.stringify(param);
60465
+ }
60466
+ catch (err) {
60467
+ return param.toString();
60468
+ }
60469
+ })
60470
+ .join(", ")}`);
60471
+ }
60361
60472
  }
60362
60473
 
60363
- async function fetchJwks(jwksIri, issuerIri) {
60364
- const jwksResponse = await (0,cross_fetch__WEBPACK_IMPORTED_MODULE_1__.fetch)(jwksIri);
60365
- if (jwksResponse.status !== 200) {
60366
- throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
60367
- }
60368
- let jwk;
60369
- try {
60370
- jwk = (await jwksResponse.json()).keys[0];
60371
- }
60372
- catch (e) {
60373
- throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
60374
- }
60375
- return jwk;
60376
- }
60377
- async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
60378
- const jwk = await fetchJwks(jwksIri, issuerIri);
60379
- let payload;
60380
- try {
60381
- const { payload: verifiedPayload } = await (0,jose__WEBPACK_IMPORTED_MODULE_2__.jwtVerify)(idToken, await (0,jose__WEBPACK_IMPORTED_MODULE_2__.importJWK)(jwk), {
60382
- issuer: issuerIri,
60383
- audience: clientId,
60384
- });
60385
- payload = verifiedPayload;
60386
- }
60387
- catch (e) {
60388
- throw new Error(`Token verification failed: ${e.stack}`);
60389
- }
60390
- if (typeof payload.webid === "string") {
60391
- return payload.webid;
60392
- }
60393
- if (typeof payload.sub !== "string") {
60394
- throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
60395
- }
60396
- try {
60397
- new URL(payload.sub);
60398
- return payload.sub;
60399
- }
60400
- catch (e) {
60401
- throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
60402
- }
60474
+ async function fetchJwks(jwksIri, issuerIri) {
60475
+ const jwksResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(jwksIri);
60476
+ if (jwksResponse.status !== 200) {
60477
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
60478
+ }
60479
+ let jwk;
60480
+ try {
60481
+ jwk = (await jwksResponse.json()).keys[0];
60482
+ }
60483
+ catch (e) {
60484
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
60485
+ }
60486
+ return jwk;
60487
+ }
60488
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
60489
+ const jwk = await fetchJwks(jwksIri, issuerIri);
60490
+ let payload;
60491
+ try {
60492
+ const { payload: verifiedPayload } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.jwtVerify)(idToken, await (0,jose__WEBPACK_IMPORTED_MODULE_1__.importJWK)(jwk), {
60493
+ issuer: issuerIri,
60494
+ audience: clientId,
60495
+ });
60496
+ payload = verifiedPayload;
60497
+ }
60498
+ catch (e) {
60499
+ throw new Error(`Token verification failed: ${e.stack}`);
60500
+ }
60501
+ if (typeof payload.webid === "string") {
60502
+ return payload.webid;
60503
+ }
60504
+ if (typeof payload.sub !== "string") {
60505
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
60506
+ }
60507
+ try {
60508
+ new URL(payload.sub);
60509
+ return payload.sub;
60510
+ }
60511
+ catch (e) {
60512
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
60513
+ }
60403
60514
  }
60404
60515
 
60405
- function isValidRedirectUrl(redirectUrl) {
60406
- try {
60407
- const urlObject = new URL(redirectUrl);
60408
- return urlObject.hash === "";
60409
- }
60410
- catch (e) {
60411
- return false;
60412
- }
60516
+ function isValidRedirectUrl(redirectUrl) {
60517
+ try {
60518
+ const urlObject = new URL(redirectUrl);
60519
+ return urlObject.hash === "";
60520
+ }
60521
+ catch (e) {
60522
+ return false;
60523
+ }
60413
60524
  }
60414
60525
 
60415
- function isSupportedTokenType(token) {
60416
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60526
+ function isSupportedTokenType(token) {
60527
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60417
60528
  }
60418
60529
 
60419
60530
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
60420
60531
 
60421
- function isValidUrl(url) {
60422
- try {
60423
- new URL(url);
60424
- return true;
60425
- }
60426
- catch (_a) {
60427
- return false;
60428
- }
60429
- }
60430
- function determineSigningAlg(supported, preferred) {
60431
- var _a;
60432
- return ((_a = preferred.find((signingAlg) => {
60433
- return supported.includes(signingAlg);
60434
- })) !== null && _a !== void 0 ? _a : null);
60435
- }
60436
- function determineClientType(options, issuerConfig) {
60437
- if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
60438
- return "static";
60439
- }
60440
- if (issuerConfig.scopesSupported.includes("webid") &&
60441
- options.clientId !== undefined &&
60442
- isValidUrl(options.clientId)) {
60443
- return "solid-oidc";
60444
- }
60445
- return "dynamic";
60446
- }
60447
- async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
60448
- const clientType = determineClientType(options, issuerConfig);
60449
- if (clientType === "dynamic") {
60450
- return clientRegistrar.getClient({
60451
- sessionId: options.sessionId,
60452
- clientName: options.clientName,
60453
- redirectUrl: options.redirectUrl,
60454
- }, issuerConfig);
60455
- }
60456
- await storageUtility.setForUser(options.sessionId, {
60457
- clientId: options.clientId,
60458
- });
60459
- if (options.clientSecret) {
60460
- await storageUtility.setForUser(options.sessionId, {
60461
- clientSecret: options.clientSecret,
60462
- });
60463
- }
60464
- if (options.clientName) {
60465
- await storageUtility.setForUser(options.sessionId, {
60466
- clientName: options.clientName,
60467
- });
60468
- }
60469
- return {
60470
- clientId: options.clientId,
60471
- clientSecret: options.clientSecret,
60472
- clientName: options.clientName,
60473
- clientType,
60474
- };
60532
+ function isValidUrl(url) {
60533
+ try {
60534
+ new URL(url);
60535
+ return true;
60536
+ }
60537
+ catch (_a) {
60538
+ return false;
60539
+ }
60540
+ }
60541
+ function determineSigningAlg(supported, preferred) {
60542
+ var _a;
60543
+ return ((_a = preferred.find((signingAlg) => {
60544
+ return supported.includes(signingAlg);
60545
+ })) !== null && _a !== void 0 ? _a : null);
60546
+ }
60547
+ function determineClientType(options, issuerConfig) {
60548
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
60549
+ return "static";
60550
+ }
60551
+ if (issuerConfig.scopesSupported.includes("webid") &&
60552
+ options.clientId !== undefined &&
60553
+ isValidUrl(options.clientId)) {
60554
+ return "solid-oidc";
60555
+ }
60556
+ return "dynamic";
60557
+ }
60558
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
60559
+ const clientType = determineClientType(options, issuerConfig);
60560
+ if (clientType === "dynamic") {
60561
+ return clientRegistrar.getClient({
60562
+ sessionId: options.sessionId,
60563
+ clientName: options.clientName,
60564
+ redirectUrl: options.redirectUrl,
60565
+ }, issuerConfig);
60566
+ }
60567
+ await storageUtility.setForUser(options.sessionId, {
60568
+ clientId: options.clientId,
60569
+ });
60570
+ if (options.clientSecret) {
60571
+ await storageUtility.setForUser(options.sessionId, {
60572
+ clientSecret: options.clientSecret,
60573
+ });
60574
+ }
60575
+ if (options.clientName) {
60576
+ await storageUtility.setForUser(options.sessionId, {
60577
+ clientName: options.clientName,
60578
+ });
60579
+ }
60580
+ return {
60581
+ clientId: options.clientId,
60582
+ clientSecret: options.clientSecret,
60583
+ clientName: options.clientName,
60584
+ clientType,
60585
+ };
60475
60586
  }
60476
60587
 
60477
- async function getSessionIdFromOauthState(storageUtility, oauthState) {
60478
- return storageUtility.getForUser(oauthState, "sessionId");
60479
- }
60480
- async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
60481
- try {
60482
- const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
60483
- storageUtility.getForUser(sessionId, "issuer", {
60484
- errorIfNull: true,
60485
- }),
60486
- storageUtility.getForUser(sessionId, "codeVerifier"),
60487
- storageUtility.getForUser(sessionId, "redirectUrl"),
60488
- storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
60489
- ]);
60490
- await storageUtility.deleteForUser(sessionId, "codeVerifier");
60491
- const issuerConfig = await configFetcher.fetchConfig(issuerIri);
60492
- return {
60493
- codeVerifier,
60494
- redirectUrl: storedRedirectIri,
60495
- issuerConfig,
60496
- dpop: dpop === "true",
60497
- };
60498
- }
60499
- catch (e) {
60500
- throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
60501
- }
60502
- }
60503
- async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
60504
- if (refreshToken !== undefined) {
60505
- await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
60506
- }
60507
- if (webId !== undefined) {
60508
- await storageUtility.setForUser(sessionId, { webId }, { secure });
60509
- }
60510
- if (isLoggedIn !== undefined) {
60511
- await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
60512
- }
60513
- if (dpopKey !== undefined) {
60514
- await storageUtility.setForUser(sessionId, {
60515
- publicKey: JSON.stringify(dpopKey.publicKey),
60516
- privateKey: JSON.stringify(await (0,jose__WEBPACK_IMPORTED_MODULE_2__.exportJWK)(dpopKey.privateKey)),
60517
- }, { secure });
60518
- }
60519
- }
60520
- class StorageUtility {
60521
- constructor(secureStorage, insecureStorage) {
60522
- this.secureStorage = secureStorage;
60523
- this.insecureStorage = insecureStorage;
60524
- }
60525
- getKey(userId) {
60526
- return `solidClientAuthenticationUser:${userId}`;
60527
- }
60528
- async getUserData(userId, secure) {
60529
- const stored = await (secure
60530
- ? this.secureStorage
60531
- : this.insecureStorage).get(this.getKey(userId));
60532
- if (stored === undefined) {
60533
- return {};
60534
- }
60535
- try {
60536
- return JSON.parse(stored);
60537
- }
60538
- catch (err) {
60539
- throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
60540
- }
60541
- }
60542
- async setUserData(userId, data, secure) {
60543
- await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
60544
- }
60545
- async get(key, options) {
60546
- const value = await ((options === null || options === void 0 ? void 0 : options.secure)
60547
- ? this.secureStorage
60548
- : this.insecureStorage).get(key);
60549
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60550
- throw new Error(`[${key}] is not stored`);
60551
- }
60552
- return value;
60553
- }
60554
- async set(key, value, options) {
60555
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
60556
- }
60557
- async delete(key, options) {
60558
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
60559
- }
60560
- async getForUser(userId, key, options) {
60561
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60562
- let value;
60563
- if (!userData || !userData[key]) {
60564
- value = undefined;
60565
- }
60566
- value = userData[key];
60567
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60568
- throw new Error(`Field [${key}] for user [${userId}] is not stored`);
60569
- }
60570
- return value || undefined;
60571
- }
60572
- async setForUser(userId, values, options) {
60573
- let userData;
60574
- try {
60575
- userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60576
- }
60577
- catch (_a) {
60578
- userData = {};
60579
- }
60580
- await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
60581
- }
60582
- async deleteForUser(userId, key, options) {
60583
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60584
- delete userData[key];
60585
- await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
60586
- }
60587
- async deleteAllUserData(userId, options) {
60588
- await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
60589
- }
60588
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
60589
+ return storageUtility.getForUser(oauthState, "sessionId");
60590
+ }
60591
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
60592
+ try {
60593
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
60594
+ storageUtility.getForUser(sessionId, "issuer", {
60595
+ errorIfNull: true,
60596
+ }),
60597
+ storageUtility.getForUser(sessionId, "codeVerifier"),
60598
+ storageUtility.getForUser(sessionId, "redirectUrl"),
60599
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
60600
+ ]);
60601
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
60602
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
60603
+ return {
60604
+ codeVerifier,
60605
+ redirectUrl: storedRedirectIri,
60606
+ issuerConfig,
60607
+ dpop: dpop === "true",
60608
+ };
60609
+ }
60610
+ catch (e) {
60611
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
60612
+ }
60613
+ }
60614
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
60615
+ if (refreshToken !== undefined) {
60616
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
60617
+ }
60618
+ if (webId !== undefined) {
60619
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
60620
+ }
60621
+ if (isLoggedIn !== undefined) {
60622
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
60623
+ }
60624
+ if (dpopKey !== undefined) {
60625
+ await storageUtility.setForUser(sessionId, {
60626
+ publicKey: JSON.stringify(dpopKey.publicKey),
60627
+ privateKey: JSON.stringify(await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(dpopKey.privateKey)),
60628
+ }, { secure });
60629
+ }
60630
+ }
60631
+ class StorageUtility {
60632
+ constructor(secureStorage, insecureStorage) {
60633
+ this.secureStorage = secureStorage;
60634
+ this.insecureStorage = insecureStorage;
60635
+ }
60636
+ getKey(userId) {
60637
+ return `solidClientAuthenticationUser:${userId}`;
60638
+ }
60639
+ async getUserData(userId, secure) {
60640
+ const stored = await (secure
60641
+ ? this.secureStorage
60642
+ : this.insecureStorage).get(this.getKey(userId));
60643
+ if (stored === undefined) {
60644
+ return {};
60645
+ }
60646
+ try {
60647
+ return JSON.parse(stored);
60648
+ }
60649
+ catch (err) {
60650
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
60651
+ }
60652
+ }
60653
+ async setUserData(userId, data, secure) {
60654
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
60655
+ }
60656
+ async get(key, options) {
60657
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
60658
+ ? this.secureStorage
60659
+ : this.insecureStorage).get(key);
60660
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60661
+ throw new Error(`[${key}] is not stored`);
60662
+ }
60663
+ return value;
60664
+ }
60665
+ async set(key, value, options) {
60666
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
60667
+ }
60668
+ async delete(key, options) {
60669
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
60670
+ }
60671
+ async getForUser(userId, key, options) {
60672
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60673
+ let value;
60674
+ if (!userData || !userData[key]) {
60675
+ value = undefined;
60676
+ }
60677
+ value = userData[key];
60678
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60679
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
60680
+ }
60681
+ return value || undefined;
60682
+ }
60683
+ async setForUser(userId, values, options) {
60684
+ let userData;
60685
+ try {
60686
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60687
+ }
60688
+ catch (_a) {
60689
+ userData = {};
60690
+ }
60691
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
60692
+ }
60693
+ async deleteForUser(userId, key, options) {
60694
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60695
+ delete userData[key];
60696
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
60697
+ }
60698
+ async deleteAllUserData(userId, options) {
60699
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
60700
+ }
60590
60701
  }
60591
60702
 
60592
- class InMemoryStorage {
60593
- constructor() {
60594
- this.map = {};
60595
- }
60596
- async get(key) {
60597
- return this.map[key] || undefined;
60598
- }
60599
- async set(key, value) {
60600
- this.map[key] = value;
60601
- }
60602
- async delete(key) {
60603
- delete this.map[key];
60604
- }
60703
+ class InMemoryStorage {
60704
+ constructor() {
60705
+ this.map = {};
60706
+ }
60707
+ async get(key) {
60708
+ return this.map[key] || undefined;
60709
+ }
60710
+ async set(key, value) {
60711
+ this.map[key] = value;
60712
+ }
60713
+ async delete(key) {
60714
+ delete this.map[key];
60715
+ }
60605
60716
  }
60606
60717
 
60607
- class ConfigurationError extends Error {
60608
- constructor(message) {
60609
- super(message);
60610
- }
60718
+ class ConfigurationError extends Error {
60719
+ constructor(message) {
60720
+ super(message);
60721
+ }
60611
60722
  }
60612
60723
 
60613
- class NotImplementedError extends Error {
60614
- constructor(methodName) {
60615
- super(`[${methodName}] is not implemented`);
60616
- }
60724
+ class NotImplementedError extends Error {
60725
+ constructor(methodName) {
60726
+ super(`[${methodName}] is not implemented`);
60727
+ }
60617
60728
  }
60618
60729
 
60619
- class InvalidResponseError extends Error {
60620
- constructor(missingFields) {
60621
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
60622
- this.missingFields = missingFields;
60623
- }
60730
+ class InvalidResponseError extends Error {
60731
+ constructor(missingFields) {
60732
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
60733
+ this.missingFields = missingFields;
60734
+ }
60624
60735
  }
60625
60736
 
60626
- class OidcProviderError extends Error {
60627
- constructor(message, error, errorDescription) {
60628
- super(message);
60629
- this.error = error;
60630
- this.errorDescription = errorDescription;
60631
- }
60737
+ class OidcProviderError extends Error {
60738
+ constructor(message, error, errorDescription) {
60739
+ super(message);
60740
+ this.error = error;
60741
+ this.errorDescription = errorDescription;
60742
+ }
60632
60743
  }
60633
60744
 
60634
- function normalizeHTU(audience) {
60635
- const audienceUrl = new URL(audience);
60636
- return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
60637
- }
60638
- async function createDpopHeader(audience, method, dpopKey) {
60639
- return new jose__WEBPACK_IMPORTED_MODULE_2__.SignJWT({
60640
- htu: normalizeHTU(audience),
60641
- htm: method.toUpperCase(),
60642
- jti: (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])(),
60643
- })
60644
- .setProtectedHeader({
60645
- alg: PREFERRED_SIGNING_ALG[0],
60646
- jwk: dpopKey.publicKey,
60647
- typ: "dpop+jwt",
60648
- })
60649
- .setIssuedAt()
60650
- .sign(dpopKey.privateKey, {});
60651
- }
60652
- async function generateDpopKeyPair() {
60653
- const { privateKey, publicKey } = await (0,jose__WEBPACK_IMPORTED_MODULE_2__.generateKeyPair)(PREFERRED_SIGNING_ALG[0]);
60654
- const dpopKeyPair = {
60655
- privateKey,
60656
- publicKey: await (0,jose__WEBPACK_IMPORTED_MODULE_2__.exportJWK)(publicKey),
60657
- };
60658
- [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
60659
- return dpopKeyPair;
60745
+ function normalizeHTU(audience) {
60746
+ const audienceUrl = new URL(audience);
60747
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
60748
+ }
60749
+ async function createDpopHeader(audience, method, dpopKey) {
60750
+ return new jose__WEBPACK_IMPORTED_MODULE_1__.SignJWT({
60751
+ htu: normalizeHTU(audience),
60752
+ htm: method.toUpperCase(),
60753
+ jti: (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])(),
60754
+ })
60755
+ .setProtectedHeader({
60756
+ alg: PREFERRED_SIGNING_ALG[0],
60757
+ jwk: dpopKey.publicKey,
60758
+ typ: "dpop+jwt",
60759
+ })
60760
+ .setIssuedAt()
60761
+ .sign(dpopKey.privateKey, {});
60762
+ }
60763
+ async function generateDpopKeyPair() {
60764
+ const { privateKey, publicKey } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)(PREFERRED_SIGNING_ALG[0]);
60765
+ const dpopKeyPair = {
60766
+ privateKey,
60767
+ publicKey: await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(publicKey),
60768
+ };
60769
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
60770
+ return dpopKeyPair;
60660
60771
  }
60661
60772
 
60662
- const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
60663
- function isExpectedAuthError(statusCode) {
60664
- return [401, 403].includes(statusCode);
60665
- }
60666
- async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
60667
- var _a;
60668
- const headers = new cross_fetch__WEBPACK_IMPORTED_MODULE_1__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60669
- headers.set("Authorization", `DPoP ${authToken}`);
60670
- headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
60671
- return {
60672
- ...defaultOptions,
60673
- headers,
60674
- };
60675
- }
60676
- async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
60677
- if (dpopKey !== undefined) {
60678
- return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
60679
- }
60680
- const headers = new cross_fetch__WEBPACK_IMPORTED_MODULE_1__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60681
- headers.set("Authorization", `Bearer ${authToken}`);
60682
- return {
60683
- ...defaultOptions,
60684
- headers,
60685
- };
60686
- }
60687
- async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
60688
- return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
60689
- }
60690
- async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
60691
- var _a;
60692
- const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
60693
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
60694
- if (typeof tokenSet.refreshToken === "string") {
60695
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
60696
- }
60697
- return {
60698
- accessToken: tokenSet.accessToken,
60699
- refreshToken: tokenSet.refreshToken,
60700
- expiresIn: tokenSet.expiresIn,
60701
- };
60702
- }
60703
- const computeRefreshDelay = (expiresIn) => {
60704
- if (expiresIn !== undefined) {
60705
- return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
60706
- ?
60707
- expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
60708
- : expiresIn;
60709
- }
60710
- return DEFAULT_EXPIRATION_TIME_SECONDS;
60711
- };
60712
- async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
60713
- var _a;
60714
- let currentAccessToken = accessToken;
60715
- let latestTimeout;
60716
- const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
60717
- if (currentRefreshOptions !== undefined) {
60718
- const proactivelyRefreshToken = async () => {
60719
- var _a, _b, _c, _d;
60720
- try {
60721
- const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
60722
- currentAccessToken = refreshedAccessToken;
60723
- if (refreshToken !== undefined) {
60724
- currentRefreshOptions.refreshToken = refreshToken;
60725
- }
60726
- clearTimeout(latestTimeout);
60727
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
60728
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60729
- }
60730
- catch (e) {
60731
- if (e instanceof OidcProviderError) {
60732
- (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
60733
- (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
60734
- }
60735
- if (e instanceof InvalidResponseError &&
60736
- e.missingFields.includes("access_token")) {
60737
- (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
60738
- }
60739
- }
60740
- };
60741
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
60742
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60743
- }
60744
- else if (options !== undefined && options.eventEmitter !== undefined) {
60745
- const expirationTimeout = setTimeout(() => {
60746
- options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
60747
- }, computeRefreshDelay(options.expiresIn) * 1000);
60748
- options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
60749
- }
60750
- return async (url, requestInit) => {
60751
- let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
60752
- const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
60753
- if (response.ok || failedButNotExpectedAuthError) {
60754
- return response;
60755
- }
60756
- const hasBeenRedirected = response.url !== url;
60757
- if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
60758
- response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
60759
- }
60760
- return response;
60761
- };
60773
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
60774
+ function isExpectedAuthError(statusCode) {
60775
+ return [401, 403].includes(statusCode);
60776
+ }
60777
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
60778
+ var _a;
60779
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60780
+ headers.set("Authorization", `DPoP ${authToken}`);
60781
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
60782
+ return {
60783
+ ...defaultOptions,
60784
+ headers,
60785
+ };
60786
+ }
60787
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
60788
+ if (dpopKey !== undefined) {
60789
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
60790
+ }
60791
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60792
+ headers.set("Authorization", `Bearer ${authToken}`);
60793
+ return {
60794
+ ...defaultOptions,
60795
+ headers,
60796
+ };
60797
+ }
60798
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
60799
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
60800
+ }
60801
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
60802
+ var _a;
60803
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
60804
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
60805
+ if (typeof tokenSet.refreshToken === "string") {
60806
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
60807
+ }
60808
+ return {
60809
+ accessToken: tokenSet.accessToken,
60810
+ refreshToken: tokenSet.refreshToken,
60811
+ expiresIn: tokenSet.expiresIn,
60812
+ };
60813
+ }
60814
+ const computeRefreshDelay = (expiresIn) => {
60815
+ if (expiresIn !== undefined) {
60816
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
60817
+ ?
60818
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
60819
+ : expiresIn;
60820
+ }
60821
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
60822
+ };
60823
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
60824
+ var _a;
60825
+ let currentAccessToken = accessToken;
60826
+ let latestTimeout;
60827
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
60828
+ if (currentRefreshOptions !== undefined) {
60829
+ const proactivelyRefreshToken = async () => {
60830
+ var _a, _b, _c, _d;
60831
+ try {
60832
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
60833
+ currentAccessToken = refreshedAccessToken;
60834
+ if (refreshToken !== undefined) {
60835
+ currentRefreshOptions.refreshToken = refreshToken;
60836
+ }
60837
+ clearTimeout(latestTimeout);
60838
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
60839
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60840
+ }
60841
+ catch (e) {
60842
+ if (e instanceof OidcProviderError) {
60843
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
60844
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
60845
+ }
60846
+ if (e instanceof InvalidResponseError &&
60847
+ e.missingFields.includes("access_token")) {
60848
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
60849
+ }
60850
+ }
60851
+ };
60852
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
60853
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60854
+ }
60855
+ else if (options !== undefined && options.eventEmitter !== undefined) {
60856
+ const expirationTimeout = setTimeout(() => {
60857
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
60858
+ }, computeRefreshDelay(options.expiresIn) * 1000);
60859
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
60860
+ }
60861
+ return async (url, requestInit) => {
60862
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
60863
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
60864
+ if (response.ok || failedButNotExpectedAuthError) {
60865
+ return response;
60866
+ }
60867
+ const hasBeenRedirected = response.url !== url;
60868
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
60869
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
60870
+ }
60871
+ return response;
60872
+ };
60762
60873
  }
60763
60874
 
60764
- const StorageUtilityGetResponse = "getResponse";
60765
- const StorageUtilityMock = {
60766
- get: async (key, options) => StorageUtilityGetResponse,
60767
- set: async (key, value) => {
60768
- },
60769
- delete: async (key) => {
60770
- },
60771
- getForUser: async (userId, key, options) => StorageUtilityGetResponse,
60772
- setForUser: async (userId, values, options) => {
60773
- },
60774
- deleteForUser: async (userId, key, options) => {
60775
- },
60776
- deleteAllUserData: async (userId, options) => {
60777
- },
60778
- };
60779
- const mockStorage = (stored) => {
60780
- const store = stored;
60781
- return {
60782
- get: async (key) => {
60783
- if (store[key] === undefined) {
60784
- return undefined;
60785
- }
60786
- if (typeof store[key] === "string") {
60787
- return store[key];
60788
- }
60789
- return JSON.stringify(store[key]);
60790
- },
60791
- set: async (key, value) => {
60792
- store[key] = value;
60793
- },
60794
- delete: async (key) => {
60795
- delete store[key];
60796
- },
60797
- };
60798
- };
60799
- const mockStorageUtility = (stored, isSecure = false) => {
60800
- if (isSecure) {
60801
- return new StorageUtility(mockStorage(stored), mockStorage({}));
60802
- }
60803
- return new StorageUtility(mockStorage({}), mockStorage(stored));
60875
+ const StorageUtilityGetResponse = "getResponse";
60876
+ const StorageUtilityMock = {
60877
+ get: async (key, options) => StorageUtilityGetResponse,
60878
+ set: async (key, value) => {
60879
+ },
60880
+ delete: async (key) => {
60881
+ },
60882
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
60883
+ setForUser: async (userId, values, options) => {
60884
+ },
60885
+ deleteForUser: async (userId, key, options) => {
60886
+ },
60887
+ deleteAllUserData: async (userId, options) => {
60888
+ },
60804
60889
  };
60890
+ const mockStorage = (stored) => {
60891
+ const store = stored;
60892
+ return {
60893
+ get: async (key) => {
60894
+ if (store[key] === undefined) {
60895
+ return undefined;
60896
+ }
60897
+ if (typeof store[key] === "string") {
60898
+ return store[key];
60899
+ }
60900
+ return JSON.stringify(store[key]);
60901
+ },
60902
+ set: async (key, value) => {
60903
+ store[key] = value;
60904
+ },
60905
+ delete: async (key) => {
60906
+ delete store[key];
60907
+ },
60908
+ };
60909
+ };
60910
+ const mockStorageUtility = (stored, isSecure = false) => {
60911
+ if (isSecure) {
60912
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
60913
+ }
60914
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
60915
+ };
60916
+
60917
+
60918
+
60919
+
60920
+ /***/ }),
60921
+
60922
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs":
60923
+ /*!*********************************************************************!*\
60924
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs ***!
60925
+ \*********************************************************************/
60926
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
60927
+
60928
+ "use strict";
60929
+ __webpack_require__.r(__webpack_exports__);
60930
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
60931
+ /* harmony export */ "Headers": () => (/* binding */ Headers),
60932
+ /* harmony export */ "Request": () => (/* binding */ Request),
60933
+ /* harmony export */ "Response": () => (/* binding */ Response),
60934
+ /* harmony export */ "default": () => (/* binding */ indexBrowser),
60935
+ /* harmony export */ "fetch": () => (/* binding */ fetch)
60936
+ /* harmony export */ });
60937
+ var indexBrowser = globalThis.fetch;
60938
+ const { fetch, Response, Request, Headers } = globalThis;
60805
60939
 
60806
60940
 
60807
60941