solid-ui 2.4.27-1b50dba8 → 2.4.27-20175fe3

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, 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,57 +2666,83 @@ 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;
2671
- if (oldMsg) {
2672
- // edit message replaces old one
2673
- sts.push($rdf.st(mostRecentVersion(oldMsg), ns.dct('isReplacedBy'), message, chatDocument));
2674
- // do we need to rebuild oldMsg signaturen ?
2675
- if (deleteIt) {
2676
- sts.push($rdf.st(message, ns.schema('dateDeleted'), dateStamp, chatDocument));
2677
- msg.dateDeleted = dateStamp;
2678
- }
2679
- } else {
2680
- // link new message to channel
2681
- sts.push($rdf.st(_this.channel, ns.wf('message'), message, chatDocument));
2669
+ msg = (0, _signature.getBlankMsg)();
2670
+ msg.id = message.uri;
2671
+ if (!oldMsg) {
2672
+ _context2.next = 22;
2673
+ break;
2674
+ }
2675
+ // edit message replaces old one
2676
+ oldMsgMaker = _solidLogic.store.any(oldMsg, ns.foaf('maker')); // may not be needed here, but needed on READ
2677
+ if (!(oldMsgMaker.uri === me.uri)) {
2678
+ _context2.next = 16;
2679
+ break;
2680
+ }
2681
+ sts.push($rdf.st(mostRecentVersion(oldMsg), ns.dct('isReplacedBy'), message, chatDocument));
2682
+ if (deleteIt) {
2683
+ // we need to add a specific signature, else anyone can delete a msg ?
2684
+ sts.push($rdf.st(message, ns.schema('dateDeleted'), dateStamp, chatDocument));
2685
+ // msg.dateDeleted = dateStamp
2682
2686
  }
2687
+ _context2.next = 20;
2688
+ break;
2689
+ case 16:
2690
+ errMsg = 'Error you cannot delete/edit a message from someone else : \n' + oldMsgMaker.uri;
2691
+ debug.warn(errMsg);
2692
+ alert(errMsg);
2693
+ throw new Error(errMsg);
2694
+ case 20:
2695
+ _context2.next = 23;
2696
+ break;
2697
+ case 22:
2698
+ // link new message to channel
2699
+ sts.push($rdf.st(_this.channel, ns.wf('message'), message, chatDocument));
2700
+ case 23:
2683
2701
  sts.push($rdf.st(message, ns.sioc('content'), _solidLogic.store.literal(text), chatDocument));
2684
2702
  msg.content = text;
2685
2703
  sts.push($rdf.st(message, ns.dct('created'), dateStamp, chatDocument));
2686
- msg.created = dateStamp;
2704
+ msg.created = dateStamp.value;
2687
2705
  if (!me) {
2688
- _context2.next = 21;
2706
+ _context2.next = 36;
2689
2707
  break;
2690
2708
  }
2691
2709
  sts.push($rdf.st(message, ns.foaf('maker'), me, chatDocument));
2692
- msg.maker = me;
2693
- // privateKey the cached private key of me, cache should be deleted after a certain time
2694
- _context2.next = 19;
2695
- return (0, _keys.getPrivateKey)(me);
2696
- case 19:
2710
+ msg.maker = me.uri;
2711
+ // privateKey the cached private key of me, cached in store
2712
+ _context2.next = 32;
2713
+ return (0, _keys.getPrivateKey)(me.uri);
2714
+ case 32:
2697
2715
  privateKey = _context2.sent;
2698
- sts.push($rdf.st(message, $rdf.sym("".concat(_signature.SEC, "Proof")), $rdf.sym((0, _signature.signMsg)(msg, privateKey), chatDocument)));
2699
- case 21:
2700
- _context2.prev = 21;
2701
- _context2.next = 24;
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;
2702
2728
  return _solidLogic.store.updater.update([], sts);
2703
- case 24:
2704
- _context2.next = 32;
2729
+ case 39:
2730
+ _context2.next = 47;
2705
2731
  break;
2706
- case 26:
2707
- _context2.prev = 26;
2708
- _context2.t0 = _context2["catch"](21);
2709
- errMsg = 'Error saving chat message: ' + _context2.t0;
2710
- debug.warn(errMsg);
2711
- alert(errMsg);
2712
- throw new Error(errMsg);
2713
- case 32:
2732
+ case 41:
2733
+ _context2.prev = 41;
2734
+ _context2.t0 = _context2["catch"](36);
2735
+ _errMsg = 'Error saving chat message: ' + _context2.t0;
2736
+ debug.warn(_errMsg);
2737
+ alert(_errMsg);
2738
+ throw new Error(_errMsg);
2739
+ case 47:
2714
2740
  return _context2.abrupt("return", message);
2715
- case 33:
2741
+ case 48:
2716
2742
  case "end":
2717
2743
  return _context2.stop();
2718
2744
  }
2719
- }, _callee2, null, [[21, 26]]);
2745
+ }, _callee2, null, [[36, 41]]);
2720
2746
  })();
2721
2747
  });
2722
2748
  function updateMessage(_x2) {
@@ -4011,6 +4037,7 @@ exports.getPrivateKey = getPrivateKey;
4011
4037
  exports.getPublicKey = getPublicKey;
4012
4038
  var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
4013
4039
  var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
4040
+ var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js"));
4014
4041
  var _secp256k = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/secp256k1.js");
4015
4042
  var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
4016
4043
  var _signature = __webpack_require__(/*! ./signature */ "./lib/chat/signature.js");
@@ -4018,8 +4045,6 @@ var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-l
4018
4045
  var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"));
4019
4046
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
4020
4047
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
4021
- // should have webcrypto.getRandomValues defined
4022
-
4023
4048
  function generatePrivateKey() {
4024
4049
  return (0, _utils.bytesToHex)(_secp256k.schnorr.utils.randomPrivateKey());
4025
4050
  }
@@ -4027,63 +4052,136 @@ function generatePublicKey(privateKey) {
4027
4052
  return (0, _utils.bytesToHex)(_secp256k.schnorr.getPublicKey(privateKey));
4028
4053
  }
4029
4054
  function getPublicKey(webId) {
4030
- // find publickey
4031
- /* const url = new URL(webId)
4032
- url.hash = ''
4033
- store.fetcher.load(url.href)
4034
- let publicKey = store.any(store.sym(webId), store.sym(CERT +'publicKey')) */
4035
4055
  var publicKey = publicKeyExists(webId);
4036
- return publicKey === null || publicKey === void 0 ? void 0 : publicKey.uri;
4056
+ return publicKey;
4037
4057
  }
4038
4058
  function publicKeyExists(webId) {
4039
4059
  // find publickey
4040
4060
  var url = new URL(webId);
4041
4061
  url.hash = '';
4062
+ /* debug.warn('Alain publicKeyExists')
4063
+ debug.warn(webId)
4064
+ debug.warn(url.href) */
4042
4065
  _solidLogic.store.fetcher.load(url.href);
4043
- var publicKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'publicKey'));
4044
- return publicKey;
4066
+ var publicKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'PublicKey'));
4067
+ return publicKey === null || publicKey === void 0 ? void 0 : publicKey.value; // as NamedNode
4045
4068
  }
4046
- function privateKeyExists(webId) {
4069
+
4070
+ var privKeyUrl = function privKeyUrl(webId) {
4047
4071
  var url = new URL(webId);
4048
- var privateKeyUrl = url.hostname + '/profile/privateKey.ttl';
4049
- _solidLogic.store.fetcher.load(privateKeyUrl);
4050
- var privateKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'privateKey'));
4051
- return privateKey;
4072
+ var privateKeyUrl = url.protocol + '//' + url.host + '/profile/privateKey.ttl';
4073
+ return privateKeyUrl;
4074
+ };
4075
+ function privateKeyExists(_x) {
4076
+ return _privateKeyExists.apply(this, arguments);
4077
+ }
4078
+ function _privateKeyExists() {
4079
+ _privateKeyExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4080
+ var privateKeyUrl, privateKey, _err$response, data, contentType, response;
4081
+ return _regenerator["default"].wrap(function _callee$(_context) {
4082
+ while (1) switch (_context.prev = _context.next) {
4083
+ case 0:
4084
+ /* const url = new URL(webId)
4085
+ const privateKeyUrl = url.protocol + '//' + url.host + '/profile/privateKey.ttl' */
4086
+ privateKeyUrl = privKeyUrl(webId);
4087
+ /* debug.warn('Alain privateKeyExists')
4088
+ debug.warn(webId)
4089
+ debug.warn(privateKeyUrl) */
4090
+ _context.prev = 1;
4091
+ _solidLogic.store.fetcher.load(privateKeyUrl);
4092
+ privateKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'PrivateKey'));
4093
+ return _context.abrupt("return", privateKey === null || privateKey === void 0 ? void 0 : privateKey.value);
4094
+ case 7:
4095
+ _context.prev = 7;
4096
+ _context.t0 = _context["catch"](1);
4097
+ 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)) {
4098
+ _context.next = 24;
4099
+ break;
4100
+ }
4101
+ _context.prev = 10;
4102
+ // create privateKey resource
4103
+ data = '';
4104
+ contentType = 'text/ttl';
4105
+ _context.next = 15;
4106
+ return _solidLogic.store.fetcher.webOperation('PUT', privateKeyUrl, {
4107
+ data: data,
4108
+ contentType: contentType
4109
+ });
4110
+ case 15:
4111
+ response = _context.sent;
4112
+ _context.next = 22;
4113
+ break;
4114
+ case 18:
4115
+ _context.prev = 18;
4116
+ _context.t1 = _context["catch"](10);
4117
+ debug.log('createIfNotExists doc FAILED: ' + privateKeyUrl + ': ' + _context.t1);
4118
+ throw _context.t1;
4119
+ case 22:
4120
+ delete _solidLogic.store.fetcher.requested[privateKeyUrl]; // delete cached 404 error
4121
+ return _context.abrupt("return", undefined);
4122
+ case 24:
4123
+ debug.log('createIfNotExists doc FAILED: ' + privateKeyUrl + ': ' + _context.t0);
4124
+ throw _context.t0;
4125
+ case 26:
4126
+ case "end":
4127
+ return _context.stop();
4128
+ }
4129
+ }, _callee, null, [[1, 7], [10, 18]]);
4130
+ }));
4131
+ return _privateKeyExists.apply(this, arguments);
4052
4132
  }
4053
- function getPrivateKey(_x) {
4133
+ function getPrivateKey(_x2) {
4054
4134
  return _getPrivateKey.apply(this, arguments);
4055
4135
  }
4056
4136
  function _getPrivateKey() {
4057
- _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4137
+ _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
4058
4138
  var url, privateKeyUrl, publicKey, privateKey, del, add;
4059
- return _regenerator["default"].wrap(function _callee$(_context) {
4060
- while (1) switch (_context.prev = _context.next) {
4139
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
4140
+ while (1) switch (_context2.prev = _context2.next) {
4061
4141
  case 0:
4062
4142
  url = new URL(webId);
4063
- privateKeyUrl = url.hostname + '/profile/privateKey.ttl'; // find publickey
4064
- publicKey = publicKeyExists(webId); // find privateKey
4065
- privateKey = privateKeyExists(webId); // create key pair
4143
+ url.hash = '';
4144
+ /* const privateKeyUrl = url.protocol + '//' + url.host + '/profile/privateKey.ttl' */
4145
+ privateKeyUrl = privKeyUrl(webId); // find publickey
4146
+ publicKey = publicKeyExists(webId); // debug.warn('publicKey ' + publicKey)
4147
+ // find privateKey
4148
+ _context2.next = 6;
4149
+ return privateKeyExists(webId);
4150
+ case 6:
4151
+ privateKey = _context2.sent;
4152
+ // debug.warn('privateKey ' + privateKey)
4153
+ if (privateKey && publicKey !== generatePublicKey(privateKey)) debug.warn('publicKey is not valid');
4154
+
4155
+ // simulate new key pair
4156
+ /* const newPrivateKey = generatePrivateKey()
4157
+ const newPublicKey = generatePublicKey(newPrivateKey)
4158
+ debug.log('newPrivateKey ' + newPrivateKey)
4159
+ debug.log('newPublicKey ' + newPublicKey) */
4160
+
4161
+ // create key pair
4066
4162
  if (!(!privateKey || !publicKey)) {
4067
- _context.next = 15;
4163
+ _context2.next = 19;
4068
4164
  break;
4069
4165
  }
4070
4166
  del = [];
4071
4167
  add = [];
4072
- if (privateKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'privateKey'), privateKey, $rdf.sym(privateKeyUrl)));
4073
- if (publicKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'publicKey'), publicKey, $rdf.sym(url.href)));
4074
- privateKey = _solidLogic.store.sym(generatePrivateKey());
4075
- publicKey = _solidLogic.store.sym(generatePublicKey(privateKey.uri));
4076
- add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'privateKey'), $rdf.literal(privateKey.uri), $rdf.sym(privateKeyUrl)));
4077
- add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'publicKey'), $rdf.literal(publicKey.uri), $rdf.sym(url.href)));
4078
- _context.next = 15;
4168
+ if (privateKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'PrivateKey'), $rdf.lit(privateKey), $rdf.sym(privateKeyUrl)));
4169
+ if (publicKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'PublicKey'), $rdf.lit(publicKey), $rdf.sym(url.href)));
4170
+ privateKey = generatePrivateKey();
4171
+ publicKey = generatePublicKey(privateKey);
4172
+ /* debug.log('newPrivateKey-1 ' + privateKey)
4173
+ debug.log('newPublicKey-1 ' + publicKey) */
4174
+ add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'PrivateKey'), $rdf.literal(privateKey), $rdf.sym(privateKeyUrl)));
4175
+ add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'PublicKey'), $rdf.literal(publicKey), $rdf.sym(url.href)));
4176
+ _context2.next = 19;
4079
4177
  return _solidLogic.store.updater.updateMany(del, add);
4080
- case 15:
4081
- return _context.abrupt("return", privateKey.uri);
4082
- case 16:
4178
+ case 19:
4179
+ return _context2.abrupt("return", privateKey);
4180
+ case 20:
4083
4181
  case "end":
4084
- return _context.stop();
4182
+ return _context2.stop();
4085
4183
  }
4086
- }, _callee);
4184
+ }, _callee2);
4087
4185
  }));
4088
4186
  return _getPrivateKey.apply(this, arguments);
4089
4187
  }
@@ -4215,21 +4313,32 @@ function renderMessageRow(channelObject, message, fresh, options, userContext) {
4215
4313
  var creator = _solidLogic.store.any(message, ns.foaf('maker'));
4216
4314
  var date = _solidLogic.store.any(message, ns.dct('created'));
4217
4315
  var latestVersion = (0, _chatLogic.mostRecentVersion)(message);
4218
- var content = _solidLogic.store.any(latestVersion, ns.sioc('content'));
4219
- var signature = _solidLogic.store.any(message, $rdf.sym("".concat(_signature.SEC, "Proof")));
4316
+ var latestVersionCreator = _solidLogic.store.any(latestVersion, ns.foaf('maker'));
4317
+ // use latest content if same owner, else use original
4318
+ var msgId = creator === latestVersionCreator ? latestVersion : message;
4319
+ var content = _solidLogic.store.any(msgId, ns.sioc('content'));
4320
+ var signature = _solidLogic.store.any(msgId, $rdf.sym("".concat(_signature.SEC, "Proof")));
4321
+ debug.log('alain ' + (signature === null || signature === void 0 ? void 0 : signature.value));
4220
4322
 
4221
4323
  // verify signature
4222
4324
  var msg = (0, _signature.getBlankMsg)();
4223
- msg.id = message;
4224
- msg.created = date;
4225
- // this is not correct.
4226
- // If the message has been edited/deleted we must verify the latest message and may be the intermediate ones
4227
- msg.content = content;
4228
- msg.maker = creator;
4229
-
4230
- // pubKey could be store in a cache for all makers
4231
- var pubKey = (0, _keys.getPublicKey)(creator); // alain no
4232
- if (!(0, _signature.verifySignature)(signature, msg, pubKey)) throw new Error();
4325
+ msg.id = msgId.uri;
4326
+ msg.created = _solidLogic.store.any(msgId, ns.dct('created')).value;
4327
+ msg.content = content.value;
4328
+ msg.maker = creator.uri;
4329
+ try {
4330
+ // pubKey could be store in a cache for all makers
4331
+ var pubKey = (0, _keys.getPublicKey)(creator.uri);
4332
+ /* const pubKey0 = '023a9da707bee1302f66083c9d95673ff969b41607a66f52686fa774d64ceb87'
4333
+ debug.warn('publicKeys\n' + pubKey0 + '\n' + pubKey)
4334
+ const privKey0 = getPrivateKey(creator.uri) // alain to remove
4335
+ // unsigned messages should be signaled as unsecured
4336
+ debug.warn(msg)
4337
+ debug.warn(signature?.value) */
4338
+ if (signature !== null && signature !== void 0 && signature.value && !(0, _signature.verifySignature)(signature.value, msg, pubKey)) throw new Error('invalid signature');
4339
+ } catch (err) {
4340
+ debug.log(err);
4341
+ }
4233
4342
  var originalMessage = (0, _chatLogic.originalVersion)(message);
4234
4343
  var edited = !message.sameTerm(originalMessage);
4235
4344
  var sortDate = _solidLogic.store.the(originalMessage, ns.dct('created'), null, originalMessage.doc()); // In message
@@ -5032,8 +5141,8 @@ exports.utf8Encoder = exports.utf8Decoder = void 0;
5032
5141
  exports.validateMsg = validateMsg;
5033
5142
  exports.verifySignature = verifySignature;
5034
5143
  var _secp256k = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/secp256k1.js");
5035
- var _sha = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
5036
5144
  var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
5145
+ var _sha = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
5037
5146
  // import {utf8Encoder} from './utils'
5038
5147
  // import { getPublicKey } from './keys'
5039
5148
 
@@ -5043,7 +5152,7 @@ var utf8Encoder = new TextEncoder();
5043
5152
  exports.utf8Encoder = utf8Encoder;
5044
5153
  var SEC = 'https://w3id.org/security#'; // Proof, VerificationMethod
5045
5154
  exports.SEC = SEC;
5046
- var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivatKey, PublicKey
5155
+ var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivateKey, PublicKey
5047
5156
 
5048
5157
  /* eslint-disable no-unused-vars */
5049
5158
  /* export enum Kind {
@@ -13176,8 +13285,8 @@ Object.defineProperty(exports, "__esModule", ({
13176
13285
  }));
13177
13286
  exports.versionInfo = void 0;
13178
13287
  var versionInfo = {
13179
- buildTime: '2023-04-18T10:32:40Z',
13180
- commit: '1b50dba8005b1d24e9e6b4fab30f6284fb6d6e6e',
13288
+ buildTime: '2023-04-21T21:20:00Z',
13289
+ commit: '20175fe34b116218e9d7838365c079aa30ed7459',
13181
13290
  npmInfo: {
13182
13291
  'solid-ui': '2.4.27',
13183
13292
  npm: '8.19.4',
@@ -25340,6 +25449,8 @@ __webpack_require__.r(__webpack_exports__);
25340
25449
  /* 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");
25341
25450
  /* harmony import */ var _inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0__);
25342
25451
  /* 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");
25452
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
25453
+
25343
25454
 
25344
25455
 
25345
25456
 
@@ -25493,7 +25604,7 @@ async function getTokens(issuer, client, data, dpop) {
25493
25604
  headers,
25494
25605
  body: new URLSearchParams(requestBody).toString(),
25495
25606
  };
25496
- const rawTokenResponse = await await fetch(issuer.tokenEndpoint, tokenRequestInit);
25607
+ const rawTokenResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, tokenRequestInit);
25497
25608
  const jsonTokenResponse = (await rawTokenResponse.json());
25498
25609
  const tokenResponse = validateTokenEndpointResponse(jsonTokenResponse, dpop);
25499
25610
  const webId = await (0,_inrupt_solid_client_authn_core__WEBPACK_IMPORTED_MODULE_1__.getWebidFromTokenPayload)(tokenResponse.id_token, issuer.jwksUri, issuer.issuer, client.clientId);
@@ -25577,7 +25688,7 @@ async function refresh(refreshToken, issuer, client, dpopKey) {
25577
25688
  else if (isValidUrl(client.clientId)) {
25578
25689
  requestBody.client_id = client.clientId;
25579
25690
  }
25580
- const rawResponse = await fetch(issuer.tokenEndpoint, {
25691
+ const rawResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, {
25581
25692
  method: "POST",
25582
25693
  body: new URLSearchParams(requestBody).toString(),
25583
25694
  headers: {
@@ -25692,8 +25803,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=
25692
25803
 
25693
25804
  Object.defineProperty(exports, "__esModule", ({ value: true }));
25694
25805
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
25806
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
25695
25807
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
25696
- const globalFetch = (request, init) => window.fetch(request, init);
25808
+ const globalFetch = (request, init) => (0, universal_fetch_1.fetch)(request, init);
25697
25809
  class ClientAuthentication {
25698
25810
  constructor(loginHandler, redirectHandler, logoutHandler, sessionInfoManager, issuerConfigFetcher) {
25699
25811
  this.loginHandler = loginHandler;
@@ -26187,6 +26299,7 @@ exports["default"] = ClientRegistrar;
26187
26299
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26188
26300
  exports.WELL_KNOWN_OPENID_CONFIG = void 0;
26189
26301
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26302
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26190
26303
  exports.WELL_KNOWN_OPENID_CONFIG = ".well-known/openid-configuration";
26191
26304
  const issuerConfigKeyMap = {
26192
26305
  issuer: {
@@ -26293,7 +26406,7 @@ class IssuerConfigFetcher {
26293
26406
  async fetchConfig(issuer) {
26294
26407
  let issuerConfig;
26295
26408
  const openIdConfigUrl = new URL(exports.WELL_KNOWN_OPENID_CONFIG, issuer.endsWith("/") ? issuer : `${issuer}/`).href;
26296
- const issuerConfigRequestBody = await window.fetch(openIdConfigUrl);
26409
+ const issuerConfigRequestBody = await (0, universal_fetch_1.fetch)(openIdConfigUrl);
26297
26410
  try {
26298
26411
  issuerConfig = processConfig(await issuerConfigRequestBody.json());
26299
26412
  }
@@ -26396,6 +26509,7 @@ exports["default"] = Redirector;
26396
26509
 
26397
26510
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26398
26511
  exports.AuthCodeRedirectHandler = void 0;
26512
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26399
26513
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26400
26514
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
26401
26515
  class AuthCodeRedirectHandler {
@@ -26459,7 +26573,7 @@ class AuthCodeRedirectHandler {
26459
26573
  tokenRefresher: this.tokerRefresher,
26460
26574
  };
26461
26575
  }
26462
- const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(fetch, tokens.accessToken, {
26576
+ const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(universal_fetch_1.fetch, tokens.accessToken, {
26463
26577
  dpopKey: tokens.dpopKey,
26464
26578
  refreshOptions,
26465
26579
  eventEmitter,
@@ -26697,11 +26811,12 @@ exports.SessionInfoManager = exports.clear = exports.getUnauthenticatedSession =
26697
26811
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26698
26812
  const uuid_1 = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-browser/node_modules/uuid/dist/commonjs-browser/index.js");
26699
26813
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
26814
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26700
26815
  function getUnauthenticatedSession() {
26701
26816
  return {
26702
26817
  isLoggedIn: false,
26703
26818
  sessionId: (0, uuid_1.v4)(),
26704
- fetch,
26819
+ fetch: universal_fetch_1.fetch,
26705
26820
  };
26706
26821
  }
26707
26822
  exports.getUnauthenticatedSession = getUnauthenticatedSession;
@@ -27854,513 +27969,513 @@ exports["default"] = _default;
27854
27969
 
27855
27970
 
27856
27971
  var events = __webpack_require__(/*! events */ "./node_modules/events/events.js");
27857
- var crossFetch = __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js");
27972
+ var universalFetch = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
27858
27973
  var jose = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
27859
27974
  var uuid = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-core/node_modules/uuid/dist/commonjs-browser/index.js");
27860
27975
 
27861
- const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
27862
- const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
27863
- const EVENTS = {
27864
- ERROR: "error",
27865
- LOGIN: "login",
27866
- LOGOUT: "logout",
27867
- NEW_REFRESH_TOKEN: "newRefreshToken",
27868
- SESSION_EXPIRED: "sessionExpired",
27869
- SESSION_EXTENDED: "sessionExtended",
27870
- SESSION_RESTORED: "sessionRestore",
27871
- TIMEOUT_SET: "timeoutSet",
27872
- };
27873
- const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
27874
- const SCOPE_OPENID = "openid";
27875
- const SCOPE_OFFLINE = "offline_access";
27876
- const SCOPE_WEBID = "webid";
27976
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
27977
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
27978
+ const EVENTS = {
27979
+ ERROR: "error",
27980
+ LOGIN: "login",
27981
+ LOGOUT: "logout",
27982
+ NEW_REFRESH_TOKEN: "newRefreshToken",
27983
+ SESSION_EXPIRED: "sessionExpired",
27984
+ SESSION_EXTENDED: "sessionExtended",
27985
+ SESSION_RESTORED: "sessionRestore",
27986
+ TIMEOUT_SET: "timeoutSet",
27987
+ };
27988
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
27989
+ const SCOPE_OPENID = "openid";
27990
+ const SCOPE_OFFLINE = "offline_access";
27991
+ const SCOPE_WEBID = "webid";
27877
27992
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
27878
27993
 
27879
- const buildProxyHandler = (toExclude, errorMessage) => ({
27880
- get(target, prop, receiver) {
27881
- if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&
27882
- Object.getOwnPropertyNames(toExclude).includes(prop)) {
27883
- throw new Error(`${errorMessage}: [${prop}] is not supported`);
27884
- }
27885
- return Reflect.get(target, prop, receiver);
27886
- },
27994
+ const buildProxyHandler = (toExclude, errorMessage) => ({
27995
+ get(target, prop, receiver) {
27996
+ if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&
27997
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
27998
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
27999
+ }
28000
+ return Reflect.get(target, prop, receiver);
28001
+ },
27887
28002
  });
27888
28003
 
27889
- class AggregateHandler {
27890
- constructor(handleables) {
27891
- this.handleables = handleables;
27892
- }
27893
- async getProperHandler(params) {
27894
- const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
27895
- for (let i = 0; i < canHandleList.length; i += 1) {
27896
- if (canHandleList[i]) {
27897
- return this.handleables[i];
27898
- }
27899
- }
27900
- return null;
27901
- }
27902
- async canHandle(...params) {
27903
- return (await this.getProperHandler(params)) !== null;
27904
- }
27905
- async handle(...params) {
27906
- const handler = await this.getProperHandler(params);
27907
- if (handler) {
27908
- return handler.handle(...params);
27909
- }
27910
- throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
27911
- .map((param) => {
27912
- try {
27913
- return JSON.stringify(param);
27914
- }
27915
- catch (err) {
27916
- return param.toString();
27917
- }
27918
- })
27919
- .join(", ")}`);
27920
- }
28004
+ class AggregateHandler {
28005
+ constructor(handleables) {
28006
+ this.handleables = handleables;
28007
+ }
28008
+ async getProperHandler(params) {
28009
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
28010
+ for (let i = 0; i < canHandleList.length; i += 1) {
28011
+ if (canHandleList[i]) {
28012
+ return this.handleables[i];
28013
+ }
28014
+ }
28015
+ return null;
28016
+ }
28017
+ async canHandle(...params) {
28018
+ return (await this.getProperHandler(params)) !== null;
28019
+ }
28020
+ async handle(...params) {
28021
+ const handler = await this.getProperHandler(params);
28022
+ if (handler) {
28023
+ return handler.handle(...params);
28024
+ }
28025
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
28026
+ .map((param) => {
28027
+ try {
28028
+ return JSON.stringify(param);
28029
+ }
28030
+ catch (err) {
28031
+ return param.toString();
28032
+ }
28033
+ })
28034
+ .join(", ")}`);
28035
+ }
27921
28036
  }
27922
28037
 
27923
- async function fetchJwks(jwksIri, issuerIri) {
27924
- const jwksResponse = await crossFetch.fetch(jwksIri);
27925
- if (jwksResponse.status !== 200) {
27926
- throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
27927
- }
27928
- let jwk;
27929
- try {
27930
- jwk = (await jwksResponse.json()).keys[0];
27931
- }
27932
- catch (e) {
27933
- throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
27934
- }
27935
- return jwk;
27936
- }
27937
- async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
27938
- const jwk = await fetchJwks(jwksIri, issuerIri);
27939
- let payload;
27940
- try {
27941
- const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {
27942
- issuer: issuerIri,
27943
- audience: clientId,
27944
- });
27945
- payload = verifiedPayload;
27946
- }
27947
- catch (e) {
27948
- throw new Error(`Token verification failed: ${e.stack}`);
27949
- }
27950
- if (typeof payload.webid === "string") {
27951
- return payload.webid;
27952
- }
27953
- if (typeof payload.sub !== "string") {
27954
- throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
27955
- }
27956
- try {
27957
- new URL(payload.sub);
27958
- return payload.sub;
27959
- }
27960
- catch (e) {
27961
- throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
27962
- }
28038
+ async function fetchJwks(jwksIri, issuerIri) {
28039
+ const jwksResponse = await universalFetch.fetch(jwksIri);
28040
+ if (jwksResponse.status !== 200) {
28041
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
28042
+ }
28043
+ let jwk;
28044
+ try {
28045
+ jwk = (await jwksResponse.json()).keys[0];
28046
+ }
28047
+ catch (e) {
28048
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
28049
+ }
28050
+ return jwk;
28051
+ }
28052
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
28053
+ const jwk = await fetchJwks(jwksIri, issuerIri);
28054
+ let payload;
28055
+ try {
28056
+ const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {
28057
+ issuer: issuerIri,
28058
+ audience: clientId,
28059
+ });
28060
+ payload = verifiedPayload;
28061
+ }
28062
+ catch (e) {
28063
+ throw new Error(`Token verification failed: ${e.stack}`);
28064
+ }
28065
+ if (typeof payload.webid === "string") {
28066
+ return payload.webid;
28067
+ }
28068
+ if (typeof payload.sub !== "string") {
28069
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
28070
+ }
28071
+ try {
28072
+ new URL(payload.sub);
28073
+ return payload.sub;
28074
+ }
28075
+ catch (e) {
28076
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
28077
+ }
27963
28078
  }
27964
28079
 
27965
- function isValidRedirectUrl(redirectUrl) {
27966
- try {
27967
- const urlObject = new URL(redirectUrl);
27968
- return urlObject.hash === "";
27969
- }
27970
- catch (e) {
27971
- return false;
27972
- }
28080
+ function isValidRedirectUrl(redirectUrl) {
28081
+ try {
28082
+ const urlObject = new URL(redirectUrl);
28083
+ return urlObject.hash === "";
28084
+ }
28085
+ catch (e) {
28086
+ return false;
28087
+ }
27973
28088
  }
27974
28089
 
27975
- function isSupportedTokenType(token) {
27976
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
28090
+ function isSupportedTokenType(token) {
28091
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
27977
28092
  }
27978
28093
 
27979
28094
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
27980
28095
 
27981
- function isValidUrl(url) {
27982
- try {
27983
- new URL(url);
27984
- return true;
27985
- }
27986
- catch (_a) {
27987
- return false;
27988
- }
27989
- }
27990
- function determineSigningAlg(supported, preferred) {
27991
- var _a;
27992
- return ((_a = preferred.find((signingAlg) => {
27993
- return supported.includes(signingAlg);
27994
- })) !== null && _a !== void 0 ? _a : null);
27995
- }
27996
- function determineClientType(options, issuerConfig) {
27997
- if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
27998
- return "static";
27999
- }
28000
- if (issuerConfig.scopesSupported.includes("webid") &&
28001
- options.clientId !== undefined &&
28002
- isValidUrl(options.clientId)) {
28003
- return "solid-oidc";
28004
- }
28005
- return "dynamic";
28006
- }
28007
- async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
28008
- const clientType = determineClientType(options, issuerConfig);
28009
- if (clientType === "dynamic") {
28010
- return clientRegistrar.getClient({
28011
- sessionId: options.sessionId,
28012
- clientName: options.clientName,
28013
- redirectUrl: options.redirectUrl,
28014
- }, issuerConfig);
28015
- }
28016
- await storageUtility.setForUser(options.sessionId, {
28017
- clientId: options.clientId,
28018
- });
28019
- if (options.clientSecret) {
28020
- await storageUtility.setForUser(options.sessionId, {
28021
- clientSecret: options.clientSecret,
28022
- });
28023
- }
28024
- if (options.clientName) {
28025
- await storageUtility.setForUser(options.sessionId, {
28026
- clientName: options.clientName,
28027
- });
28028
- }
28029
- return {
28030
- clientId: options.clientId,
28031
- clientSecret: options.clientSecret,
28032
- clientName: options.clientName,
28033
- clientType,
28034
- };
28096
+ function isValidUrl(url) {
28097
+ try {
28098
+ new URL(url);
28099
+ return true;
28100
+ }
28101
+ catch (_a) {
28102
+ return false;
28103
+ }
28104
+ }
28105
+ function determineSigningAlg(supported, preferred) {
28106
+ var _a;
28107
+ return ((_a = preferred.find((signingAlg) => {
28108
+ return supported.includes(signingAlg);
28109
+ })) !== null && _a !== void 0 ? _a : null);
28110
+ }
28111
+ function determineClientType(options, issuerConfig) {
28112
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
28113
+ return "static";
28114
+ }
28115
+ if (issuerConfig.scopesSupported.includes("webid") &&
28116
+ options.clientId !== undefined &&
28117
+ isValidUrl(options.clientId)) {
28118
+ return "solid-oidc";
28119
+ }
28120
+ return "dynamic";
28121
+ }
28122
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
28123
+ const clientType = determineClientType(options, issuerConfig);
28124
+ if (clientType === "dynamic") {
28125
+ return clientRegistrar.getClient({
28126
+ sessionId: options.sessionId,
28127
+ clientName: options.clientName,
28128
+ redirectUrl: options.redirectUrl,
28129
+ }, issuerConfig);
28130
+ }
28131
+ await storageUtility.setForUser(options.sessionId, {
28132
+ clientId: options.clientId,
28133
+ });
28134
+ if (options.clientSecret) {
28135
+ await storageUtility.setForUser(options.sessionId, {
28136
+ clientSecret: options.clientSecret,
28137
+ });
28138
+ }
28139
+ if (options.clientName) {
28140
+ await storageUtility.setForUser(options.sessionId, {
28141
+ clientName: options.clientName,
28142
+ });
28143
+ }
28144
+ return {
28145
+ clientId: options.clientId,
28146
+ clientSecret: options.clientSecret,
28147
+ clientName: options.clientName,
28148
+ clientType,
28149
+ };
28035
28150
  }
28036
28151
 
28037
- async function getSessionIdFromOauthState(storageUtility, oauthState) {
28038
- return storageUtility.getForUser(oauthState, "sessionId");
28039
- }
28040
- async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
28041
- try {
28042
- const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
28043
- storageUtility.getForUser(sessionId, "issuer", {
28044
- errorIfNull: true,
28045
- }),
28046
- storageUtility.getForUser(sessionId, "codeVerifier"),
28047
- storageUtility.getForUser(sessionId, "redirectUrl"),
28048
- storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
28049
- ]);
28050
- await storageUtility.deleteForUser(sessionId, "codeVerifier");
28051
- const issuerConfig = await configFetcher.fetchConfig(issuerIri);
28052
- return {
28053
- codeVerifier,
28054
- redirectUrl: storedRedirectIri,
28055
- issuerConfig,
28056
- dpop: dpop === "true",
28057
- };
28058
- }
28059
- catch (e) {
28060
- throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
28061
- }
28062
- }
28063
- async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
28064
- if (refreshToken !== undefined) {
28065
- await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
28066
- }
28067
- if (webId !== undefined) {
28068
- await storageUtility.setForUser(sessionId, { webId }, { secure });
28069
- }
28070
- if (isLoggedIn !== undefined) {
28071
- await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
28072
- }
28073
- if (dpopKey !== undefined) {
28074
- await storageUtility.setForUser(sessionId, {
28075
- publicKey: JSON.stringify(dpopKey.publicKey),
28076
- privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),
28077
- }, { secure });
28078
- }
28079
- }
28080
- class StorageUtility {
28081
- constructor(secureStorage, insecureStorage) {
28082
- this.secureStorage = secureStorage;
28083
- this.insecureStorage = insecureStorage;
28084
- }
28085
- getKey(userId) {
28086
- return `solidClientAuthenticationUser:${userId}`;
28087
- }
28088
- async getUserData(userId, secure) {
28089
- const stored = await (secure
28090
- ? this.secureStorage
28091
- : this.insecureStorage).get(this.getKey(userId));
28092
- if (stored === undefined) {
28093
- return {};
28094
- }
28095
- try {
28096
- return JSON.parse(stored);
28097
- }
28098
- catch (err) {
28099
- throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
28100
- }
28101
- }
28102
- async setUserData(userId, data, secure) {
28103
- await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
28104
- }
28105
- async get(key, options) {
28106
- const value = await ((options === null || options === void 0 ? void 0 : options.secure)
28107
- ? this.secureStorage
28108
- : this.insecureStorage).get(key);
28109
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28110
- throw new Error(`[${key}] is not stored`);
28111
- }
28112
- return value;
28113
- }
28114
- async set(key, value, options) {
28115
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
28116
- }
28117
- async delete(key, options) {
28118
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
28119
- }
28120
- async getForUser(userId, key, options) {
28121
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28122
- let value;
28123
- if (!userData || !userData[key]) {
28124
- value = undefined;
28125
- }
28126
- value = userData[key];
28127
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28128
- throw new Error(`Field [${key}] for user [${userId}] is not stored`);
28129
- }
28130
- return value || undefined;
28131
- }
28132
- async setForUser(userId, values, options) {
28133
- let userData;
28134
- try {
28135
- userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28136
- }
28137
- catch (_a) {
28138
- userData = {};
28139
- }
28140
- await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
28141
- }
28142
- async deleteForUser(userId, key, options) {
28143
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28144
- delete userData[key];
28145
- await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
28146
- }
28147
- async deleteAllUserData(userId, options) {
28148
- await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
28149
- }
28152
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
28153
+ return storageUtility.getForUser(oauthState, "sessionId");
28154
+ }
28155
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
28156
+ try {
28157
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
28158
+ storageUtility.getForUser(sessionId, "issuer", {
28159
+ errorIfNull: true,
28160
+ }),
28161
+ storageUtility.getForUser(sessionId, "codeVerifier"),
28162
+ storageUtility.getForUser(sessionId, "redirectUrl"),
28163
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
28164
+ ]);
28165
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
28166
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
28167
+ return {
28168
+ codeVerifier,
28169
+ redirectUrl: storedRedirectIri,
28170
+ issuerConfig,
28171
+ dpop: dpop === "true",
28172
+ };
28173
+ }
28174
+ catch (e) {
28175
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
28176
+ }
28177
+ }
28178
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
28179
+ if (refreshToken !== undefined) {
28180
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
28181
+ }
28182
+ if (webId !== undefined) {
28183
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
28184
+ }
28185
+ if (isLoggedIn !== undefined) {
28186
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
28187
+ }
28188
+ if (dpopKey !== undefined) {
28189
+ await storageUtility.setForUser(sessionId, {
28190
+ publicKey: JSON.stringify(dpopKey.publicKey),
28191
+ privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),
28192
+ }, { secure });
28193
+ }
28194
+ }
28195
+ class StorageUtility {
28196
+ constructor(secureStorage, insecureStorage) {
28197
+ this.secureStorage = secureStorage;
28198
+ this.insecureStorage = insecureStorage;
28199
+ }
28200
+ getKey(userId) {
28201
+ return `solidClientAuthenticationUser:${userId}`;
28202
+ }
28203
+ async getUserData(userId, secure) {
28204
+ const stored = await (secure
28205
+ ? this.secureStorage
28206
+ : this.insecureStorage).get(this.getKey(userId));
28207
+ if (stored === undefined) {
28208
+ return {};
28209
+ }
28210
+ try {
28211
+ return JSON.parse(stored);
28212
+ }
28213
+ catch (err) {
28214
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
28215
+ }
28216
+ }
28217
+ async setUserData(userId, data, secure) {
28218
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
28219
+ }
28220
+ async get(key, options) {
28221
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
28222
+ ? this.secureStorage
28223
+ : this.insecureStorage).get(key);
28224
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28225
+ throw new Error(`[${key}] is not stored`);
28226
+ }
28227
+ return value;
28228
+ }
28229
+ async set(key, value, options) {
28230
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
28231
+ }
28232
+ async delete(key, options) {
28233
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
28234
+ }
28235
+ async getForUser(userId, key, options) {
28236
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28237
+ let value;
28238
+ if (!userData || !userData[key]) {
28239
+ value = undefined;
28240
+ }
28241
+ value = userData[key];
28242
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28243
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
28244
+ }
28245
+ return value || undefined;
28246
+ }
28247
+ async setForUser(userId, values, options) {
28248
+ let userData;
28249
+ try {
28250
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28251
+ }
28252
+ catch (_a) {
28253
+ userData = {};
28254
+ }
28255
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
28256
+ }
28257
+ async deleteForUser(userId, key, options) {
28258
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28259
+ delete userData[key];
28260
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
28261
+ }
28262
+ async deleteAllUserData(userId, options) {
28263
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
28264
+ }
28150
28265
  }
28151
28266
 
28152
- class InMemoryStorage {
28153
- constructor() {
28154
- this.map = {};
28155
- }
28156
- async get(key) {
28157
- return this.map[key] || undefined;
28158
- }
28159
- async set(key, value) {
28160
- this.map[key] = value;
28161
- }
28162
- async delete(key) {
28163
- delete this.map[key];
28164
- }
28267
+ class InMemoryStorage {
28268
+ constructor() {
28269
+ this.map = {};
28270
+ }
28271
+ async get(key) {
28272
+ return this.map[key] || undefined;
28273
+ }
28274
+ async set(key, value) {
28275
+ this.map[key] = value;
28276
+ }
28277
+ async delete(key) {
28278
+ delete this.map[key];
28279
+ }
28165
28280
  }
28166
28281
 
28167
- class ConfigurationError extends Error {
28168
- constructor(message) {
28169
- super(message);
28170
- }
28282
+ class ConfigurationError extends Error {
28283
+ constructor(message) {
28284
+ super(message);
28285
+ }
28171
28286
  }
28172
28287
 
28173
- class NotImplementedError extends Error {
28174
- constructor(methodName) {
28175
- super(`[${methodName}] is not implemented`);
28176
- }
28288
+ class NotImplementedError extends Error {
28289
+ constructor(methodName) {
28290
+ super(`[${methodName}] is not implemented`);
28291
+ }
28177
28292
  }
28178
28293
 
28179
- class InvalidResponseError extends Error {
28180
- constructor(missingFields) {
28181
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28182
- this.missingFields = missingFields;
28183
- }
28294
+ class InvalidResponseError extends Error {
28295
+ constructor(missingFields) {
28296
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28297
+ this.missingFields = missingFields;
28298
+ }
28184
28299
  }
28185
28300
 
28186
- class OidcProviderError extends Error {
28187
- constructor(message, error, errorDescription) {
28188
- super(message);
28189
- this.error = error;
28190
- this.errorDescription = errorDescription;
28191
- }
28301
+ class OidcProviderError extends Error {
28302
+ constructor(message, error, errorDescription) {
28303
+ super(message);
28304
+ this.error = error;
28305
+ this.errorDescription = errorDescription;
28306
+ }
28192
28307
  }
28193
28308
 
28194
- function normalizeHTU(audience) {
28195
- const audienceUrl = new URL(audience);
28196
- return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
28197
- }
28198
- async function createDpopHeader(audience, method, dpopKey) {
28199
- return new jose.SignJWT({
28200
- htu: normalizeHTU(audience),
28201
- htm: method.toUpperCase(),
28202
- jti: uuid.v4(),
28203
- })
28204
- .setProtectedHeader({
28205
- alg: PREFERRED_SIGNING_ALG[0],
28206
- jwk: dpopKey.publicKey,
28207
- typ: "dpop+jwt",
28208
- })
28209
- .setIssuedAt()
28210
- .sign(dpopKey.privateKey, {});
28211
- }
28212
- async function generateDpopKeyPair() {
28213
- const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);
28214
- const dpopKeyPair = {
28215
- privateKey,
28216
- publicKey: await jose.exportJWK(publicKey),
28217
- };
28218
- [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
28219
- return dpopKeyPair;
28309
+ function normalizeHTU(audience) {
28310
+ const audienceUrl = new URL(audience);
28311
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
28312
+ }
28313
+ async function createDpopHeader(audience, method, dpopKey) {
28314
+ return new jose.SignJWT({
28315
+ htu: normalizeHTU(audience),
28316
+ htm: method.toUpperCase(),
28317
+ jti: uuid.v4(),
28318
+ })
28319
+ .setProtectedHeader({
28320
+ alg: PREFERRED_SIGNING_ALG[0],
28321
+ jwk: dpopKey.publicKey,
28322
+ typ: "dpop+jwt",
28323
+ })
28324
+ .setIssuedAt()
28325
+ .sign(dpopKey.privateKey, {});
28326
+ }
28327
+ async function generateDpopKeyPair() {
28328
+ const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);
28329
+ const dpopKeyPair = {
28330
+ privateKey,
28331
+ publicKey: await jose.exportJWK(publicKey),
28332
+ };
28333
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
28334
+ return dpopKeyPair;
28220
28335
  }
28221
28336
 
28222
- const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
28223
- function isExpectedAuthError(statusCode) {
28224
- return [401, 403].includes(statusCode);
28225
- }
28226
- async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
28227
- var _a;
28228
- const headers = new crossFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28229
- headers.set("Authorization", `DPoP ${authToken}`);
28230
- headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
28231
- return {
28232
- ...defaultOptions,
28233
- headers,
28234
- };
28235
- }
28236
- async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
28237
- if (dpopKey !== undefined) {
28238
- return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
28239
- }
28240
- const headers = new crossFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28241
- headers.set("Authorization", `Bearer ${authToken}`);
28242
- return {
28243
- ...defaultOptions,
28244
- headers,
28245
- };
28246
- }
28247
- async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
28248
- return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
28249
- }
28250
- async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
28251
- var _a;
28252
- const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
28253
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
28254
- if (typeof tokenSet.refreshToken === "string") {
28255
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
28256
- }
28257
- return {
28258
- accessToken: tokenSet.accessToken,
28259
- refreshToken: tokenSet.refreshToken,
28260
- expiresIn: tokenSet.expiresIn,
28261
- };
28262
- }
28263
- const computeRefreshDelay = (expiresIn) => {
28264
- if (expiresIn !== undefined) {
28265
- return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
28266
- ?
28267
- expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
28268
- : expiresIn;
28269
- }
28270
- return DEFAULT_EXPIRATION_TIME_SECONDS;
28271
- };
28272
- async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
28273
- var _a;
28274
- let currentAccessToken = accessToken;
28275
- let latestTimeout;
28276
- const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
28277
- if (currentRefreshOptions !== undefined) {
28278
- const proactivelyRefreshToken = async () => {
28279
- var _a, _b, _c, _d;
28280
- try {
28281
- const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
28282
- currentAccessToken = refreshedAccessToken;
28283
- if (refreshToken !== undefined) {
28284
- currentRefreshOptions.refreshToken = refreshToken;
28285
- }
28286
- clearTimeout(latestTimeout);
28287
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
28288
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28289
- }
28290
- catch (e) {
28291
- if (e instanceof OidcProviderError) {
28292
- (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
28293
- (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
28294
- }
28295
- if (e instanceof InvalidResponseError &&
28296
- e.missingFields.includes("access_token")) {
28297
- (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
28298
- }
28299
- }
28300
- };
28301
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
28302
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28303
- }
28304
- else if (options !== undefined && options.eventEmitter !== undefined) {
28305
- const expirationTimeout = setTimeout(() => {
28306
- options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
28307
- }, computeRefreshDelay(options.expiresIn) * 1000);
28308
- options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
28309
- }
28310
- return async (url, requestInit) => {
28311
- let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
28312
- const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
28313
- if (response.ok || failedButNotExpectedAuthError) {
28314
- return response;
28315
- }
28316
- const hasBeenRedirected = response.url !== url;
28317
- if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
28318
- response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
28319
- }
28320
- return response;
28321
- };
28337
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
28338
+ function isExpectedAuthError(statusCode) {
28339
+ return [401, 403].includes(statusCode);
28340
+ }
28341
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
28342
+ var _a;
28343
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28344
+ headers.set("Authorization", `DPoP ${authToken}`);
28345
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
28346
+ return {
28347
+ ...defaultOptions,
28348
+ headers,
28349
+ };
28350
+ }
28351
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
28352
+ if (dpopKey !== undefined) {
28353
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
28354
+ }
28355
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28356
+ headers.set("Authorization", `Bearer ${authToken}`);
28357
+ return {
28358
+ ...defaultOptions,
28359
+ headers,
28360
+ };
28361
+ }
28362
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
28363
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
28364
+ }
28365
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
28366
+ var _a;
28367
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
28368
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
28369
+ if (typeof tokenSet.refreshToken === "string") {
28370
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
28371
+ }
28372
+ return {
28373
+ accessToken: tokenSet.accessToken,
28374
+ refreshToken: tokenSet.refreshToken,
28375
+ expiresIn: tokenSet.expiresIn,
28376
+ };
28377
+ }
28378
+ const computeRefreshDelay = (expiresIn) => {
28379
+ if (expiresIn !== undefined) {
28380
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
28381
+ ?
28382
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
28383
+ : expiresIn;
28384
+ }
28385
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
28386
+ };
28387
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
28388
+ var _a;
28389
+ let currentAccessToken = accessToken;
28390
+ let latestTimeout;
28391
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
28392
+ if (currentRefreshOptions !== undefined) {
28393
+ const proactivelyRefreshToken = async () => {
28394
+ var _a, _b, _c, _d;
28395
+ try {
28396
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
28397
+ currentAccessToken = refreshedAccessToken;
28398
+ if (refreshToken !== undefined) {
28399
+ currentRefreshOptions.refreshToken = refreshToken;
28400
+ }
28401
+ clearTimeout(latestTimeout);
28402
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
28403
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28404
+ }
28405
+ catch (e) {
28406
+ if (e instanceof OidcProviderError) {
28407
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
28408
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
28409
+ }
28410
+ if (e instanceof InvalidResponseError &&
28411
+ e.missingFields.includes("access_token")) {
28412
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
28413
+ }
28414
+ }
28415
+ };
28416
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
28417
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28418
+ }
28419
+ else if (options !== undefined && options.eventEmitter !== undefined) {
28420
+ const expirationTimeout = setTimeout(() => {
28421
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
28422
+ }, computeRefreshDelay(options.expiresIn) * 1000);
28423
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
28424
+ }
28425
+ return async (url, requestInit) => {
28426
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
28427
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
28428
+ if (response.ok || failedButNotExpectedAuthError) {
28429
+ return response;
28430
+ }
28431
+ const hasBeenRedirected = response.url !== url;
28432
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
28433
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
28434
+ }
28435
+ return response;
28436
+ };
28322
28437
  }
28323
28438
 
28324
- const StorageUtilityGetResponse = "getResponse";
28325
- const StorageUtilityMock = {
28326
- get: async (key, options) => StorageUtilityGetResponse,
28327
- set: async (key, value) => {
28328
- },
28329
- delete: async (key) => {
28330
- },
28331
- getForUser: async (userId, key, options) => StorageUtilityGetResponse,
28332
- setForUser: async (userId, values, options) => {
28333
- },
28334
- deleteForUser: async (userId, key, options) => {
28335
- },
28336
- deleteAllUserData: async (userId, options) => {
28337
- },
28338
- };
28339
- const mockStorage = (stored) => {
28340
- const store = stored;
28341
- return {
28342
- get: async (key) => {
28343
- if (store[key] === undefined) {
28344
- return undefined;
28345
- }
28346
- if (typeof store[key] === "string") {
28347
- return store[key];
28348
- }
28349
- return JSON.stringify(store[key]);
28350
- },
28351
- set: async (key, value) => {
28352
- store[key] = value;
28353
- },
28354
- delete: async (key) => {
28355
- delete store[key];
28356
- },
28357
- };
28358
- };
28359
- const mockStorageUtility = (stored, isSecure = false) => {
28360
- if (isSecure) {
28361
- return new StorageUtility(mockStorage(stored), mockStorage({}));
28362
- }
28363
- return new StorageUtility(mockStorage({}), mockStorage(stored));
28439
+ const StorageUtilityGetResponse = "getResponse";
28440
+ const StorageUtilityMock = {
28441
+ get: async (key, options) => StorageUtilityGetResponse,
28442
+ set: async (key, value) => {
28443
+ },
28444
+ delete: async (key) => {
28445
+ },
28446
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
28447
+ setForUser: async (userId, values, options) => {
28448
+ },
28449
+ deleteForUser: async (userId, key, options) => {
28450
+ },
28451
+ deleteAllUserData: async (userId, options) => {
28452
+ },
28453
+ };
28454
+ const mockStorage = (stored) => {
28455
+ const store = stored;
28456
+ return {
28457
+ get: async (key) => {
28458
+ if (store[key] === undefined) {
28459
+ return undefined;
28460
+ }
28461
+ if (typeof store[key] === "string") {
28462
+ return store[key];
28463
+ }
28464
+ return JSON.stringify(store[key]);
28465
+ },
28466
+ set: async (key, value) => {
28467
+ store[key] = value;
28468
+ },
28469
+ delete: async (key) => {
28470
+ delete store[key];
28471
+ },
28472
+ };
28473
+ };
28474
+ const mockStorageUtility = (stored, isSecure = false) => {
28475
+ if (isSecure) {
28476
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
28477
+ }
28478
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
28364
28479
  };
28365
28480
 
28366
28481
  exports.AggregateHandler = AggregateHandler;
@@ -29584,6 +29699,29 @@ function validate(uuid) {
29584
29699
 
29585
29700
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validate);
29586
29701
 
29702
+ /***/ }),
29703
+
29704
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js":
29705
+ /*!********************************************************************!*\
29706
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.js ***!
29707
+ \********************************************************************/
29708
+ /***/ ((__unused_webpack_module, exports) => {
29709
+
29710
+ "use strict";
29711
+
29712
+
29713
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
29714
+
29715
+ var indexBrowser = globalThis.fetch;
29716
+ const { fetch, Response, Request, Headers } = globalThis;
29717
+
29718
+ exports.Headers = Headers;
29719
+ exports.Request = Request;
29720
+ exports.Response = Response;
29721
+ exports["default"] = indexBrowser;
29722
+ exports.fetch = fetch;
29723
+
29724
+
29587
29725
  /***/ }),
29588
29726
 
29589
29727
  /***/ "./node_modules/@noble/curves/_shortw_utils.js":
@@ -60228,518 +60366,541 @@ __webpack_require__.r(__webpack_exports__);
60228
60366
  /* harmony export */ "saveSessionInfoToStorage": () => (/* binding */ saveSessionInfoToStorage)
60229
60367
  /* harmony export */ });
60230
60368
  /* harmony import */ var events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js");
60231
- /* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js");
60232
- /* harmony import */ var jose__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
60369
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
60370
+ /* harmony import */ var jose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
60233
60371
  /* 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");
60234
60372
 
60235
60373
 
60236
60374
 
60237
60375
 
60238
60376
 
60239
- const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
60240
- const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
60241
- const EVENTS = {
60242
- ERROR: "error",
60243
- LOGIN: "login",
60244
- LOGOUT: "logout",
60245
- NEW_REFRESH_TOKEN: "newRefreshToken",
60246
- SESSION_EXPIRED: "sessionExpired",
60247
- SESSION_EXTENDED: "sessionExtended",
60248
- SESSION_RESTORED: "sessionRestore",
60249
- TIMEOUT_SET: "timeoutSet",
60250
- };
60251
- const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
60252
- const SCOPE_OPENID = "openid";
60253
- const SCOPE_OFFLINE = "offline_access";
60254
- const SCOPE_WEBID = "webid";
60377
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
60378
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
60379
+ const EVENTS = {
60380
+ ERROR: "error",
60381
+ LOGIN: "login",
60382
+ LOGOUT: "logout",
60383
+ NEW_REFRESH_TOKEN: "newRefreshToken",
60384
+ SESSION_EXPIRED: "sessionExpired",
60385
+ SESSION_EXTENDED: "sessionExtended",
60386
+ SESSION_RESTORED: "sessionRestore",
60387
+ TIMEOUT_SET: "timeoutSet",
60388
+ };
60389
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
60390
+ const SCOPE_OPENID = "openid";
60391
+ const SCOPE_OFFLINE = "offline_access";
60392
+ const SCOPE_WEBID = "webid";
60255
60393
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
60256
60394
 
60257
- const buildProxyHandler = (toExclude, errorMessage) => ({
60258
- get(target, prop, receiver) {
60259
- if (!Object.getOwnPropertyNames(events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter).includes(prop) &&
60260
- Object.getOwnPropertyNames(toExclude).includes(prop)) {
60261
- throw new Error(`${errorMessage}: [${prop}] is not supported`);
60262
- }
60263
- return Reflect.get(target, prop, receiver);
60264
- },
60395
+ const buildProxyHandler = (toExclude, errorMessage) => ({
60396
+ get(target, prop, receiver) {
60397
+ if (!Object.getOwnPropertyNames(events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter).includes(prop) &&
60398
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
60399
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
60400
+ }
60401
+ return Reflect.get(target, prop, receiver);
60402
+ },
60265
60403
  });
60266
60404
 
60267
- class AggregateHandler {
60268
- constructor(handleables) {
60269
- this.handleables = handleables;
60270
- }
60271
- async getProperHandler(params) {
60272
- const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
60273
- for (let i = 0; i < canHandleList.length; i += 1) {
60274
- if (canHandleList[i]) {
60275
- return this.handleables[i];
60276
- }
60277
- }
60278
- return null;
60279
- }
60280
- async canHandle(...params) {
60281
- return (await this.getProperHandler(params)) !== null;
60282
- }
60283
- async handle(...params) {
60284
- const handler = await this.getProperHandler(params);
60285
- if (handler) {
60286
- return handler.handle(...params);
60287
- }
60288
- throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
60289
- .map((param) => {
60290
- try {
60291
- return JSON.stringify(param);
60292
- }
60293
- catch (err) {
60294
- return param.toString();
60295
- }
60296
- })
60297
- .join(", ")}`);
60298
- }
60405
+ class AggregateHandler {
60406
+ constructor(handleables) {
60407
+ this.handleables = handleables;
60408
+ }
60409
+ async getProperHandler(params) {
60410
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
60411
+ for (let i = 0; i < canHandleList.length; i += 1) {
60412
+ if (canHandleList[i]) {
60413
+ return this.handleables[i];
60414
+ }
60415
+ }
60416
+ return null;
60417
+ }
60418
+ async canHandle(...params) {
60419
+ return (await this.getProperHandler(params)) !== null;
60420
+ }
60421
+ async handle(...params) {
60422
+ const handler = await this.getProperHandler(params);
60423
+ if (handler) {
60424
+ return handler.handle(...params);
60425
+ }
60426
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
60427
+ .map((param) => {
60428
+ try {
60429
+ return JSON.stringify(param);
60430
+ }
60431
+ catch (err) {
60432
+ return param.toString();
60433
+ }
60434
+ })
60435
+ .join(", ")}`);
60436
+ }
60299
60437
  }
60300
60438
 
60301
- async function fetchJwks(jwksIri, issuerIri) {
60302
- const jwksResponse = await (0,cross_fetch__WEBPACK_IMPORTED_MODULE_1__.fetch)(jwksIri);
60303
- if (jwksResponse.status !== 200) {
60304
- throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
60305
- }
60306
- let jwk;
60307
- try {
60308
- jwk = (await jwksResponse.json()).keys[0];
60309
- }
60310
- catch (e) {
60311
- throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
60312
- }
60313
- return jwk;
60314
- }
60315
- async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
60316
- const jwk = await fetchJwks(jwksIri, issuerIri);
60317
- let payload;
60318
- try {
60319
- const { payload: verifiedPayload } = await (0,jose__WEBPACK_IMPORTED_MODULE_2__.jwtVerify)(idToken, await (0,jose__WEBPACK_IMPORTED_MODULE_2__.importJWK)(jwk), {
60320
- issuer: issuerIri,
60321
- audience: clientId,
60322
- });
60323
- payload = verifiedPayload;
60324
- }
60325
- catch (e) {
60326
- throw new Error(`Token verification failed: ${e.stack}`);
60327
- }
60328
- if (typeof payload.webid === "string") {
60329
- return payload.webid;
60330
- }
60331
- if (typeof payload.sub !== "string") {
60332
- throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
60333
- }
60334
- try {
60335
- new URL(payload.sub);
60336
- return payload.sub;
60337
- }
60338
- catch (e) {
60339
- throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
60340
- }
60439
+ async function fetchJwks(jwksIri, issuerIri) {
60440
+ const jwksResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(jwksIri);
60441
+ if (jwksResponse.status !== 200) {
60442
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
60443
+ }
60444
+ let jwk;
60445
+ try {
60446
+ jwk = (await jwksResponse.json()).keys[0];
60447
+ }
60448
+ catch (e) {
60449
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
60450
+ }
60451
+ return jwk;
60452
+ }
60453
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
60454
+ const jwk = await fetchJwks(jwksIri, issuerIri);
60455
+ let payload;
60456
+ try {
60457
+ const { payload: verifiedPayload } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.jwtVerify)(idToken, await (0,jose__WEBPACK_IMPORTED_MODULE_1__.importJWK)(jwk), {
60458
+ issuer: issuerIri,
60459
+ audience: clientId,
60460
+ });
60461
+ payload = verifiedPayload;
60462
+ }
60463
+ catch (e) {
60464
+ throw new Error(`Token verification failed: ${e.stack}`);
60465
+ }
60466
+ if (typeof payload.webid === "string") {
60467
+ return payload.webid;
60468
+ }
60469
+ if (typeof payload.sub !== "string") {
60470
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
60471
+ }
60472
+ try {
60473
+ new URL(payload.sub);
60474
+ return payload.sub;
60475
+ }
60476
+ catch (e) {
60477
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
60478
+ }
60341
60479
  }
60342
60480
 
60343
- function isValidRedirectUrl(redirectUrl) {
60344
- try {
60345
- const urlObject = new URL(redirectUrl);
60346
- return urlObject.hash === "";
60347
- }
60348
- catch (e) {
60349
- return false;
60350
- }
60481
+ function isValidRedirectUrl(redirectUrl) {
60482
+ try {
60483
+ const urlObject = new URL(redirectUrl);
60484
+ return urlObject.hash === "";
60485
+ }
60486
+ catch (e) {
60487
+ return false;
60488
+ }
60351
60489
  }
60352
60490
 
60353
- function isSupportedTokenType(token) {
60354
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60491
+ function isSupportedTokenType(token) {
60492
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60355
60493
  }
60356
60494
 
60357
60495
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
60358
60496
 
60359
- function isValidUrl(url) {
60360
- try {
60361
- new URL(url);
60362
- return true;
60363
- }
60364
- catch (_a) {
60365
- return false;
60366
- }
60367
- }
60368
- function determineSigningAlg(supported, preferred) {
60369
- var _a;
60370
- return ((_a = preferred.find((signingAlg) => {
60371
- return supported.includes(signingAlg);
60372
- })) !== null && _a !== void 0 ? _a : null);
60373
- }
60374
- function determineClientType(options, issuerConfig) {
60375
- if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
60376
- return "static";
60377
- }
60378
- if (issuerConfig.scopesSupported.includes("webid") &&
60379
- options.clientId !== undefined &&
60380
- isValidUrl(options.clientId)) {
60381
- return "solid-oidc";
60382
- }
60383
- return "dynamic";
60384
- }
60385
- async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
60386
- const clientType = determineClientType(options, issuerConfig);
60387
- if (clientType === "dynamic") {
60388
- return clientRegistrar.getClient({
60389
- sessionId: options.sessionId,
60390
- clientName: options.clientName,
60391
- redirectUrl: options.redirectUrl,
60392
- }, issuerConfig);
60393
- }
60394
- await storageUtility.setForUser(options.sessionId, {
60395
- clientId: options.clientId,
60396
- });
60397
- if (options.clientSecret) {
60398
- await storageUtility.setForUser(options.sessionId, {
60399
- clientSecret: options.clientSecret,
60400
- });
60401
- }
60402
- if (options.clientName) {
60403
- await storageUtility.setForUser(options.sessionId, {
60404
- clientName: options.clientName,
60405
- });
60406
- }
60407
- return {
60408
- clientId: options.clientId,
60409
- clientSecret: options.clientSecret,
60410
- clientName: options.clientName,
60411
- clientType,
60412
- };
60497
+ function isValidUrl(url) {
60498
+ try {
60499
+ new URL(url);
60500
+ return true;
60501
+ }
60502
+ catch (_a) {
60503
+ return false;
60504
+ }
60505
+ }
60506
+ function determineSigningAlg(supported, preferred) {
60507
+ var _a;
60508
+ return ((_a = preferred.find((signingAlg) => {
60509
+ return supported.includes(signingAlg);
60510
+ })) !== null && _a !== void 0 ? _a : null);
60511
+ }
60512
+ function determineClientType(options, issuerConfig) {
60513
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
60514
+ return "static";
60515
+ }
60516
+ if (issuerConfig.scopesSupported.includes("webid") &&
60517
+ options.clientId !== undefined &&
60518
+ isValidUrl(options.clientId)) {
60519
+ return "solid-oidc";
60520
+ }
60521
+ return "dynamic";
60522
+ }
60523
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
60524
+ const clientType = determineClientType(options, issuerConfig);
60525
+ if (clientType === "dynamic") {
60526
+ return clientRegistrar.getClient({
60527
+ sessionId: options.sessionId,
60528
+ clientName: options.clientName,
60529
+ redirectUrl: options.redirectUrl,
60530
+ }, issuerConfig);
60531
+ }
60532
+ await storageUtility.setForUser(options.sessionId, {
60533
+ clientId: options.clientId,
60534
+ });
60535
+ if (options.clientSecret) {
60536
+ await storageUtility.setForUser(options.sessionId, {
60537
+ clientSecret: options.clientSecret,
60538
+ });
60539
+ }
60540
+ if (options.clientName) {
60541
+ await storageUtility.setForUser(options.sessionId, {
60542
+ clientName: options.clientName,
60543
+ });
60544
+ }
60545
+ return {
60546
+ clientId: options.clientId,
60547
+ clientSecret: options.clientSecret,
60548
+ clientName: options.clientName,
60549
+ clientType,
60550
+ };
60413
60551
  }
60414
60552
 
60415
- async function getSessionIdFromOauthState(storageUtility, oauthState) {
60416
- return storageUtility.getForUser(oauthState, "sessionId");
60417
- }
60418
- async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
60419
- try {
60420
- const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
60421
- storageUtility.getForUser(sessionId, "issuer", {
60422
- errorIfNull: true,
60423
- }),
60424
- storageUtility.getForUser(sessionId, "codeVerifier"),
60425
- storageUtility.getForUser(sessionId, "redirectUrl"),
60426
- storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
60427
- ]);
60428
- await storageUtility.deleteForUser(sessionId, "codeVerifier");
60429
- const issuerConfig = await configFetcher.fetchConfig(issuerIri);
60430
- return {
60431
- codeVerifier,
60432
- redirectUrl: storedRedirectIri,
60433
- issuerConfig,
60434
- dpop: dpop === "true",
60435
- };
60436
- }
60437
- catch (e) {
60438
- throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
60439
- }
60440
- }
60441
- async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
60442
- if (refreshToken !== undefined) {
60443
- await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
60444
- }
60445
- if (webId !== undefined) {
60446
- await storageUtility.setForUser(sessionId, { webId }, { secure });
60447
- }
60448
- if (isLoggedIn !== undefined) {
60449
- await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
60450
- }
60451
- if (dpopKey !== undefined) {
60452
- await storageUtility.setForUser(sessionId, {
60453
- publicKey: JSON.stringify(dpopKey.publicKey),
60454
- privateKey: JSON.stringify(await (0,jose__WEBPACK_IMPORTED_MODULE_2__.exportJWK)(dpopKey.privateKey)),
60455
- }, { secure });
60456
- }
60457
- }
60458
- class StorageUtility {
60459
- constructor(secureStorage, insecureStorage) {
60460
- this.secureStorage = secureStorage;
60461
- this.insecureStorage = insecureStorage;
60462
- }
60463
- getKey(userId) {
60464
- return `solidClientAuthenticationUser:${userId}`;
60465
- }
60466
- async getUserData(userId, secure) {
60467
- const stored = await (secure
60468
- ? this.secureStorage
60469
- : this.insecureStorage).get(this.getKey(userId));
60470
- if (stored === undefined) {
60471
- return {};
60472
- }
60473
- try {
60474
- return JSON.parse(stored);
60475
- }
60476
- catch (err) {
60477
- throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
60478
- }
60479
- }
60480
- async setUserData(userId, data, secure) {
60481
- await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
60482
- }
60483
- async get(key, options) {
60484
- const value = await ((options === null || options === void 0 ? void 0 : options.secure)
60485
- ? this.secureStorage
60486
- : this.insecureStorage).get(key);
60487
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60488
- throw new Error(`[${key}] is not stored`);
60489
- }
60490
- return value;
60491
- }
60492
- async set(key, value, options) {
60493
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
60494
- }
60495
- async delete(key, options) {
60496
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
60497
- }
60498
- async getForUser(userId, key, options) {
60499
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60500
- let value;
60501
- if (!userData || !userData[key]) {
60502
- value = undefined;
60503
- }
60504
- value = userData[key];
60505
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60506
- throw new Error(`Field [${key}] for user [${userId}] is not stored`);
60507
- }
60508
- return value || undefined;
60509
- }
60510
- async setForUser(userId, values, options) {
60511
- let userData;
60512
- try {
60513
- userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60514
- }
60515
- catch (_a) {
60516
- userData = {};
60517
- }
60518
- await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
60519
- }
60520
- async deleteForUser(userId, key, options) {
60521
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60522
- delete userData[key];
60523
- await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
60524
- }
60525
- async deleteAllUserData(userId, options) {
60526
- await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
60527
- }
60553
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
60554
+ return storageUtility.getForUser(oauthState, "sessionId");
60555
+ }
60556
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
60557
+ try {
60558
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
60559
+ storageUtility.getForUser(sessionId, "issuer", {
60560
+ errorIfNull: true,
60561
+ }),
60562
+ storageUtility.getForUser(sessionId, "codeVerifier"),
60563
+ storageUtility.getForUser(sessionId, "redirectUrl"),
60564
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
60565
+ ]);
60566
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
60567
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
60568
+ return {
60569
+ codeVerifier,
60570
+ redirectUrl: storedRedirectIri,
60571
+ issuerConfig,
60572
+ dpop: dpop === "true",
60573
+ };
60574
+ }
60575
+ catch (e) {
60576
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
60577
+ }
60578
+ }
60579
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
60580
+ if (refreshToken !== undefined) {
60581
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
60582
+ }
60583
+ if (webId !== undefined) {
60584
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
60585
+ }
60586
+ if (isLoggedIn !== undefined) {
60587
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
60588
+ }
60589
+ if (dpopKey !== undefined) {
60590
+ await storageUtility.setForUser(sessionId, {
60591
+ publicKey: JSON.stringify(dpopKey.publicKey),
60592
+ privateKey: JSON.stringify(await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(dpopKey.privateKey)),
60593
+ }, { secure });
60594
+ }
60595
+ }
60596
+ class StorageUtility {
60597
+ constructor(secureStorage, insecureStorage) {
60598
+ this.secureStorage = secureStorage;
60599
+ this.insecureStorage = insecureStorage;
60600
+ }
60601
+ getKey(userId) {
60602
+ return `solidClientAuthenticationUser:${userId}`;
60603
+ }
60604
+ async getUserData(userId, secure) {
60605
+ const stored = await (secure
60606
+ ? this.secureStorage
60607
+ : this.insecureStorage).get(this.getKey(userId));
60608
+ if (stored === undefined) {
60609
+ return {};
60610
+ }
60611
+ try {
60612
+ return JSON.parse(stored);
60613
+ }
60614
+ catch (err) {
60615
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
60616
+ }
60617
+ }
60618
+ async setUserData(userId, data, secure) {
60619
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
60620
+ }
60621
+ async get(key, options) {
60622
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
60623
+ ? this.secureStorage
60624
+ : this.insecureStorage).get(key);
60625
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60626
+ throw new Error(`[${key}] is not stored`);
60627
+ }
60628
+ return value;
60629
+ }
60630
+ async set(key, value, options) {
60631
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
60632
+ }
60633
+ async delete(key, options) {
60634
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
60635
+ }
60636
+ async getForUser(userId, key, options) {
60637
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60638
+ let value;
60639
+ if (!userData || !userData[key]) {
60640
+ value = undefined;
60641
+ }
60642
+ value = userData[key];
60643
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60644
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
60645
+ }
60646
+ return value || undefined;
60647
+ }
60648
+ async setForUser(userId, values, options) {
60649
+ let userData;
60650
+ try {
60651
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60652
+ }
60653
+ catch (_a) {
60654
+ userData = {};
60655
+ }
60656
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
60657
+ }
60658
+ async deleteForUser(userId, key, options) {
60659
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60660
+ delete userData[key];
60661
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
60662
+ }
60663
+ async deleteAllUserData(userId, options) {
60664
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
60665
+ }
60528
60666
  }
60529
60667
 
60530
- class InMemoryStorage {
60531
- constructor() {
60532
- this.map = {};
60533
- }
60534
- async get(key) {
60535
- return this.map[key] || undefined;
60536
- }
60537
- async set(key, value) {
60538
- this.map[key] = value;
60539
- }
60540
- async delete(key) {
60541
- delete this.map[key];
60542
- }
60668
+ class InMemoryStorage {
60669
+ constructor() {
60670
+ this.map = {};
60671
+ }
60672
+ async get(key) {
60673
+ return this.map[key] || undefined;
60674
+ }
60675
+ async set(key, value) {
60676
+ this.map[key] = value;
60677
+ }
60678
+ async delete(key) {
60679
+ delete this.map[key];
60680
+ }
60543
60681
  }
60544
60682
 
60545
- class ConfigurationError extends Error {
60546
- constructor(message) {
60547
- super(message);
60548
- }
60683
+ class ConfigurationError extends Error {
60684
+ constructor(message) {
60685
+ super(message);
60686
+ }
60549
60687
  }
60550
60688
 
60551
- class NotImplementedError extends Error {
60552
- constructor(methodName) {
60553
- super(`[${methodName}] is not implemented`);
60554
- }
60689
+ class NotImplementedError extends Error {
60690
+ constructor(methodName) {
60691
+ super(`[${methodName}] is not implemented`);
60692
+ }
60555
60693
  }
60556
60694
 
60557
- class InvalidResponseError extends Error {
60558
- constructor(missingFields) {
60559
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
60560
- this.missingFields = missingFields;
60561
- }
60695
+ class InvalidResponseError extends Error {
60696
+ constructor(missingFields) {
60697
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
60698
+ this.missingFields = missingFields;
60699
+ }
60562
60700
  }
60563
60701
 
60564
- class OidcProviderError extends Error {
60565
- constructor(message, error, errorDescription) {
60566
- super(message);
60567
- this.error = error;
60568
- this.errorDescription = errorDescription;
60569
- }
60702
+ class OidcProviderError extends Error {
60703
+ constructor(message, error, errorDescription) {
60704
+ super(message);
60705
+ this.error = error;
60706
+ this.errorDescription = errorDescription;
60707
+ }
60570
60708
  }
60571
60709
 
60572
- function normalizeHTU(audience) {
60573
- const audienceUrl = new URL(audience);
60574
- return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
60575
- }
60576
- async function createDpopHeader(audience, method, dpopKey) {
60577
- return new jose__WEBPACK_IMPORTED_MODULE_2__.SignJWT({
60578
- htu: normalizeHTU(audience),
60579
- htm: method.toUpperCase(),
60580
- jti: (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])(),
60581
- })
60582
- .setProtectedHeader({
60583
- alg: PREFERRED_SIGNING_ALG[0],
60584
- jwk: dpopKey.publicKey,
60585
- typ: "dpop+jwt",
60586
- })
60587
- .setIssuedAt()
60588
- .sign(dpopKey.privateKey, {});
60589
- }
60590
- async function generateDpopKeyPair() {
60591
- const { privateKey, publicKey } = await (0,jose__WEBPACK_IMPORTED_MODULE_2__.generateKeyPair)(PREFERRED_SIGNING_ALG[0]);
60592
- const dpopKeyPair = {
60593
- privateKey,
60594
- publicKey: await (0,jose__WEBPACK_IMPORTED_MODULE_2__.exportJWK)(publicKey),
60595
- };
60596
- [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
60597
- return dpopKeyPair;
60710
+ function normalizeHTU(audience) {
60711
+ const audienceUrl = new URL(audience);
60712
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
60713
+ }
60714
+ async function createDpopHeader(audience, method, dpopKey) {
60715
+ return new jose__WEBPACK_IMPORTED_MODULE_1__.SignJWT({
60716
+ htu: normalizeHTU(audience),
60717
+ htm: method.toUpperCase(),
60718
+ jti: (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])(),
60719
+ })
60720
+ .setProtectedHeader({
60721
+ alg: PREFERRED_SIGNING_ALG[0],
60722
+ jwk: dpopKey.publicKey,
60723
+ typ: "dpop+jwt",
60724
+ })
60725
+ .setIssuedAt()
60726
+ .sign(dpopKey.privateKey, {});
60727
+ }
60728
+ async function generateDpopKeyPair() {
60729
+ const { privateKey, publicKey } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)(PREFERRED_SIGNING_ALG[0]);
60730
+ const dpopKeyPair = {
60731
+ privateKey,
60732
+ publicKey: await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(publicKey),
60733
+ };
60734
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
60735
+ return dpopKeyPair;
60598
60736
  }
60599
60737
 
60600
- const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
60601
- function isExpectedAuthError(statusCode) {
60602
- return [401, 403].includes(statusCode);
60603
- }
60604
- async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
60605
- var _a;
60606
- const headers = new cross_fetch__WEBPACK_IMPORTED_MODULE_1__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60607
- headers.set("Authorization", `DPoP ${authToken}`);
60608
- headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
60609
- return {
60610
- ...defaultOptions,
60611
- headers,
60612
- };
60613
- }
60614
- async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
60615
- if (dpopKey !== undefined) {
60616
- return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
60617
- }
60618
- const headers = new cross_fetch__WEBPACK_IMPORTED_MODULE_1__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60619
- headers.set("Authorization", `Bearer ${authToken}`);
60620
- return {
60621
- ...defaultOptions,
60622
- headers,
60623
- };
60624
- }
60625
- async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
60626
- return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
60627
- }
60628
- async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
60629
- var _a;
60630
- const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
60631
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
60632
- if (typeof tokenSet.refreshToken === "string") {
60633
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
60634
- }
60635
- return {
60636
- accessToken: tokenSet.accessToken,
60637
- refreshToken: tokenSet.refreshToken,
60638
- expiresIn: tokenSet.expiresIn,
60639
- };
60640
- }
60641
- const computeRefreshDelay = (expiresIn) => {
60642
- if (expiresIn !== undefined) {
60643
- return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
60644
- ?
60645
- expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
60646
- : expiresIn;
60647
- }
60648
- return DEFAULT_EXPIRATION_TIME_SECONDS;
60649
- };
60650
- async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
60651
- var _a;
60652
- let currentAccessToken = accessToken;
60653
- let latestTimeout;
60654
- const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
60655
- if (currentRefreshOptions !== undefined) {
60656
- const proactivelyRefreshToken = async () => {
60657
- var _a, _b, _c, _d;
60658
- try {
60659
- const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
60660
- currentAccessToken = refreshedAccessToken;
60661
- if (refreshToken !== undefined) {
60662
- currentRefreshOptions.refreshToken = refreshToken;
60663
- }
60664
- clearTimeout(latestTimeout);
60665
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
60666
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60667
- }
60668
- catch (e) {
60669
- if (e instanceof OidcProviderError) {
60670
- (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
60671
- (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
60672
- }
60673
- if (e instanceof InvalidResponseError &&
60674
- e.missingFields.includes("access_token")) {
60675
- (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
60676
- }
60677
- }
60678
- };
60679
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
60680
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60681
- }
60682
- else if (options !== undefined && options.eventEmitter !== undefined) {
60683
- const expirationTimeout = setTimeout(() => {
60684
- options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
60685
- }, computeRefreshDelay(options.expiresIn) * 1000);
60686
- options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
60687
- }
60688
- return async (url, requestInit) => {
60689
- let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
60690
- const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
60691
- if (response.ok || failedButNotExpectedAuthError) {
60692
- return response;
60693
- }
60694
- const hasBeenRedirected = response.url !== url;
60695
- if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
60696
- response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
60697
- }
60698
- return response;
60699
- };
60738
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
60739
+ function isExpectedAuthError(statusCode) {
60740
+ return [401, 403].includes(statusCode);
60741
+ }
60742
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
60743
+ var _a;
60744
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60745
+ headers.set("Authorization", `DPoP ${authToken}`);
60746
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
60747
+ return {
60748
+ ...defaultOptions,
60749
+ headers,
60750
+ };
60751
+ }
60752
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
60753
+ if (dpopKey !== undefined) {
60754
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
60755
+ }
60756
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60757
+ headers.set("Authorization", `Bearer ${authToken}`);
60758
+ return {
60759
+ ...defaultOptions,
60760
+ headers,
60761
+ };
60762
+ }
60763
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
60764
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
60765
+ }
60766
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
60767
+ var _a;
60768
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
60769
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
60770
+ if (typeof tokenSet.refreshToken === "string") {
60771
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
60772
+ }
60773
+ return {
60774
+ accessToken: tokenSet.accessToken,
60775
+ refreshToken: tokenSet.refreshToken,
60776
+ expiresIn: tokenSet.expiresIn,
60777
+ };
60778
+ }
60779
+ const computeRefreshDelay = (expiresIn) => {
60780
+ if (expiresIn !== undefined) {
60781
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
60782
+ ?
60783
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
60784
+ : expiresIn;
60785
+ }
60786
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
60787
+ };
60788
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
60789
+ var _a;
60790
+ let currentAccessToken = accessToken;
60791
+ let latestTimeout;
60792
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
60793
+ if (currentRefreshOptions !== undefined) {
60794
+ const proactivelyRefreshToken = async () => {
60795
+ var _a, _b, _c, _d;
60796
+ try {
60797
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
60798
+ currentAccessToken = refreshedAccessToken;
60799
+ if (refreshToken !== undefined) {
60800
+ currentRefreshOptions.refreshToken = refreshToken;
60801
+ }
60802
+ clearTimeout(latestTimeout);
60803
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
60804
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60805
+ }
60806
+ catch (e) {
60807
+ if (e instanceof OidcProviderError) {
60808
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
60809
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
60810
+ }
60811
+ if (e instanceof InvalidResponseError &&
60812
+ e.missingFields.includes("access_token")) {
60813
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
60814
+ }
60815
+ }
60816
+ };
60817
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
60818
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60819
+ }
60820
+ else if (options !== undefined && options.eventEmitter !== undefined) {
60821
+ const expirationTimeout = setTimeout(() => {
60822
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
60823
+ }, computeRefreshDelay(options.expiresIn) * 1000);
60824
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
60825
+ }
60826
+ return async (url, requestInit) => {
60827
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
60828
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
60829
+ if (response.ok || failedButNotExpectedAuthError) {
60830
+ return response;
60831
+ }
60832
+ const hasBeenRedirected = response.url !== url;
60833
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
60834
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
60835
+ }
60836
+ return response;
60837
+ };
60700
60838
  }
60701
60839
 
60702
- const StorageUtilityGetResponse = "getResponse";
60703
- const StorageUtilityMock = {
60704
- get: async (key, options) => StorageUtilityGetResponse,
60705
- set: async (key, value) => {
60706
- },
60707
- delete: async (key) => {
60708
- },
60709
- getForUser: async (userId, key, options) => StorageUtilityGetResponse,
60710
- setForUser: async (userId, values, options) => {
60711
- },
60712
- deleteForUser: async (userId, key, options) => {
60713
- },
60714
- deleteAllUserData: async (userId, options) => {
60715
- },
60716
- };
60717
- const mockStorage = (stored) => {
60718
- const store = stored;
60719
- return {
60720
- get: async (key) => {
60721
- if (store[key] === undefined) {
60722
- return undefined;
60723
- }
60724
- if (typeof store[key] === "string") {
60725
- return store[key];
60726
- }
60727
- return JSON.stringify(store[key]);
60728
- },
60729
- set: async (key, value) => {
60730
- store[key] = value;
60731
- },
60732
- delete: async (key) => {
60733
- delete store[key];
60734
- },
60735
- };
60736
- };
60737
- const mockStorageUtility = (stored, isSecure = false) => {
60738
- if (isSecure) {
60739
- return new StorageUtility(mockStorage(stored), mockStorage({}));
60740
- }
60741
- return new StorageUtility(mockStorage({}), mockStorage(stored));
60840
+ const StorageUtilityGetResponse = "getResponse";
60841
+ const StorageUtilityMock = {
60842
+ get: async (key, options) => StorageUtilityGetResponse,
60843
+ set: async (key, value) => {
60844
+ },
60845
+ delete: async (key) => {
60846
+ },
60847
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
60848
+ setForUser: async (userId, values, options) => {
60849
+ },
60850
+ deleteForUser: async (userId, key, options) => {
60851
+ },
60852
+ deleteAllUserData: async (userId, options) => {
60853
+ },
60742
60854
  };
60855
+ const mockStorage = (stored) => {
60856
+ const store = stored;
60857
+ return {
60858
+ get: async (key) => {
60859
+ if (store[key] === undefined) {
60860
+ return undefined;
60861
+ }
60862
+ if (typeof store[key] === "string") {
60863
+ return store[key];
60864
+ }
60865
+ return JSON.stringify(store[key]);
60866
+ },
60867
+ set: async (key, value) => {
60868
+ store[key] = value;
60869
+ },
60870
+ delete: async (key) => {
60871
+ delete store[key];
60872
+ },
60873
+ };
60874
+ };
60875
+ const mockStorageUtility = (stored, isSecure = false) => {
60876
+ if (isSecure) {
60877
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
60878
+ }
60879
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
60880
+ };
60881
+
60882
+
60883
+
60884
+
60885
+ /***/ }),
60886
+
60887
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs":
60888
+ /*!*********************************************************************!*\
60889
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs ***!
60890
+ \*********************************************************************/
60891
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
60892
+
60893
+ "use strict";
60894
+ __webpack_require__.r(__webpack_exports__);
60895
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
60896
+ /* harmony export */ "Headers": () => (/* binding */ Headers),
60897
+ /* harmony export */ "Request": () => (/* binding */ Request),
60898
+ /* harmony export */ "Response": () => (/* binding */ Response),
60899
+ /* harmony export */ "default": () => (/* binding */ indexBrowser),
60900
+ /* harmony export */ "fetch": () => (/* binding */ fetch)
60901
+ /* harmony export */ });
60902
+ var indexBrowser = globalThis.fetch;
60903
+ const { fetch, Response, Request, Headers } = globalThis;
60743
60904
 
60744
60905
 
60745
60906