solid-ui 2.4.27-6c8461c9 → 2.4.27-70090f20

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, 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;
2682
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
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 = 35;
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;
2710
+ msg.maker = me.uri;
2711
+ // privateKey the cached private key of me, cached in store
2712
+ _context2.next = 32;
2695
2713
  return (0, _keys.getPrivateKey)(me);
2696
- case 19:
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
+ // me.uri)
2717
+ // const privateKey0 = 'a11bc5d2eee6cdb3b37f5473a712cad905ccfb13fb2ccdbf1be0a1ac4fdc7d2a'
2718
+ sig = (0, _signature.signMsg)(msg, privateKey); // const pubKey0 = '023a9da707bee1302f66083c9d95673ff969b41607a66f52686fa774d64ceb87'
2719
+ /* const pubKey = await getPublicKey(me)
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 35:
2726
+ _context2.prev = 35;
2727
+ _context2.next = 38;
2702
2728
  return _solidLogic.store.updater.update([], sts);
2703
- case 24:
2704
- _context2.next = 32;
2729
+ case 38:
2730
+ _context2.next = 46;
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 40:
2733
+ _context2.prev = 40;
2734
+ _context2.t0 = _context2["catch"](35);
2735
+ _errMsg = 'Error saving chat message: ' + _context2.t0;
2736
+ debug.warn(_errMsg);
2737
+ alert(_errMsg);
2738
+ throw new Error(_errMsg);
2739
+ case 46:
2714
2740
  return _context2.abrupt("return", message);
2715
- case 33:
2741
+ case 47:
2716
2742
  case "end":
2717
2743
  return _context2.stop();
2718
2744
  }
2719
- }, _callee2, null, [[21, 26]]);
2745
+ }, _callee2, null, [[35, 40]]);
2720
2746
  })();
2721
2747
  });
2722
2748
  function updateMessage(_x2) {
@@ -4011,82 +4037,215 @@ 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");
4017
4044
  var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js");
4018
4045
  var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"));
4046
+ var _accessData = __webpack_require__(/*! ../utils/keyHelpers/accessData */ "./lib/utils/keyHelpers/accessData.js");
4047
+ var _acl = __webpack_require__(/*! ../utils/keyHelpers/acl */ "./lib/utils/keyHelpers/acl.js");
4019
4048
  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
4049
  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
4050
  function generatePrivateKey() {
4024
4051
  return (0, _utils.bytesToHex)(_secp256k.schnorr.utils.randomPrivateKey());
4025
4052
  }
4026
4053
  function generatePublicKey(privateKey) {
4027
4054
  return (0, _utils.bytesToHex)(_secp256k.schnorr.getPublicKey(privateKey));
4028
4055
  }
4029
- 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
- var publicKey = publicKeyExists(webId);
4036
- return publicKey === null || publicKey === void 0 ? void 0 : publicKey.uri;
4037
- }
4038
- function publicKeyExists(webId) {
4039
- // find publickey
4040
- var url = new URL(webId);
4041
- url.hash = '';
4042
- _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;
4045
- }
4046
- function privateKeyExists(webId) {
4047
- 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;
4052
- }
4053
- function getPrivateKey(_x) {
4054
- return _getPrivateKey.apply(this, arguments);
4056
+
4057
+ /**
4058
+ * getPublicKey
4059
+ * used for displaying messages in chat, therefore does not
4060
+ * create a new key if not found
4061
+ * @param webId
4062
+ * @returns string | undefined
4063
+ */
4064
+ function getPublicKey(_x) {
4065
+ return _getPublicKey.apply(this, arguments);
4055
4066
  }
4056
- function _getPrivateKey() {
4057
- _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4058
- var url, privateKeyUrl, publicKey, privateKey, del, add;
4067
+ function _getPublicKey() {
4068
+ _getPublicKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4069
+ var publicKeyDoc, key;
4059
4070
  return _regenerator["default"].wrap(function _callee$(_context) {
4060
4071
  while (1) switch (_context.prev = _context.next) {
4061
4072
  case 0:
4062
- 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
4066
- if (!(!privateKey || !publicKey)) {
4067
- _context.next = 15;
4073
+ _context.next = 2;
4074
+ return _solidLogic.store.fetcher.load(webId);
4075
+ case 2:
4076
+ _context.next = 4;
4077
+ return (0, _accessData.pubKeyUrl)(webId);
4078
+ case 4:
4079
+ publicKeyDoc = _context.sent;
4080
+ _context.prev = 5;
4081
+ _context.next = 8;
4082
+ return _solidLogic.store.fetcher.load(publicKeyDoc);
4083
+ case 8:
4084
+ // url.href)
4085
+ key = _solidLogic.store.any(webId, _solidLogic.store.sym(_signature.CERT + 'PublicKey'));
4086
+ return _context.abrupt("return", key === null || key === void 0 ? void 0 : key.value);
4087
+ case 12:
4088
+ _context.prev = 12;
4089
+ _context.t0 = _context["catch"](5);
4090
+ return _context.abrupt("return", undefined);
4091
+ case 15:
4092
+ case "end":
4093
+ return _context.stop();
4094
+ }
4095
+ }, _callee, null, [[5, 12]]);
4096
+ }));
4097
+ return _getPublicKey.apply(this, arguments);
4098
+ }
4099
+ function getPrivateKey(_x2) {
4100
+ return _getPrivateKey.apply(this, arguments);
4101
+ }
4102
+ /**
4103
+ * delete acl if keydoc exists
4104
+ * create/edit keyDoc
4105
+ * set keyDoc acl
4106
+ */
4107
+ function _getPrivateKey() {
4108
+ _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
4109
+ var publicKeyDoc, privateKeyDoc, publicKey, privateKey, validPublicKey, del, add, newPublicKey, keyContainer;
4110
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
4111
+ while (1) switch (_context2.prev = _context2.next) {
4112
+ case 0:
4113
+ _context2.next = 2;
4114
+ return _solidLogic.store.fetcher.load(webId);
4115
+ case 2:
4116
+ _context2.next = 4;
4117
+ return (0, _accessData.pubKeyUrl)(webId);
4118
+ case 4:
4119
+ publicKeyDoc = _context2.sent;
4120
+ _context2.next = 7;
4121
+ return (0, _accessData.privKeyUrl)(webId);
4122
+ case 7:
4123
+ privateKeyDoc = _context2.sent;
4124
+ _context2.next = 10;
4125
+ return (0, _accessData.getExistingPublicKey)(webId, publicKeyDoc);
4126
+ case 10:
4127
+ publicKey = _context2.sent;
4128
+ _context2.next = 13;
4129
+ return (0, _accessData.getExistingPrivateKey)(webId, privateKeyDoc);
4130
+ case 13:
4131
+ privateKey = _context2.sent;
4132
+ // is publicKey valid ?
4133
+ validPublicKey = true;
4134
+ if (privateKey && publicKey !== generatePublicKey(privateKey)) {
4135
+ if (confirm('This is strange the publicKey is not valid for\n' + (webId === null || webId === void 0 ? void 0 : webId.uri) + '\'shall we repair keeping the private key ?')) validPublicKey = false;
4136
+ }
4137
+
4138
+ // create key pair or repair publicKey
4139
+ if (!(!privateKey || !publicKey || !validPublicKey)) {
4140
+ _context2.next = 34;
4068
4141
  break;
4069
4142
  }
4070
4143
  del = [];
4071
- 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;
4079
- return _solidLogic.store.updater.updateMany(del, add);
4080
- case 15:
4081
- return _context.abrupt("return", privateKey.uri);
4082
- case 16:
4144
+ add = []; // if (privateKey) del.push($rdf.st(webId, store.sym(CERT + 'PrivateKey'), $rdf.lit(privateKey), store.sym(privateKeyDoc)))
4145
+ if (privateKey) {
4146
+ _context2.next = 24;
4147
+ break;
4148
+ }
4149
+ // add = []
4150
+ privateKey = generatePrivateKey();
4151
+ add = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PrivateKey'), $rdf.literal(privateKey), _solidLogic.store.sym(privateKeyDoc))];
4152
+ _context2.next = 24;
4153
+ return saveKey(privateKeyDoc, [], add, webId.uri);
4154
+ case 24:
4155
+ if (!(!publicKey || !validPublicKey)) {
4156
+ _context2.next = 31;
4157
+ break;
4158
+ }
4159
+ del = [];
4160
+ // delete invalid public key
4161
+ if (publicKey) {
4162
+ del = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PublicKey'), $rdf.lit(publicKey), _solidLogic.store.sym(publicKeyDoc))];
4163
+ debug.log(del);
4164
+ }
4165
+ // update new valid key
4166
+ newPublicKey = generatePublicKey(privateKey);
4167
+ add = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PublicKey'), $rdf.literal(newPublicKey), _solidLogic.store.sym(publicKeyDoc))];
4168
+ _context2.next = 31;
4169
+ return saveKey(publicKeyDoc, del, add);
4170
+ case 31:
4171
+ keyContainer = privateKeyDoc.substring(0, privateKeyDoc.lastIndexOf('/') + 1);
4172
+ _context2.next = 34;
4173
+ return (0, _acl.setAcl)(keyContainer, (0, _acl.keyContainerAclBody)(webId.uri));
4174
+ case 34:
4175
+ return _context2.abrupt("return", privateKey);
4176
+ case 35:
4083
4177
  case "end":
4084
- return _context.stop();
4178
+ return _context2.stop();
4085
4179
  }
4086
- }, _callee);
4180
+ }, _callee2);
4087
4181
  }));
4088
4182
  return _getPrivateKey.apply(this, arguments);
4089
4183
  }
4184
+ function saveKey(_x3, _x4, _x5) {
4185
+ return _saveKey.apply(this, arguments);
4186
+ }
4187
+ function _saveKey() {
4188
+ _saveKey = (0, _asyncToGenerator2["default"])(function (keyDoc, del, add) {
4189
+ var me = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
4190
+ return /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
4191
+ var keyAclDoc, response, aclBody;
4192
+ return _regenerator["default"].wrap(function _callee3$(_context3) {
4193
+ while (1) switch (_context3.prev = _context3.next) {
4194
+ case 0:
4195
+ _context3.next = 2;
4196
+ return _solidLogic.store.fetcher.load(keyDoc);
4197
+ case 2:
4198
+ _context3.prev = 2;
4199
+ // get keyAcldoc
4200
+ keyAclDoc = _solidLogic.store.any(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl'));
4201
+ if (!keyAclDoc) {
4202
+ _context3.next = 17;
4203
+ break;
4204
+ }
4205
+ _context3.prev = 5;
4206
+ _context3.next = 8;
4207
+ return _solidLogic.store.fetcher.webOperation('DELETE', keyAclDoc.value);
4208
+ case 8:
4209
+ response = _context3.sent;
4210
+ // this may fail if webId is not an owner
4211
+ debug.log('delete ' + keyAclDoc.value + ' ' + response.status); // should test 404 and 2xx
4212
+ _context3.next = 17;
4213
+ break;
4214
+ case 12:
4215
+ _context3.prev = 12;
4216
+ _context3.t0 = _context3["catch"](5);
4217
+ if (!(_context3.t0.response.status !== 404)) {
4218
+ _context3.next = 16;
4219
+ break;
4220
+ }
4221
+ throw new Error(_context3.t0);
4222
+ case 16:
4223
+ debug.log('delete ' + keyAclDoc.value + ' ' + _context3.t0.response.status); // should test 404 and 2xx
4224
+ case 17:
4225
+ _context3.next = 19;
4226
+ return _solidLogic.store.updater.updateMany(del, add);
4227
+ case 19:
4228
+ // or a promise store.updater.update ?
4229
+ // create READ only ACL
4230
+ aclBody = (0, _acl.keyAclBody)(keyDoc, me);
4231
+ _context3.next = 22;
4232
+ return (0, _acl.setAcl)(keyDoc, aclBody);
4233
+ case 22:
4234
+ _context3.next = 27;
4235
+ break;
4236
+ case 24:
4237
+ _context3.prev = 24;
4238
+ _context3.t1 = _context3["catch"](2);
4239
+ throw new Error(_context3.t1);
4240
+ case 27:
4241
+ case "end":
4242
+ return _context3.stop();
4243
+ }
4244
+ }, _callee3, null, [[2, 24], [5, 12]]);
4245
+ })();
4246
+ });
4247
+ return _saveKey.apply(this, arguments);
4248
+ }
4090
4249
  //# sourceMappingURL=keys.js.map
4091
4250
 
4092
4251
  /***/ }),
@@ -4215,21 +4374,39 @@ function renderMessageRow(channelObject, message, fresh, options, userContext) {
4215
4374
  var creator = _solidLogic.store.any(message, ns.foaf('maker'));
4216
4375
  var date = _solidLogic.store.any(message, ns.dct('created'));
4217
4376
  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")));
4377
+ var latestVersionCreator = _solidLogic.store.any(latestVersion, ns.foaf('maker'));
4220
4378
 
4221
- // verify signature
4379
+ // use latest content if same owner, else use original
4380
+ var msgId = creator.uri === latestVersionCreator.uri ? latestVersion : message;
4381
+ var content = _solidLogic.store.any(msgId, ns.sioc('content'));
4382
+ var signature = _solidLogic.store.any(msgId, $rdf.sym("".concat(_signature.SEC, "Proof")));
4383
+
4384
+ // set message object
4222
4385
  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();
4386
+ msg.id = msgId.uri;
4387
+ msg.created = _solidLogic.store.any(msgId, ns.dct('created')).value;
4388
+ msg.content = content.value;
4389
+ msg.maker = creator.uri;
4390
+
4391
+ // unsigned message
4392
+ if (!(signature !== null && signature !== void 0 && signature.value)) debug.warn(msgId.uri + ' is unsigned'); // TODO replace with UI (colored message ?)
4393
+
4394
+ // signed message, get public key and check signature
4395
+ else {
4396
+ (0, _keys.getPublicKey)(creator).then(function (publicKey) {
4397
+ debug.log(creator.uri + '\n' + msg.created + '\n' + msg.id + '\n' + publicKey);
4398
+ if (!publicKey) {
4399
+ // TODO try to recreate the publicKey
4400
+ // if(me.uri === creator.uri) await getPrivateKey(creator)
4401
+ debug.warn('message is signed but ' + creator.uri + ' is missing publicKey');
4402
+ }
4403
+ // check that publicKey is a valid hex string
4404
+ var regex = /[0-9A-Fa-f]{6}/g;
4405
+ if (!(publicKey !== null && publicKey !== void 0 && publicKey.match(regex))) debug.warn('invalid publicKey hex string\n' + creator.uri + '\n' + publicKey);
4406
+ // verify signature
4407
+ else if (signature !== null && signature !== void 0 && signature.value && !(0, _signature.verifySignature)(signature === null || signature === void 0 ? void 0 : signature.value, msg, publicKey)) debug.warn('invalid signature\n' + msg.id);
4408
+ });
4409
+ }
4233
4410
  var originalMessage = (0, _chatLogic.originalVersion)(message);
4234
4411
  var edited = !message.sameTerm(originalMessage);
4235
4412
  var sortDate = _solidLogic.store.the(originalMessage, ns.dct('created'), null, originalMessage.doc()); // In message
@@ -5023,17 +5200,15 @@ Object.defineProperty(exports, "__esModule", ({
5023
5200
  value: true
5024
5201
  }));
5025
5202
  exports.SEC = exports.CERT = void 0;
5026
- exports.finishMsg = finishMsg;
5027
5203
  exports.getBlankMsg = getBlankMsg;
5028
5204
  exports.getMsgHash = getMsgHash;
5029
5205
  exports.serializeMsg = serializeMsg;
5030
5206
  exports.signMsg = signMsg;
5031
5207
  exports.utf8Encoder = exports.utf8Decoder = void 0;
5032
- exports.validateMsg = validateMsg;
5033
5208
  exports.verifySignature = verifySignature;
5034
5209
  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
5210
  var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
5211
+ var _sha = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
5037
5212
  // import {utf8Encoder} from './utils'
5038
5213
  // import { getPublicKey } from './keys'
5039
5214
 
@@ -5043,7 +5218,7 @@ var utf8Encoder = new TextEncoder();
5043
5218
  exports.utf8Encoder = utf8Encoder;
5044
5219
  var SEC = 'https://w3id.org/security#'; // Proof, VerificationMethod
5045
5220
  exports.SEC = SEC;
5046
- var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivatKey, PublicKey
5221
+ var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivateKey, PublicKey
5047
5222
 
5048
5223
  /* eslint-disable no-unused-vars */
5049
5224
  /* export enum Kind {
@@ -5075,19 +5250,22 @@ function getBlankMsg() {
5075
5250
  id: '',
5076
5251
  created: '',
5077
5252
  dateDeleted: '',
5253
+ // TODO to remove if not used
5078
5254
  content: '',
5079
5255
  maker: '',
5080
- sig: ''
5256
+ sig: '' // TODO to remove if not used
5081
5257
  };
5082
5258
  }
5083
- function finishMsg(t, privateKey) {
5084
- // to update to chat message triples
5085
- var message = t;
5086
- // message.pubkey = getPublicKey(privateKey)
5087
- message.id = getMsgHash(message);
5088
- message.sig = signMsg(message, privateKey);
5089
- return message;
5090
- }
5259
+
5260
+ /* export function finishMsg (t: MsgTemplate, privateKey: string): Message {
5261
+ // to update to chat message triples
5262
+ const message = t as Message
5263
+ // message.pubkey = getPublicKey(privateKey)
5264
+ message.id = getMsgHash(message)
5265
+ message.sig = signMsg(message, privateKey)
5266
+ return message
5267
+ } */
5268
+
5091
5269
  function serializeMsg(msg) {
5092
5270
  // to update to chat messages triples
5093
5271
  /* if (!validateMsg(msg))
@@ -5099,27 +5277,29 @@ function getMsgHash(message) {
5099
5277
  var msgHash = (0, _sha.sha256)(utf8Encoder.encode(serializeMsg(message)));
5100
5278
  return (0, _utils.bytesToHex)(msgHash);
5101
5279
  }
5102
- var isRecord = function isRecord(obj) {
5103
- return obj instanceof Object;
5104
- };
5105
- function validateMsg(message) {
5106
- /* if (!isRecord(message)) return false
5280
+
5281
+ // const isRecord = (obj: unknown): obj is Record<string, unknown> => obj instanceof Object
5282
+
5283
+ /* export function validateMsg<T> (message: T): message is T & UnsignedMsg {
5284
+ if (!isRecord(message)) return false
5107
5285
  if (typeof message.kind !== 'number') return false
5108
5286
  if (typeof message.content !== 'string') return false
5109
5287
  if (typeof message.created_at !== 'number') return false
5110
5288
  if (typeof message.pubkey !== 'string') return false
5111
5289
  if (!message.pubkey.match(/^[a-f0-9]{64}$/)) return false
5112
- if (!Array.isArray(message.tags)) return false
5290
+
5291
+ if (!Array.isArray(message.tags)) return false
5113
5292
  for (let i = 0; i < message.tags.length; i++) {
5114
5293
  let tag = message.tags[i]
5115
5294
  if (!Array.isArray(tag)) return false
5116
5295
  for (let j = 0; j < tag.length; j++) {
5117
5296
  if (typeof tag[j] === 'object') return false
5118
5297
  }
5119
- } */
5298
+ }
5299
+
5300
+ return true
5301
+ } */
5120
5302
 
5121
- return true;
5122
- }
5123
5303
  function verifySignature(sig, message, pubKey) {
5124
5304
  return _secp256k.schnorr.verify(sig, getMsgHash(message), pubKey);
5125
5305
  }
@@ -13048,6 +13228,353 @@ function predParentOf(node) {
13048
13228
 
13049
13229
  /***/ }),
13050
13230
 
13231
+ /***/ "./lib/utils/keyHelpers/accessData.js":
13232
+ /*!********************************************!*\
13233
+ !*** ./lib/utils/keyHelpers/accessData.js ***!
13234
+ \********************************************/
13235
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
13236
+
13237
+ "use strict";
13238
+
13239
+
13240
+ var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
13241
+ var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
13242
+ Object.defineProperty(exports, "__esModule", ({
13243
+ value: true
13244
+ }));
13245
+ exports.getExistingPrivateKey = getExistingPrivateKey;
13246
+ exports.getExistingPublicKey = getExistingPublicKey;
13247
+ exports.getKeyIfExists = getKeyIfExists;
13248
+ exports.pubKeyUrl = exports.privKeyUrl = exports.getPodRoot = void 0;
13249
+ var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
13250
+ var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
13251
+ var debug = _interopRequireWildcard(__webpack_require__(/*! ../../debug */ "./lib/debug.js"));
13252
+ var _signature = __webpack_require__(/*! ../../chat/signature */ "./lib/chat/signature.js");
13253
+ var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js");
13254
+ var ns = _interopRequireWildcard(__webpack_require__(/*! ../../ns */ "./lib/ns.js"));
13255
+ 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); }
13256
+ 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; }
13257
+ var getPodRoot = /*#__PURE__*/function () {
13258
+ var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
13259
+ var _podRoot;
13260
+ var webIdURL, storages, podRoot, path, _res$headers$get, res;
13261
+ return _regenerator["default"].wrap(function _callee$(_context) {
13262
+ while (1) switch (_context.prev = _context.next) {
13263
+ case 0:
13264
+ webIdURL = new URL(webId.uri); // find storages in webId document
13265
+ _context.next = 3;
13266
+ return _solidLogic.store.fetcher.load(webId.uri);
13267
+ case 3:
13268
+ storages = _solidLogic.store.each(webId, ns.space('storage'), null, webId.doc());
13269
+ if (storages !== null && storages !== void 0 && storages.length) {
13270
+ _context.next = 19;
13271
+ break;
13272
+ }
13273
+ // find storage recursively in webId URL
13274
+ path = webIdURL.pathname;
13275
+ case 6:
13276
+ if (!path.length) {
13277
+ _context.next = 17;
13278
+ break;
13279
+ }
13280
+ path = path.substring(0, path.lastIndexOf('/'));
13281
+ podRoot = _solidLogic.store.sym(webIdURL.origin + path + '/');
13282
+ _context.next = 11;
13283
+ return _solidLogic.store.fetcher.webOperation('HEAD', podRoot.uri);
13284
+ case 11:
13285
+ res = _context.sent;
13286
+ if (!((_res$headers$get = res.headers.get('link')) !== null && _res$headers$get !== void 0 && _res$headers$get.includes(ns.space('Storage').value))) {
13287
+ _context.next = 14;
13288
+ break;
13289
+ }
13290
+ return _context.abrupt("break", 17);
13291
+ case 14:
13292
+ if (!path) debug.warn("Current user storage not found for\n".concat(webId));
13293
+ _context.next = 6;
13294
+ break;
13295
+ case 17:
13296
+ _context.next = 21;
13297
+ break;
13298
+ case 19:
13299
+ // give preference to storage in webId root
13300
+ podRoot = storages.find(function (storage) {
13301
+ return webIdURL.origin === new URL(storage.value).origin;
13302
+ });
13303
+ if (!podRoot) podRoot = storages[0];
13304
+ case 21:
13305
+ return _context.abrupt("return", (_podRoot = podRoot) === null || _podRoot === void 0 ? void 0 : _podRoot.value);
13306
+ case 22:
13307
+ case "end":
13308
+ return _context.stop();
13309
+ }
13310
+ }, _callee);
13311
+ }));
13312
+ return function getPodRoot(_x) {
13313
+ return _ref.apply(this, arguments);
13314
+ };
13315
+ }();
13316
+ exports.getPodRoot = getPodRoot;
13317
+ var pubKeyUrl = /*#__PURE__*/function () {
13318
+ var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
13319
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
13320
+ while (1) switch (_context2.prev = _context2.next) {
13321
+ case 0:
13322
+ _context2.prev = 0;
13323
+ _context2.next = 3;
13324
+ return getPodRoot(webId);
13325
+ case 3:
13326
+ _context2.t0 = _context2.sent;
13327
+ return _context2.abrupt("return", _context2.t0 + 'profile/keys/publicKey.ttl');
13328
+ case 7:
13329
+ _context2.prev = 7;
13330
+ _context2.t1 = _context2["catch"](0);
13331
+ throw new Error(_context2.t1);
13332
+ case 10:
13333
+ case "end":
13334
+ return _context2.stop();
13335
+ }
13336
+ }, _callee2, null, [[0, 7]]);
13337
+ }));
13338
+ return function pubKeyUrl(_x2) {
13339
+ return _ref2.apply(this, arguments);
13340
+ };
13341
+ }();
13342
+ exports.pubKeyUrl = pubKeyUrl;
13343
+ function getExistingPublicKey(_x3, _x4) {
13344
+ return _getExistingPublicKey.apply(this, arguments);
13345
+ }
13346
+ function _getExistingPublicKey() {
13347
+ _getExistingPublicKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(webId, publicKeyUrl) {
13348
+ return _regenerator["default"].wrap(function _callee4$(_context4) {
13349
+ while (1) switch (_context4.prev = _context4.next) {
13350
+ case 0:
13351
+ _context4.next = 2;
13352
+ return getKeyIfExists(webId, publicKeyUrl, 'PublicKey');
13353
+ case 2:
13354
+ return _context4.abrupt("return", _context4.sent);
13355
+ case 3:
13356
+ case "end":
13357
+ return _context4.stop();
13358
+ }
13359
+ }, _callee4);
13360
+ }));
13361
+ return _getExistingPublicKey.apply(this, arguments);
13362
+ }
13363
+ var privKeyUrl = /*#__PURE__*/function () {
13364
+ var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(webId) {
13365
+ return _regenerator["default"].wrap(function _callee3$(_context3) {
13366
+ while (1) switch (_context3.prev = _context3.next) {
13367
+ case 0:
13368
+ _context3.prev = 0;
13369
+ _context3.next = 3;
13370
+ return getPodRoot(webId);
13371
+ case 3:
13372
+ _context3.t0 = _context3.sent;
13373
+ return _context3.abrupt("return", _context3.t0 + 'profile/keys/privateKey.ttl');
13374
+ case 7:
13375
+ _context3.prev = 7;
13376
+ _context3.t1 = _context3["catch"](0);
13377
+ throw new Error(_context3.t1);
13378
+ case 10:
13379
+ case "end":
13380
+ return _context3.stop();
13381
+ }
13382
+ }, _callee3, null, [[0, 7]]);
13383
+ }));
13384
+ return function privKeyUrl(_x5) {
13385
+ return _ref3.apply(this, arguments);
13386
+ };
13387
+ }();
13388
+ exports.privKeyUrl = privKeyUrl;
13389
+ function getExistingPrivateKey(_x6, _x7) {
13390
+ return _getExistingPrivateKey.apply(this, arguments);
13391
+ }
13392
+ function _getExistingPrivateKey() {
13393
+ _getExistingPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(webId, privateKeyUrl) {
13394
+ return _regenerator["default"].wrap(function _callee5$(_context5) {
13395
+ while (1) switch (_context5.prev = _context5.next) {
13396
+ case 0:
13397
+ _context5.next = 2;
13398
+ return getKeyIfExists(webId, privateKeyUrl, 'PrivateKey');
13399
+ case 2:
13400
+ return _context5.abrupt("return", _context5.sent);
13401
+ case 3:
13402
+ case "end":
13403
+ return _context5.stop();
13404
+ }
13405
+ }, _callee5);
13406
+ }));
13407
+ return _getExistingPrivateKey.apply(this, arguments);
13408
+ }
13409
+ function getKeyIfExists(_x8, _x9, _x10) {
13410
+ return _getKeyIfExists.apply(this, arguments);
13411
+ }
13412
+ function _getKeyIfExists() {
13413
+ _getKeyIfExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(webId, keyUrl, keyType) {
13414
+ var key, _err$response, data, contentType, response;
13415
+ return _regenerator["default"].wrap(function _callee6$(_context6) {
13416
+ while (1) switch (_context6.prev = _context6.next) {
13417
+ case 0:
13418
+ _context6.prev = 0;
13419
+ _context6.next = 3;
13420
+ return _solidLogic.store.fetcher.load(keyUrl);
13421
+ case 3:
13422
+ key = _solidLogic.store.any(webId, _solidLogic.store.sym(_signature.CERT + keyType));
13423
+ return _context6.abrupt("return", key === null || key === void 0 ? void 0 : key.value);
13424
+ case 7:
13425
+ _context6.prev = 7;
13426
+ _context6.t0 = _context6["catch"](0);
13427
+ if (!((_context6.t0 === null || _context6.t0 === void 0 ? void 0 : (_err$response = _context6.t0.response) === null || _err$response === void 0 ? void 0 : _err$response.status) === 404)) {
13428
+ _context6.next = 24;
13429
+ break;
13430
+ }
13431
+ _context6.prev = 10;
13432
+ // create resource
13433
+ data = '';
13434
+ contentType = 'text/turtle';
13435
+ _context6.next = 15;
13436
+ return _solidLogic.store.fetcher.webOperation('PUT', keyUrl, {
13437
+ data: data,
13438
+ contentType: contentType
13439
+ });
13440
+ case 15:
13441
+ response = _context6.sent;
13442
+ _context6.next = 22;
13443
+ break;
13444
+ case 18:
13445
+ _context6.prev = 18;
13446
+ _context6.t1 = _context6["catch"](10);
13447
+ debug.log('createIfNotExists doc FAILED: ' + keyUrl + ': ' + _context6.t1);
13448
+ throw _context6.t1;
13449
+ case 22:
13450
+ delete _solidLogic.store.fetcher.requested[keyUrl]; // delete cached 404 error
13451
+ return _context6.abrupt("return", undefined);
13452
+ case 24:
13453
+ debug.log('createIfNotExists doc FAILED: ' + keyUrl + ': ' + _context6.t0);
13454
+ throw _context6.t0;
13455
+ case 26:
13456
+ case "end":
13457
+ return _context6.stop();
13458
+ }
13459
+ }, _callee6, null, [[0, 7], [10, 18]]);
13460
+ }));
13461
+ return _getKeyIfExists.apply(this, arguments);
13462
+ }
13463
+ //# sourceMappingURL=accessData.js.map
13464
+
13465
+ /***/ }),
13466
+
13467
+ /***/ "./lib/utils/keyHelpers/acl.js":
13468
+ /*!*************************************!*\
13469
+ !*** ./lib/utils/keyHelpers/acl.js ***!
13470
+ \*************************************/
13471
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
13472
+
13473
+ "use strict";
13474
+
13475
+
13476
+ var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
13477
+ var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
13478
+ Object.defineProperty(exports, "__esModule", ({
13479
+ value: true
13480
+ }));
13481
+ exports.keyContainerAclBody = exports.keyAclBody = void 0;
13482
+ exports.setAcl = setAcl;
13483
+ var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
13484
+ var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
13485
+ var debug = _interopRequireWildcard(__webpack_require__(/*! ../../debug */ "./lib/debug.js"));
13486
+ var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js");
13487
+ 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); }
13488
+ 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; }
13489
+ /**
13490
+ * set ACL
13491
+ * @param keyDoc
13492
+ * @param aclBody
13493
+ */
13494
+ function setAcl(_x, _x2) {
13495
+ return _setAcl.apply(this, arguments);
13496
+ }
13497
+ /**
13498
+ * key container ACL
13499
+ * @param me
13500
+ * @returns aclBody
13501
+ */
13502
+ function _setAcl() {
13503
+ _setAcl = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(keyDoc, aclBody) {
13504
+ var keyAclDoc, response, aclResponse;
13505
+ return _regenerator["default"].wrap(function _callee$(_context) {
13506
+ while (1) switch (_context.prev = _context.next) {
13507
+ case 0:
13508
+ _context.next = 2;
13509
+ return _solidLogic.store.fetcher.load(keyDoc);
13510
+ case 2:
13511
+ // FIXME: check the Why value on this quad:
13512
+ debug.log(_solidLogic.store.statementsMatching(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl')));
13513
+ keyAclDoc = _solidLogic.store.any(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl'));
13514
+ if (keyAclDoc) {
13515
+ _context.next = 6;
13516
+ break;
13517
+ }
13518
+ throw new Error('Key ACL doc not found!');
13519
+ case 6:
13520
+ _context.prev = 6;
13521
+ _context.next = 9;
13522
+ return _solidLogic.store.fetcher.webOperation('DELETE', keyAclDoc.value);
13523
+ case 9:
13524
+ response = _context.sent;
13525
+ // this may fail if webId is not an owner
13526
+ debug.log('delete ' + keyAclDoc.value + ' ' + response.status); // should test 404 and 2xx
13527
+ _context.next = 18;
13528
+ break;
13529
+ case 13:
13530
+ _context.prev = 13;
13531
+ _context.t0 = _context["catch"](6);
13532
+ if (!(_context.t0.response.status !== 404)) {
13533
+ _context.next = 17;
13534
+ break;
13535
+ }
13536
+ throw new Error(_context.t0);
13537
+ case 17:
13538
+ debug.log('delete ' + keyAclDoc.value + ' ' + _context.t0.response.status); // should test 404 and 2xx
13539
+ case 18:
13540
+ _context.next = 20;
13541
+ return _solidLogic.store.fetcher.webOperation('PUT', keyAclDoc.value, {
13542
+ data: aclBody,
13543
+ contentType: 'text/turtle'
13544
+ });
13545
+ case 20:
13546
+ aclResponse = _context.sent;
13547
+ case 21:
13548
+ case "end":
13549
+ return _context.stop();
13550
+ }
13551
+ }, _callee, null, [[6, 13]]);
13552
+ }));
13553
+ return _setAcl.apply(this, arguments);
13554
+ }
13555
+ var keyContainerAclBody = function keyContainerAclBody(me) {
13556
+ var aclBody = "\n@prefix : <#>.\n@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n@prefix foaf: <http://xmlns.com/foaf/0.1/>.\n@prefix key: <./>.\n\n:ReadWrite\n a acl:Authorization;\n acl:accessTo key:;\n acl:default key:;\n acl:agent <".concat(me, ">;\n acl:mode acl:Read, acl:Write.\n");
13557
+ return aclBody;
13558
+ };
13559
+
13560
+ /**
13561
+ * Read only ACL
13562
+ * @param keyDoc
13563
+ * @param me
13564
+ * @returns aclBody
13565
+ */
13566
+ exports.keyContainerAclBody = keyContainerAclBody;
13567
+ var keyAclBody = function keyAclBody(keyDoc, me) {
13568
+ var keyAgent = 'acl:agentClass foaf:Agent'; // publicKey
13569
+ if (me !== null && me !== void 0 && me.length) keyAgent = "acl:agent <".concat(me, ">"); // privateKey
13570
+ var aclBody = "\n@prefix foaf: <http://xmlns.com/foaf/0.1/>.\n@prefix acl: <http://www.w3.org/ns/auth/acl#>.\n<#Read>\n a acl:Authorization;\n ".concat(keyAgent, ";\n acl:accessTo <").concat(keyDoc.split('/').pop(), ">;\n acl:mode acl:Read.\n");
13571
+ return aclBody;
13572
+ };
13573
+ exports.keyAclBody = keyAclBody;
13574
+ //# sourceMappingURL=acl.js.map
13575
+
13576
+ /***/ }),
13577
+
13051
13578
  /***/ "./lib/utils/label.js":
13052
13579
  /*!****************************!*\
13053
13580
  !*** ./lib/utils/label.js ***!
@@ -13176,8 +13703,8 @@ Object.defineProperty(exports, "__esModule", ({
13176
13703
  }));
13177
13704
  exports.versionInfo = void 0;
13178
13705
  var versionInfo = {
13179
- buildTime: '2023-04-18T15:43:25Z',
13180
- commit: '6c8461c90348c12751456ce058874760f5b987aa',
13706
+ buildTime: '2023-05-17T09:06:38Z',
13707
+ commit: '70090f2023b45d5656d749a1af527ae2dccf0d00',
13181
13708
  npmInfo: {
13182
13709
  'solid-ui': '2.4.27',
13183
13710
  npm: '8.19.4',
@@ -25340,6 +25867,8 @@ __webpack_require__.r(__webpack_exports__);
25340
25867
  /* 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
25868
  /* harmony import */ var _inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0__);
25342
25869
  /* 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");
25870
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
25871
+
25343
25872
 
25344
25873
 
25345
25874
 
@@ -25493,7 +26022,7 @@ async function getTokens(issuer, client, data, dpop) {
25493
26022
  headers,
25494
26023
  body: new URLSearchParams(requestBody).toString(),
25495
26024
  };
25496
- const rawTokenResponse = await await fetch(issuer.tokenEndpoint, tokenRequestInit);
26025
+ const rawTokenResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, tokenRequestInit);
25497
26026
  const jsonTokenResponse = (await rawTokenResponse.json());
25498
26027
  const tokenResponse = validateTokenEndpointResponse(jsonTokenResponse, dpop);
25499
26028
  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 +26106,7 @@ async function refresh(refreshToken, issuer, client, dpopKey) {
25577
26106
  else if (isValidUrl(client.clientId)) {
25578
26107
  requestBody.client_id = client.clientId;
25579
26108
  }
25580
- const rawResponse = await fetch(issuer.tokenEndpoint, {
26109
+ const rawResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, {
25581
26110
  method: "POST",
25582
26111
  body: new URLSearchParams(requestBody).toString(),
25583
26112
  headers: {
@@ -25692,8 +26221,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
26221
 
25693
26222
  Object.defineProperty(exports, "__esModule", ({ value: true }));
25694
26223
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26224
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
25695
26225
  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);
26226
+ const globalFetch = (request, init) => (0, universal_fetch_1.fetch)(request, init);
25697
26227
  class ClientAuthentication {
25698
26228
  constructor(loginHandler, redirectHandler, logoutHandler, sessionInfoManager, issuerConfigFetcher) {
25699
26229
  this.loginHandler = loginHandler;
@@ -26187,6 +26717,7 @@ exports["default"] = ClientRegistrar;
26187
26717
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26188
26718
  exports.WELL_KNOWN_OPENID_CONFIG = void 0;
26189
26719
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26720
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26190
26721
  exports.WELL_KNOWN_OPENID_CONFIG = ".well-known/openid-configuration";
26191
26722
  const issuerConfigKeyMap = {
26192
26723
  issuer: {
@@ -26293,7 +26824,7 @@ class IssuerConfigFetcher {
26293
26824
  async fetchConfig(issuer) {
26294
26825
  let issuerConfig;
26295
26826
  const openIdConfigUrl = new URL(exports.WELL_KNOWN_OPENID_CONFIG, issuer.endsWith("/") ? issuer : `${issuer}/`).href;
26296
- const issuerConfigRequestBody = await window.fetch(openIdConfigUrl);
26827
+ const issuerConfigRequestBody = await (0, universal_fetch_1.fetch)(openIdConfigUrl);
26297
26828
  try {
26298
26829
  issuerConfig = processConfig(await issuerConfigRequestBody.json());
26299
26830
  }
@@ -26396,6 +26927,7 @@ exports["default"] = Redirector;
26396
26927
 
26397
26928
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26398
26929
  exports.AuthCodeRedirectHandler = void 0;
26930
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26399
26931
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26400
26932
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
26401
26933
  class AuthCodeRedirectHandler {
@@ -26459,7 +26991,7 @@ class AuthCodeRedirectHandler {
26459
26991
  tokenRefresher: this.tokerRefresher,
26460
26992
  };
26461
26993
  }
26462
- const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(fetch, tokens.accessToken, {
26994
+ const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(universal_fetch_1.fetch, tokens.accessToken, {
26463
26995
  dpopKey: tokens.dpopKey,
26464
26996
  refreshOptions,
26465
26997
  eventEmitter,
@@ -26697,11 +27229,12 @@ exports.SessionInfoManager = exports.clear = exports.getUnauthenticatedSession =
26697
27229
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26698
27230
  const uuid_1 = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-browser/node_modules/uuid/dist/commonjs-browser/index.js");
26699
27231
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
27232
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26700
27233
  function getUnauthenticatedSession() {
26701
27234
  return {
26702
27235
  isLoggedIn: false,
26703
27236
  sessionId: (0, uuid_1.v4)(),
26704
- fetch,
27237
+ fetch: universal_fetch_1.fetch,
26705
27238
  };
26706
27239
  }
26707
27240
  exports.getUnauthenticatedSession = getUnauthenticatedSession;
@@ -27854,513 +28387,513 @@ exports["default"] = _default;
27854
28387
 
27855
28388
 
27856
28389
  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");
28390
+ var universalFetch = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
27858
28391
  var jose = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
27859
28392
  var uuid = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-core/node_modules/uuid/dist/commonjs-browser/index.js");
27860
28393
 
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";
28394
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
28395
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
28396
+ const EVENTS = {
28397
+ ERROR: "error",
28398
+ LOGIN: "login",
28399
+ LOGOUT: "logout",
28400
+ NEW_REFRESH_TOKEN: "newRefreshToken",
28401
+ SESSION_EXPIRED: "sessionExpired",
28402
+ SESSION_EXTENDED: "sessionExtended",
28403
+ SESSION_RESTORED: "sessionRestore",
28404
+ TIMEOUT_SET: "timeoutSet",
28405
+ };
28406
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
28407
+ const SCOPE_OPENID = "openid";
28408
+ const SCOPE_OFFLINE = "offline_access";
28409
+ const SCOPE_WEBID = "webid";
27877
28410
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
27878
28411
 
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
- },
28412
+ const buildProxyHandler = (toExclude, errorMessage) => ({
28413
+ get(target, prop, receiver) {
28414
+ if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&
28415
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
28416
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
28417
+ }
28418
+ return Reflect.get(target, prop, receiver);
28419
+ },
27887
28420
  });
27888
28421
 
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
- }
28422
+ class AggregateHandler {
28423
+ constructor(handleables) {
28424
+ this.handleables = handleables;
28425
+ }
28426
+ async getProperHandler(params) {
28427
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
28428
+ for (let i = 0; i < canHandleList.length; i += 1) {
28429
+ if (canHandleList[i]) {
28430
+ return this.handleables[i];
28431
+ }
28432
+ }
28433
+ return null;
28434
+ }
28435
+ async canHandle(...params) {
28436
+ return (await this.getProperHandler(params)) !== null;
28437
+ }
28438
+ async handle(...params) {
28439
+ const handler = await this.getProperHandler(params);
28440
+ if (handler) {
28441
+ return handler.handle(...params);
28442
+ }
28443
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
28444
+ .map((param) => {
28445
+ try {
28446
+ return JSON.stringify(param);
28447
+ }
28448
+ catch (err) {
28449
+ return param.toString();
28450
+ }
28451
+ })
28452
+ .join(", ")}`);
28453
+ }
27921
28454
  }
27922
28455
 
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
- }
28456
+ async function fetchJwks(jwksIri, issuerIri) {
28457
+ const jwksResponse = await universalFetch.fetch(jwksIri);
28458
+ if (jwksResponse.status !== 200) {
28459
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
28460
+ }
28461
+ let jwk;
28462
+ try {
28463
+ jwk = (await jwksResponse.json()).keys[0];
28464
+ }
28465
+ catch (e) {
28466
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
28467
+ }
28468
+ return jwk;
28469
+ }
28470
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
28471
+ const jwk = await fetchJwks(jwksIri, issuerIri);
28472
+ let payload;
28473
+ try {
28474
+ const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {
28475
+ issuer: issuerIri,
28476
+ audience: clientId,
28477
+ });
28478
+ payload = verifiedPayload;
28479
+ }
28480
+ catch (e) {
28481
+ throw new Error(`Token verification failed: ${e.stack}`);
28482
+ }
28483
+ if (typeof payload.webid === "string") {
28484
+ return payload.webid;
28485
+ }
28486
+ if (typeof payload.sub !== "string") {
28487
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
28488
+ }
28489
+ try {
28490
+ new URL(payload.sub);
28491
+ return payload.sub;
28492
+ }
28493
+ catch (e) {
28494
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
28495
+ }
27963
28496
  }
27964
28497
 
27965
- function isValidRedirectUrl(redirectUrl) {
27966
- try {
27967
- const urlObject = new URL(redirectUrl);
27968
- return urlObject.hash === "";
27969
- }
27970
- catch (e) {
27971
- return false;
27972
- }
28498
+ function isValidRedirectUrl(redirectUrl) {
28499
+ try {
28500
+ const urlObject = new URL(redirectUrl);
28501
+ return urlObject.hash === "";
28502
+ }
28503
+ catch (e) {
28504
+ return false;
28505
+ }
27973
28506
  }
27974
28507
 
27975
- function isSupportedTokenType(token) {
27976
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
28508
+ function isSupportedTokenType(token) {
28509
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
27977
28510
  }
27978
28511
 
27979
28512
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
27980
28513
 
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
- };
28514
+ function isValidUrl(url) {
28515
+ try {
28516
+ new URL(url);
28517
+ return true;
28518
+ }
28519
+ catch (_a) {
28520
+ return false;
28521
+ }
28522
+ }
28523
+ function determineSigningAlg(supported, preferred) {
28524
+ var _a;
28525
+ return ((_a = preferred.find((signingAlg) => {
28526
+ return supported.includes(signingAlg);
28527
+ })) !== null && _a !== void 0 ? _a : null);
28528
+ }
28529
+ function determineClientType(options, issuerConfig) {
28530
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
28531
+ return "static";
28532
+ }
28533
+ if (issuerConfig.scopesSupported.includes("webid") &&
28534
+ options.clientId !== undefined &&
28535
+ isValidUrl(options.clientId)) {
28536
+ return "solid-oidc";
28537
+ }
28538
+ return "dynamic";
28539
+ }
28540
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
28541
+ const clientType = determineClientType(options, issuerConfig);
28542
+ if (clientType === "dynamic") {
28543
+ return clientRegistrar.getClient({
28544
+ sessionId: options.sessionId,
28545
+ clientName: options.clientName,
28546
+ redirectUrl: options.redirectUrl,
28547
+ }, issuerConfig);
28548
+ }
28549
+ await storageUtility.setForUser(options.sessionId, {
28550
+ clientId: options.clientId,
28551
+ });
28552
+ if (options.clientSecret) {
28553
+ await storageUtility.setForUser(options.sessionId, {
28554
+ clientSecret: options.clientSecret,
28555
+ });
28556
+ }
28557
+ if (options.clientName) {
28558
+ await storageUtility.setForUser(options.sessionId, {
28559
+ clientName: options.clientName,
28560
+ });
28561
+ }
28562
+ return {
28563
+ clientId: options.clientId,
28564
+ clientSecret: options.clientSecret,
28565
+ clientName: options.clientName,
28566
+ clientType,
28567
+ };
28035
28568
  }
28036
28569
 
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
- }
28570
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
28571
+ return storageUtility.getForUser(oauthState, "sessionId");
28572
+ }
28573
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
28574
+ try {
28575
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
28576
+ storageUtility.getForUser(sessionId, "issuer", {
28577
+ errorIfNull: true,
28578
+ }),
28579
+ storageUtility.getForUser(sessionId, "codeVerifier"),
28580
+ storageUtility.getForUser(sessionId, "redirectUrl"),
28581
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
28582
+ ]);
28583
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
28584
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
28585
+ return {
28586
+ codeVerifier,
28587
+ redirectUrl: storedRedirectIri,
28588
+ issuerConfig,
28589
+ dpop: dpop === "true",
28590
+ };
28591
+ }
28592
+ catch (e) {
28593
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
28594
+ }
28595
+ }
28596
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
28597
+ if (refreshToken !== undefined) {
28598
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
28599
+ }
28600
+ if (webId !== undefined) {
28601
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
28602
+ }
28603
+ if (isLoggedIn !== undefined) {
28604
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
28605
+ }
28606
+ if (dpopKey !== undefined) {
28607
+ await storageUtility.setForUser(sessionId, {
28608
+ publicKey: JSON.stringify(dpopKey.publicKey),
28609
+ privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),
28610
+ }, { secure });
28611
+ }
28612
+ }
28613
+ class StorageUtility {
28614
+ constructor(secureStorage, insecureStorage) {
28615
+ this.secureStorage = secureStorage;
28616
+ this.insecureStorage = insecureStorage;
28617
+ }
28618
+ getKey(userId) {
28619
+ return `solidClientAuthenticationUser:${userId}`;
28620
+ }
28621
+ async getUserData(userId, secure) {
28622
+ const stored = await (secure
28623
+ ? this.secureStorage
28624
+ : this.insecureStorage).get(this.getKey(userId));
28625
+ if (stored === undefined) {
28626
+ return {};
28627
+ }
28628
+ try {
28629
+ return JSON.parse(stored);
28630
+ }
28631
+ catch (err) {
28632
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
28633
+ }
28634
+ }
28635
+ async setUserData(userId, data, secure) {
28636
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
28637
+ }
28638
+ async get(key, options) {
28639
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
28640
+ ? this.secureStorage
28641
+ : this.insecureStorage).get(key);
28642
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28643
+ throw new Error(`[${key}] is not stored`);
28644
+ }
28645
+ return value;
28646
+ }
28647
+ async set(key, value, options) {
28648
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
28649
+ }
28650
+ async delete(key, options) {
28651
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
28652
+ }
28653
+ async getForUser(userId, key, options) {
28654
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28655
+ let value;
28656
+ if (!userData || !userData[key]) {
28657
+ value = undefined;
28658
+ }
28659
+ value = userData[key];
28660
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28661
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
28662
+ }
28663
+ return value || undefined;
28664
+ }
28665
+ async setForUser(userId, values, options) {
28666
+ let userData;
28667
+ try {
28668
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28669
+ }
28670
+ catch (_a) {
28671
+ userData = {};
28672
+ }
28673
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
28674
+ }
28675
+ async deleteForUser(userId, key, options) {
28676
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28677
+ delete userData[key];
28678
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
28679
+ }
28680
+ async deleteAllUserData(userId, options) {
28681
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
28682
+ }
28150
28683
  }
28151
28684
 
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
- }
28685
+ class InMemoryStorage {
28686
+ constructor() {
28687
+ this.map = {};
28688
+ }
28689
+ async get(key) {
28690
+ return this.map[key] || undefined;
28691
+ }
28692
+ async set(key, value) {
28693
+ this.map[key] = value;
28694
+ }
28695
+ async delete(key) {
28696
+ delete this.map[key];
28697
+ }
28165
28698
  }
28166
28699
 
28167
- class ConfigurationError extends Error {
28168
- constructor(message) {
28169
- super(message);
28170
- }
28700
+ class ConfigurationError extends Error {
28701
+ constructor(message) {
28702
+ super(message);
28703
+ }
28171
28704
  }
28172
28705
 
28173
- class NotImplementedError extends Error {
28174
- constructor(methodName) {
28175
- super(`[${methodName}] is not implemented`);
28176
- }
28706
+ class NotImplementedError extends Error {
28707
+ constructor(methodName) {
28708
+ super(`[${methodName}] is not implemented`);
28709
+ }
28177
28710
  }
28178
28711
 
28179
- class InvalidResponseError extends Error {
28180
- constructor(missingFields) {
28181
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28182
- this.missingFields = missingFields;
28183
- }
28712
+ class InvalidResponseError extends Error {
28713
+ constructor(missingFields) {
28714
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28715
+ this.missingFields = missingFields;
28716
+ }
28184
28717
  }
28185
28718
 
28186
- class OidcProviderError extends Error {
28187
- constructor(message, error, errorDescription) {
28188
- super(message);
28189
- this.error = error;
28190
- this.errorDescription = errorDescription;
28191
- }
28719
+ class OidcProviderError extends Error {
28720
+ constructor(message, error, errorDescription) {
28721
+ super(message);
28722
+ this.error = error;
28723
+ this.errorDescription = errorDescription;
28724
+ }
28192
28725
  }
28193
28726
 
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;
28727
+ function normalizeHTU(audience) {
28728
+ const audienceUrl = new URL(audience);
28729
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
28730
+ }
28731
+ async function createDpopHeader(audience, method, dpopKey) {
28732
+ return new jose.SignJWT({
28733
+ htu: normalizeHTU(audience),
28734
+ htm: method.toUpperCase(),
28735
+ jti: uuid.v4(),
28736
+ })
28737
+ .setProtectedHeader({
28738
+ alg: PREFERRED_SIGNING_ALG[0],
28739
+ jwk: dpopKey.publicKey,
28740
+ typ: "dpop+jwt",
28741
+ })
28742
+ .setIssuedAt()
28743
+ .sign(dpopKey.privateKey, {});
28744
+ }
28745
+ async function generateDpopKeyPair() {
28746
+ const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);
28747
+ const dpopKeyPair = {
28748
+ privateKey,
28749
+ publicKey: await jose.exportJWK(publicKey),
28750
+ };
28751
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
28752
+ return dpopKeyPair;
28220
28753
  }
28221
28754
 
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
- };
28755
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
28756
+ function isExpectedAuthError(statusCode) {
28757
+ return [401, 403].includes(statusCode);
28758
+ }
28759
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
28760
+ var _a;
28761
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28762
+ headers.set("Authorization", `DPoP ${authToken}`);
28763
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
28764
+ return {
28765
+ ...defaultOptions,
28766
+ headers,
28767
+ };
28768
+ }
28769
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
28770
+ if (dpopKey !== undefined) {
28771
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
28772
+ }
28773
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28774
+ headers.set("Authorization", `Bearer ${authToken}`);
28775
+ return {
28776
+ ...defaultOptions,
28777
+ headers,
28778
+ };
28779
+ }
28780
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
28781
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
28782
+ }
28783
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
28784
+ var _a;
28785
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
28786
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
28787
+ if (typeof tokenSet.refreshToken === "string") {
28788
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
28789
+ }
28790
+ return {
28791
+ accessToken: tokenSet.accessToken,
28792
+ refreshToken: tokenSet.refreshToken,
28793
+ expiresIn: tokenSet.expiresIn,
28794
+ };
28795
+ }
28796
+ const computeRefreshDelay = (expiresIn) => {
28797
+ if (expiresIn !== undefined) {
28798
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
28799
+ ?
28800
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
28801
+ : expiresIn;
28802
+ }
28803
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
28804
+ };
28805
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
28806
+ var _a;
28807
+ let currentAccessToken = accessToken;
28808
+ let latestTimeout;
28809
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
28810
+ if (currentRefreshOptions !== undefined) {
28811
+ const proactivelyRefreshToken = async () => {
28812
+ var _a, _b, _c, _d;
28813
+ try {
28814
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
28815
+ currentAccessToken = refreshedAccessToken;
28816
+ if (refreshToken !== undefined) {
28817
+ currentRefreshOptions.refreshToken = refreshToken;
28818
+ }
28819
+ clearTimeout(latestTimeout);
28820
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
28821
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28822
+ }
28823
+ catch (e) {
28824
+ if (e instanceof OidcProviderError) {
28825
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
28826
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
28827
+ }
28828
+ if (e instanceof InvalidResponseError &&
28829
+ e.missingFields.includes("access_token")) {
28830
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
28831
+ }
28832
+ }
28833
+ };
28834
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
28835
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28836
+ }
28837
+ else if (options !== undefined && options.eventEmitter !== undefined) {
28838
+ const expirationTimeout = setTimeout(() => {
28839
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
28840
+ }, computeRefreshDelay(options.expiresIn) * 1000);
28841
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
28842
+ }
28843
+ return async (url, requestInit) => {
28844
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
28845
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
28846
+ if (response.ok || failedButNotExpectedAuthError) {
28847
+ return response;
28848
+ }
28849
+ const hasBeenRedirected = response.url !== url;
28850
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
28851
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
28852
+ }
28853
+ return response;
28854
+ };
28322
28855
  }
28323
28856
 
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));
28857
+ const StorageUtilityGetResponse = "getResponse";
28858
+ const StorageUtilityMock = {
28859
+ get: async (key, options) => StorageUtilityGetResponse,
28860
+ set: async (key, value) => {
28861
+ },
28862
+ delete: async (key) => {
28863
+ },
28864
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
28865
+ setForUser: async (userId, values, options) => {
28866
+ },
28867
+ deleteForUser: async (userId, key, options) => {
28868
+ },
28869
+ deleteAllUserData: async (userId, options) => {
28870
+ },
28871
+ };
28872
+ const mockStorage = (stored) => {
28873
+ const store = stored;
28874
+ return {
28875
+ get: async (key) => {
28876
+ if (store[key] === undefined) {
28877
+ return undefined;
28878
+ }
28879
+ if (typeof store[key] === "string") {
28880
+ return store[key];
28881
+ }
28882
+ return JSON.stringify(store[key]);
28883
+ },
28884
+ set: async (key, value) => {
28885
+ store[key] = value;
28886
+ },
28887
+ delete: async (key) => {
28888
+ delete store[key];
28889
+ },
28890
+ };
28891
+ };
28892
+ const mockStorageUtility = (stored, isSecure = false) => {
28893
+ if (isSecure) {
28894
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
28895
+ }
28896
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
28364
28897
  };
28365
28898
 
28366
28899
  exports.AggregateHandler = AggregateHandler;
@@ -29584,6 +30117,29 @@ function validate(uuid) {
29584
30117
 
29585
30118
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validate);
29586
30119
 
30120
+ /***/ }),
30121
+
30122
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js":
30123
+ /*!********************************************************************!*\
30124
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.js ***!
30125
+ \********************************************************************/
30126
+ /***/ ((__unused_webpack_module, exports) => {
30127
+
30128
+ "use strict";
30129
+
30130
+
30131
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
30132
+
30133
+ var indexBrowser = globalThis.fetch;
30134
+ const { fetch, Response, Request, Headers } = globalThis;
30135
+
30136
+ exports.Headers = Headers;
30137
+ exports.Request = Request;
30138
+ exports.Response = Response;
30139
+ exports["default"] = indexBrowser;
30140
+ exports.fetch = fetch;
30141
+
30142
+
29587
30143
  /***/ }),
29588
30144
 
29589
30145
  /***/ "./node_modules/@noble/curves/_shortw_utils.js":
@@ -60228,522 +60784,545 @@ __webpack_require__.r(__webpack_exports__);
60228
60784
  /* harmony export */ "saveSessionInfoToStorage": () => (/* binding */ saveSessionInfoToStorage)
60229
60785
  /* harmony export */ });
60230
60786
  /* 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");
60787
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
60788
+ /* harmony import */ var jose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
60233
60789
  /* 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
60790
 
60235
60791
 
60236
60792
 
60237
60793
 
60238
60794
 
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";
60795
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
60796
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
60797
+ const EVENTS = {
60798
+ ERROR: "error",
60799
+ LOGIN: "login",
60800
+ LOGOUT: "logout",
60801
+ NEW_REFRESH_TOKEN: "newRefreshToken",
60802
+ SESSION_EXPIRED: "sessionExpired",
60803
+ SESSION_EXTENDED: "sessionExtended",
60804
+ SESSION_RESTORED: "sessionRestore",
60805
+ TIMEOUT_SET: "timeoutSet",
60806
+ };
60807
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
60808
+ const SCOPE_OPENID = "openid";
60809
+ const SCOPE_OFFLINE = "offline_access";
60810
+ const SCOPE_WEBID = "webid";
60255
60811
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
60256
60812
 
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
- },
60813
+ const buildProxyHandler = (toExclude, errorMessage) => ({
60814
+ get(target, prop, receiver) {
60815
+ if (!Object.getOwnPropertyNames(events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter).includes(prop) &&
60816
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
60817
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
60818
+ }
60819
+ return Reflect.get(target, prop, receiver);
60820
+ },
60265
60821
  });
60266
60822
 
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
- }
60823
+ class AggregateHandler {
60824
+ constructor(handleables) {
60825
+ this.handleables = handleables;
60826
+ }
60827
+ async getProperHandler(params) {
60828
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
60829
+ for (let i = 0; i < canHandleList.length; i += 1) {
60830
+ if (canHandleList[i]) {
60831
+ return this.handleables[i];
60832
+ }
60833
+ }
60834
+ return null;
60835
+ }
60836
+ async canHandle(...params) {
60837
+ return (await this.getProperHandler(params)) !== null;
60838
+ }
60839
+ async handle(...params) {
60840
+ const handler = await this.getProperHandler(params);
60841
+ if (handler) {
60842
+ return handler.handle(...params);
60843
+ }
60844
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
60845
+ .map((param) => {
60846
+ try {
60847
+ return JSON.stringify(param);
60848
+ }
60849
+ catch (err) {
60850
+ return param.toString();
60851
+ }
60852
+ })
60853
+ .join(", ")}`);
60854
+ }
60299
60855
  }
60300
60856
 
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
- }
60857
+ async function fetchJwks(jwksIri, issuerIri) {
60858
+ const jwksResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(jwksIri);
60859
+ if (jwksResponse.status !== 200) {
60860
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
60861
+ }
60862
+ let jwk;
60863
+ try {
60864
+ jwk = (await jwksResponse.json()).keys[0];
60865
+ }
60866
+ catch (e) {
60867
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
60868
+ }
60869
+ return jwk;
60870
+ }
60871
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
60872
+ const jwk = await fetchJwks(jwksIri, issuerIri);
60873
+ let payload;
60874
+ try {
60875
+ const { payload: verifiedPayload } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.jwtVerify)(idToken, await (0,jose__WEBPACK_IMPORTED_MODULE_1__.importJWK)(jwk), {
60876
+ issuer: issuerIri,
60877
+ audience: clientId,
60878
+ });
60879
+ payload = verifiedPayload;
60880
+ }
60881
+ catch (e) {
60882
+ throw new Error(`Token verification failed: ${e.stack}`);
60883
+ }
60884
+ if (typeof payload.webid === "string") {
60885
+ return payload.webid;
60886
+ }
60887
+ if (typeof payload.sub !== "string") {
60888
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
60889
+ }
60890
+ try {
60891
+ new URL(payload.sub);
60892
+ return payload.sub;
60893
+ }
60894
+ catch (e) {
60895
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
60896
+ }
60341
60897
  }
60342
60898
 
60343
- function isValidRedirectUrl(redirectUrl) {
60344
- try {
60345
- const urlObject = new URL(redirectUrl);
60346
- return urlObject.hash === "";
60347
- }
60348
- catch (e) {
60349
- return false;
60350
- }
60899
+ function isValidRedirectUrl(redirectUrl) {
60900
+ try {
60901
+ const urlObject = new URL(redirectUrl);
60902
+ return urlObject.hash === "";
60903
+ }
60904
+ catch (e) {
60905
+ return false;
60906
+ }
60351
60907
  }
60352
60908
 
60353
- function isSupportedTokenType(token) {
60354
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60909
+ function isSupportedTokenType(token) {
60910
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60355
60911
  }
60356
60912
 
60357
60913
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
60358
60914
 
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
- };
60915
+ function isValidUrl(url) {
60916
+ try {
60917
+ new URL(url);
60918
+ return true;
60919
+ }
60920
+ catch (_a) {
60921
+ return false;
60922
+ }
60923
+ }
60924
+ function determineSigningAlg(supported, preferred) {
60925
+ var _a;
60926
+ return ((_a = preferred.find((signingAlg) => {
60927
+ return supported.includes(signingAlg);
60928
+ })) !== null && _a !== void 0 ? _a : null);
60929
+ }
60930
+ function determineClientType(options, issuerConfig) {
60931
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
60932
+ return "static";
60933
+ }
60934
+ if (issuerConfig.scopesSupported.includes("webid") &&
60935
+ options.clientId !== undefined &&
60936
+ isValidUrl(options.clientId)) {
60937
+ return "solid-oidc";
60938
+ }
60939
+ return "dynamic";
60940
+ }
60941
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
60942
+ const clientType = determineClientType(options, issuerConfig);
60943
+ if (clientType === "dynamic") {
60944
+ return clientRegistrar.getClient({
60945
+ sessionId: options.sessionId,
60946
+ clientName: options.clientName,
60947
+ redirectUrl: options.redirectUrl,
60948
+ }, issuerConfig);
60949
+ }
60950
+ await storageUtility.setForUser(options.sessionId, {
60951
+ clientId: options.clientId,
60952
+ });
60953
+ if (options.clientSecret) {
60954
+ await storageUtility.setForUser(options.sessionId, {
60955
+ clientSecret: options.clientSecret,
60956
+ });
60957
+ }
60958
+ if (options.clientName) {
60959
+ await storageUtility.setForUser(options.sessionId, {
60960
+ clientName: options.clientName,
60961
+ });
60962
+ }
60963
+ return {
60964
+ clientId: options.clientId,
60965
+ clientSecret: options.clientSecret,
60966
+ clientName: options.clientName,
60967
+ clientType,
60968
+ };
60413
60969
  }
60414
60970
 
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
- }
60971
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
60972
+ return storageUtility.getForUser(oauthState, "sessionId");
60973
+ }
60974
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
60975
+ try {
60976
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
60977
+ storageUtility.getForUser(sessionId, "issuer", {
60978
+ errorIfNull: true,
60979
+ }),
60980
+ storageUtility.getForUser(sessionId, "codeVerifier"),
60981
+ storageUtility.getForUser(sessionId, "redirectUrl"),
60982
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
60983
+ ]);
60984
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
60985
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
60986
+ return {
60987
+ codeVerifier,
60988
+ redirectUrl: storedRedirectIri,
60989
+ issuerConfig,
60990
+ dpop: dpop === "true",
60991
+ };
60992
+ }
60993
+ catch (e) {
60994
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
60995
+ }
60996
+ }
60997
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
60998
+ if (refreshToken !== undefined) {
60999
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
61000
+ }
61001
+ if (webId !== undefined) {
61002
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
61003
+ }
61004
+ if (isLoggedIn !== undefined) {
61005
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
61006
+ }
61007
+ if (dpopKey !== undefined) {
61008
+ await storageUtility.setForUser(sessionId, {
61009
+ publicKey: JSON.stringify(dpopKey.publicKey),
61010
+ privateKey: JSON.stringify(await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(dpopKey.privateKey)),
61011
+ }, { secure });
61012
+ }
61013
+ }
61014
+ class StorageUtility {
61015
+ constructor(secureStorage, insecureStorage) {
61016
+ this.secureStorage = secureStorage;
61017
+ this.insecureStorage = insecureStorage;
61018
+ }
61019
+ getKey(userId) {
61020
+ return `solidClientAuthenticationUser:${userId}`;
61021
+ }
61022
+ async getUserData(userId, secure) {
61023
+ const stored = await (secure
61024
+ ? this.secureStorage
61025
+ : this.insecureStorage).get(this.getKey(userId));
61026
+ if (stored === undefined) {
61027
+ return {};
61028
+ }
61029
+ try {
61030
+ return JSON.parse(stored);
61031
+ }
61032
+ catch (err) {
61033
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
61034
+ }
61035
+ }
61036
+ async setUserData(userId, data, secure) {
61037
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
61038
+ }
61039
+ async get(key, options) {
61040
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
61041
+ ? this.secureStorage
61042
+ : this.insecureStorage).get(key);
61043
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
61044
+ throw new Error(`[${key}] is not stored`);
61045
+ }
61046
+ return value;
61047
+ }
61048
+ async set(key, value, options) {
61049
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
61050
+ }
61051
+ async delete(key, options) {
61052
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
61053
+ }
61054
+ async getForUser(userId, key, options) {
61055
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61056
+ let value;
61057
+ if (!userData || !userData[key]) {
61058
+ value = undefined;
61059
+ }
61060
+ value = userData[key];
61061
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
61062
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
61063
+ }
61064
+ return value || undefined;
61065
+ }
61066
+ async setForUser(userId, values, options) {
61067
+ let userData;
61068
+ try {
61069
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61070
+ }
61071
+ catch (_a) {
61072
+ userData = {};
61073
+ }
61074
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
61075
+ }
61076
+ async deleteForUser(userId, key, options) {
61077
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61078
+ delete userData[key];
61079
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
61080
+ }
61081
+ async deleteAllUserData(userId, options) {
61082
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
61083
+ }
60528
61084
  }
60529
61085
 
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
- }
61086
+ class InMemoryStorage {
61087
+ constructor() {
61088
+ this.map = {};
61089
+ }
61090
+ async get(key) {
61091
+ return this.map[key] || undefined;
61092
+ }
61093
+ async set(key, value) {
61094
+ this.map[key] = value;
61095
+ }
61096
+ async delete(key) {
61097
+ delete this.map[key];
61098
+ }
60543
61099
  }
60544
61100
 
60545
- class ConfigurationError extends Error {
60546
- constructor(message) {
60547
- super(message);
60548
- }
61101
+ class ConfigurationError extends Error {
61102
+ constructor(message) {
61103
+ super(message);
61104
+ }
60549
61105
  }
60550
61106
 
60551
- class NotImplementedError extends Error {
60552
- constructor(methodName) {
60553
- super(`[${methodName}] is not implemented`);
60554
- }
61107
+ class NotImplementedError extends Error {
61108
+ constructor(methodName) {
61109
+ super(`[${methodName}] is not implemented`);
61110
+ }
60555
61111
  }
60556
61112
 
60557
- class InvalidResponseError extends Error {
60558
- constructor(missingFields) {
60559
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
60560
- this.missingFields = missingFields;
60561
- }
61113
+ class InvalidResponseError extends Error {
61114
+ constructor(missingFields) {
61115
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
61116
+ this.missingFields = missingFields;
61117
+ }
60562
61118
  }
60563
61119
 
60564
- class OidcProviderError extends Error {
60565
- constructor(message, error, errorDescription) {
60566
- super(message);
60567
- this.error = error;
60568
- this.errorDescription = errorDescription;
60569
- }
61120
+ class OidcProviderError extends Error {
61121
+ constructor(message, error, errorDescription) {
61122
+ super(message);
61123
+ this.error = error;
61124
+ this.errorDescription = errorDescription;
61125
+ }
60570
61126
  }
60571
61127
 
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;
61128
+ function normalizeHTU(audience) {
61129
+ const audienceUrl = new URL(audience);
61130
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
61131
+ }
61132
+ async function createDpopHeader(audience, method, dpopKey) {
61133
+ return new jose__WEBPACK_IMPORTED_MODULE_1__.SignJWT({
61134
+ htu: normalizeHTU(audience),
61135
+ htm: method.toUpperCase(),
61136
+ jti: (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])(),
61137
+ })
61138
+ .setProtectedHeader({
61139
+ alg: PREFERRED_SIGNING_ALG[0],
61140
+ jwk: dpopKey.publicKey,
61141
+ typ: "dpop+jwt",
61142
+ })
61143
+ .setIssuedAt()
61144
+ .sign(dpopKey.privateKey, {});
61145
+ }
61146
+ async function generateDpopKeyPair() {
61147
+ const { privateKey, publicKey } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)(PREFERRED_SIGNING_ALG[0]);
61148
+ const dpopKeyPair = {
61149
+ privateKey,
61150
+ publicKey: await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(publicKey),
61151
+ };
61152
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
61153
+ return dpopKeyPair;
60598
61154
  }
60599
61155
 
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
- };
61156
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
61157
+ function isExpectedAuthError(statusCode) {
61158
+ return [401, 403].includes(statusCode);
61159
+ }
61160
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
61161
+ var _a;
61162
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
61163
+ headers.set("Authorization", `DPoP ${authToken}`);
61164
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
61165
+ return {
61166
+ ...defaultOptions,
61167
+ headers,
61168
+ };
61169
+ }
61170
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
61171
+ if (dpopKey !== undefined) {
61172
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
61173
+ }
61174
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
61175
+ headers.set("Authorization", `Bearer ${authToken}`);
61176
+ return {
61177
+ ...defaultOptions,
61178
+ headers,
61179
+ };
61180
+ }
61181
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
61182
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
61183
+ }
61184
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
61185
+ var _a;
61186
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
61187
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
61188
+ if (typeof tokenSet.refreshToken === "string") {
61189
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
61190
+ }
61191
+ return {
61192
+ accessToken: tokenSet.accessToken,
61193
+ refreshToken: tokenSet.refreshToken,
61194
+ expiresIn: tokenSet.expiresIn,
61195
+ };
61196
+ }
61197
+ const computeRefreshDelay = (expiresIn) => {
61198
+ if (expiresIn !== undefined) {
61199
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
61200
+ ?
61201
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
61202
+ : expiresIn;
61203
+ }
61204
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
61205
+ };
61206
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
61207
+ var _a;
61208
+ let currentAccessToken = accessToken;
61209
+ let latestTimeout;
61210
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
61211
+ if (currentRefreshOptions !== undefined) {
61212
+ const proactivelyRefreshToken = async () => {
61213
+ var _a, _b, _c, _d;
61214
+ try {
61215
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
61216
+ currentAccessToken = refreshedAccessToken;
61217
+ if (refreshToken !== undefined) {
61218
+ currentRefreshOptions.refreshToken = refreshToken;
61219
+ }
61220
+ clearTimeout(latestTimeout);
61221
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
61222
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
61223
+ }
61224
+ catch (e) {
61225
+ if (e instanceof OidcProviderError) {
61226
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
61227
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
61228
+ }
61229
+ if (e instanceof InvalidResponseError &&
61230
+ e.missingFields.includes("access_token")) {
61231
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
61232
+ }
61233
+ }
61234
+ };
61235
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
61236
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
61237
+ }
61238
+ else if (options !== undefined && options.eventEmitter !== undefined) {
61239
+ const expirationTimeout = setTimeout(() => {
61240
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
61241
+ }, computeRefreshDelay(options.expiresIn) * 1000);
61242
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
61243
+ }
61244
+ return async (url, requestInit) => {
61245
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
61246
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
61247
+ if (response.ok || failedButNotExpectedAuthError) {
61248
+ return response;
61249
+ }
61250
+ const hasBeenRedirected = response.url !== url;
61251
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
61252
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
61253
+ }
61254
+ return response;
61255
+ };
60700
61256
  }
60701
61257
 
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));
61258
+ const StorageUtilityGetResponse = "getResponse";
61259
+ const StorageUtilityMock = {
61260
+ get: async (key, options) => StorageUtilityGetResponse,
61261
+ set: async (key, value) => {
61262
+ },
61263
+ delete: async (key) => {
61264
+ },
61265
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
61266
+ setForUser: async (userId, values, options) => {
61267
+ },
61268
+ deleteForUser: async (userId, key, options) => {
61269
+ },
61270
+ deleteAllUserData: async (userId, options) => {
61271
+ },
61272
+ };
61273
+ const mockStorage = (stored) => {
61274
+ const store = stored;
61275
+ return {
61276
+ get: async (key) => {
61277
+ if (store[key] === undefined) {
61278
+ return undefined;
61279
+ }
61280
+ if (typeof store[key] === "string") {
61281
+ return store[key];
61282
+ }
61283
+ return JSON.stringify(store[key]);
61284
+ },
61285
+ set: async (key, value) => {
61286
+ store[key] = value;
61287
+ },
61288
+ delete: async (key) => {
61289
+ delete store[key];
61290
+ },
61291
+ };
61292
+ };
61293
+ const mockStorageUtility = (stored, isSecure = false) => {
61294
+ if (isSecure) {
61295
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
61296
+ }
61297
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
60742
61298
  };
60743
61299
 
60744
61300
 
60745
61301
 
60746
61302
 
61303
+ /***/ }),
61304
+
61305
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs":
61306
+ /*!*********************************************************************!*\
61307
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs ***!
61308
+ \*********************************************************************/
61309
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
61310
+
61311
+ "use strict";
61312
+ __webpack_require__.r(__webpack_exports__);
61313
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
61314
+ /* harmony export */ "Headers": () => (/* binding */ Headers),
61315
+ /* harmony export */ "Request": () => (/* binding */ Request),
61316
+ /* harmony export */ "Response": () => (/* binding */ Response),
61317
+ /* harmony export */ "default": () => (/* binding */ indexBrowser),
61318
+ /* harmony export */ "fetch": () => (/* binding */ fetch)
61319
+ /* harmony export */ });
61320
+ var indexBrowser = globalThis.fetch;
61321
+ const { fetch, Response, Request, Headers } = globalThis;
61322
+
61323
+
61324
+
61325
+
60747
61326
  /***/ }),
60748
61327
 
60749
61328
  /***/ "./node_modules/jose/dist/browser/index.js":
@@ -61811,14 +62390,17 @@ __webpack_require__.r(__webpack_exports__);
61811
62390
  /* harmony export */ "createRemoteJWKSet": () => (/* binding */ createRemoteJWKSet)
61812
62391
  /* harmony export */ });
61813
62392
  /* harmony import */ var _runtime_fetch_jwks_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../runtime/fetch_jwks.js */ "./node_modules/jose/dist/browser/runtime/fetch_jwks.js");
61814
- /* harmony import */ var _runtime_env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../runtime/env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
61815
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
61816
- /* harmony import */ var _local_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./local.js */ "./node_modules/jose/dist/browser/jwks/local.js");
61817
-
62393
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
62394
+ /* harmony import */ var _local_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./local.js */ "./node_modules/jose/dist/browser/jwks/local.js");
61818
62395
 
61819
62396
 
61820
62397
 
61821
- class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
62398
+ function isCloudflareWorkers() {
62399
+ return (typeof WebSocketPair !== 'undefined' ||
62400
+ (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
62401
+ (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
62402
+ }
62403
+ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_2__.LocalJWKSet {
61822
62404
  constructor(url, options) {
61823
62405
  super({ keys: [] });
61824
62406
  this._jwks = undefined;
@@ -61851,7 +62433,7 @@ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
61851
62433
  return await super.getKey(protectedHeader, token);
61852
62434
  }
61853
62435
  catch (err) {
61854
- if (err instanceof _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JWKSNoMatchingKey) {
62436
+ if (err instanceof _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JWKSNoMatchingKey) {
61855
62437
  if (this.coolingDown() === false) {
61856
62438
  await this.reload();
61857
62439
  return super.getKey(protectedHeader, token);
@@ -61861,13 +62443,13 @@ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
61861
62443
  }
61862
62444
  }
61863
62445
  async reload() {
61864
- if (this._pendingFetch && (0,_runtime_env_js__WEBPACK_IMPORTED_MODULE_1__.isCloudflareWorkers)()) {
62446
+ if (this._pendingFetch && isCloudflareWorkers()) {
61865
62447
  this._pendingFetch = undefined;
61866
62448
  }
61867
62449
  this._pendingFetch || (this._pendingFetch = (0,_runtime_fetch_jwks_js__WEBPACK_IMPORTED_MODULE_0__["default"])(this._url, this._timeoutDuration, this._options)
61868
62450
  .then((json) => {
61869
- if (!(0,_local_js__WEBPACK_IMPORTED_MODULE_3__.isJWKSLike)(json)) {
61870
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JWKSInvalid('JSON Web Key Set malformed');
62451
+ if (!(0,_local_js__WEBPACK_IMPORTED_MODULE_2__.isJWKSLike)(json)) {
62452
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JWKSInvalid('JSON Web Key Set malformed');
61871
62453
  }
61872
62454
  this._jwks = { keys: json.keys };
61873
62455
  this._jwksTimestamp = Date.now();
@@ -63055,8 +63637,6 @@ __webpack_require__.r(__webpack_exports__);
63055
63637
  /* harmony export */ "checkEncCryptoKey": () => (/* binding */ checkEncCryptoKey),
63056
63638
  /* harmony export */ "checkSigCryptoKey": () => (/* binding */ checkSigCryptoKey)
63057
63639
  /* harmony export */ });
63058
- /* harmony import */ var _runtime_env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../runtime/env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
63059
-
63060
63640
  function unusable(name, prop = 'algorithm.name') {
63061
63641
  return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
63062
63642
  }
@@ -63131,11 +63711,6 @@ function checkSigCryptoKey(key, alg, ...usages) {
63131
63711
  }
63132
63712
  case 'EdDSA': {
63133
63713
  if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {
63134
- if ((0,_runtime_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)()) {
63135
- if (isAlgorithm(key.algorithm, 'NODE-ED25519'))
63136
- break;
63137
- throw unusable('Ed25519, Ed448, or NODE-ED25519');
63138
- }
63139
63714
  throw unusable('Ed25519 or Ed448');
63140
63715
  }
63141
63716
  break;
@@ -63966,14 +64541,12 @@ __webpack_require__.r(__webpack_exports__);
63966
64541
  /* harmony export */ "toPKCS8": () => (/* binding */ toPKCS8),
63967
64542
  /* harmony export */ "toSPKI": () => (/* binding */ toSPKI)
63968
64543
  /* harmony export */ });
63969
- /* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
63970
- /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
63971
- /* harmony import */ var _lib_invalid_key_input_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../lib/invalid_key_input.js */ "./node_modules/jose/dist/browser/lib/invalid_key_input.js");
63972
- /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
63973
- /* harmony import */ var _lib_format_pem_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../lib/format_pem.js */ "./node_modules/jose/dist/browser/lib/format_pem.js");
63974
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
63975
- /* harmony import */ var _is_key_like_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./is_key_like.js */ "./node_modules/jose/dist/browser/runtime/is_key_like.js");
63976
-
64544
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
64545
+ /* harmony import */ var _lib_invalid_key_input_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lib/invalid_key_input.js */ "./node_modules/jose/dist/browser/lib/invalid_key_input.js");
64546
+ /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
64547
+ /* harmony import */ var _lib_format_pem_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../lib/format_pem.js */ "./node_modules/jose/dist/browser/lib/format_pem.js");
64548
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
64549
+ /* harmony import */ var _is_key_like_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./is_key_like.js */ "./node_modules/jose/dist/browser/runtime/is_key_like.js");
63977
64550
 
63978
64551
 
63979
64552
 
@@ -63981,8 +64554,8 @@ __webpack_require__.r(__webpack_exports__);
63981
64554
 
63982
64555
 
63983
64556
  const genericExport = async (keyType, keyFormat, key) => {
63984
- if (!(0,_webcrypto_js__WEBPACK_IMPORTED_MODULE_1__.isCryptoKey)(key)) {
63985
- throw new TypeError((0,_lib_invalid_key_input_js__WEBPACK_IMPORTED_MODULE_2__["default"])(key, ..._is_key_like_js__WEBPACK_IMPORTED_MODULE_6__.types));
64557
+ if (!(0,_webcrypto_js__WEBPACK_IMPORTED_MODULE_0__.isCryptoKey)(key)) {
64558
+ throw new TypeError((0,_lib_invalid_key_input_js__WEBPACK_IMPORTED_MODULE_1__["default"])(key, ..._is_key_like_js__WEBPACK_IMPORTED_MODULE_5__.types));
63986
64559
  }
63987
64560
  if (!key.extractable) {
63988
64561
  throw new TypeError('CryptoKey is not extractable');
@@ -63990,7 +64563,7 @@ const genericExport = async (keyType, keyFormat, key) => {
63990
64563
  if (key.type !== keyType) {
63991
64564
  throw new TypeError(`key is not a ${keyType} key`);
63992
64565
  }
63993
- return (0,_lib_format_pem_js__WEBPACK_IMPORTED_MODULE_4__["default"])((0,_base64url_js__WEBPACK_IMPORTED_MODULE_3__.encodeBase64)(new Uint8Array(await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
64566
+ return (0,_lib_format_pem_js__WEBPACK_IMPORTED_MODULE_3__["default"])((0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.encodeBase64)(new Uint8Array(await _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
63994
64567
  };
63995
64568
  const toSPKI = (key) => {
63996
64569
  return genericExport('public', 'spki', key);
@@ -64028,11 +64601,11 @@ const getNamedCurve = (keyData) => {
64028
64601
  case findOid(keyData, [0x2b, 0x65, 0x71]):
64029
64602
  return 'Ed448';
64030
64603
  default:
64031
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_5__.JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');
64604
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_4__.JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');
64032
64605
  }
64033
64606
  };
64034
64607
  const genericImport = async (replace, keyFormat, pem, alg, options) => {
64035
- var _a, _b;
64608
+ var _a;
64036
64609
  let algorithm;
64037
64610
  let keyUsages;
64038
64611
  const keyData = new Uint8Array(atob(pem.replace(replace, ''))
@@ -64088,20 +64661,9 @@ const genericImport = async (replace, keyFormat, pem, alg, options) => {
64088
64661
  keyUsages = isPublic ? ['verify'] : ['sign'];
64089
64662
  break;
64090
64663
  default:
64091
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_5__.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
64092
- }
64093
- try {
64094
- return await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);
64095
- }
64096
- catch (err) {
64097
- if (algorithm.name === 'Ed25519' &&
64098
- (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' &&
64099
- (0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)()) {
64100
- algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };
64101
- return await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.importKey(keyFormat, keyData, algorithm, (_b = options === null || options === void 0 ? void 0 : options.extractable) !== null && _b !== void 0 ? _b : false, keyUsages);
64102
- }
64103
- throw err;
64664
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_4__.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
64104
64665
  }
64666
+ return _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);
64105
64667
  };
64106
64668
  const fromPKCS8 = (pem, alg, options) => {
64107
64669
  return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options);
@@ -64170,12 +64732,12 @@ function parseElement(bytes) {
64170
64732
  }
64171
64733
  function spkiFromX509(buf) {
64172
64734
  const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);
64173
- return (0,_base64url_js__WEBPACK_IMPORTED_MODULE_3__.encodeBase64)(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);
64735
+ return (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.encodeBase64)(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);
64174
64736
  }
64175
64737
  function getSPKI(x509) {
64176
64738
  const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '');
64177
- const raw = (0,_base64url_js__WEBPACK_IMPORTED_MODULE_3__.decodeBase64)(pem);
64178
- return (0,_lib_format_pem_js__WEBPACK_IMPORTED_MODULE_4__["default"])(spkiFromX509(raw), 'PUBLIC KEY');
64739
+ const raw = (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.decodeBase64)(pem);
64740
+ return (0,_lib_format_pem_js__WEBPACK_IMPORTED_MODULE_3__["default"])(spkiFromX509(raw), 'PUBLIC KEY');
64179
64741
  }
64180
64742
  const fromX509 = (pem, alg, options) => {
64181
64743
  let spki;
@@ -64603,26 +65165,6 @@ const encrypt = async (enc, plaintext, cek, iv, aad) => {
64603
65165
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (encrypt);
64604
65166
 
64605
65167
 
64606
- /***/ }),
64607
-
64608
- /***/ "./node_modules/jose/dist/browser/runtime/env.js":
64609
- /*!*******************************************************!*\
64610
- !*** ./node_modules/jose/dist/browser/runtime/env.js ***!
64611
- \*******************************************************/
64612
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
64613
-
64614
- "use strict";
64615
- __webpack_require__.r(__webpack_exports__);
64616
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
64617
- /* harmony export */ "isCloudflareWorkers": () => (/* binding */ isCloudflareWorkers)
64618
- /* harmony export */ });
64619
- function isCloudflareWorkers() {
64620
- return (typeof WebSocketPair !== 'undefined' ||
64621
- (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
64622
- (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
64623
- }
64624
-
64625
-
64626
65168
  /***/ }),
64627
65169
 
64628
65170
  /***/ "./node_modules/jose/dist/browser/runtime/fetch_jwks.js":
@@ -64687,11 +65229,9 @@ __webpack_require__.r(__webpack_exports__);
64687
65229
  /* harmony export */ "generateKeyPair": () => (/* binding */ generateKeyPair),
64688
65230
  /* harmony export */ "generateSecret": () => (/* binding */ generateSecret)
64689
65231
  /* harmony export */ });
64690
- /* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
64691
- /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
64692
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
64693
- /* harmony import */ var _random_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./random.js */ "./node_modules/jose/dist/browser/runtime/random.js");
64694
-
65232
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
65233
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65234
+ /* harmony import */ var _random_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./random.js */ "./node_modules/jose/dist/browser/runtime/random.js");
64695
65235
 
64696
65236
 
64697
65237
 
@@ -64712,7 +65252,7 @@ async function generateSecret(alg, options) {
64712
65252
  case 'A192CBC-HS384':
64713
65253
  case 'A256CBC-HS512':
64714
65254
  length = parseInt(alg.slice(-3), 10);
64715
- return (0,_random_js__WEBPACK_IMPORTED_MODULE_3__["default"])(new Uint8Array(length >> 3));
65255
+ return (0,_random_js__WEBPACK_IMPORTED_MODULE_2__["default"])(new Uint8Array(length >> 3));
64716
65256
  case 'A128KW':
64717
65257
  case 'A192KW':
64718
65258
  case 'A256KW':
@@ -64731,20 +65271,20 @@ async function generateSecret(alg, options) {
64731
65271
  keyUsages = ['encrypt', 'decrypt'];
64732
65272
  break;
64733
65273
  default:
64734
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65274
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64735
65275
  }
64736
- return _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);
65276
+ return _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);
64737
65277
  }
64738
65278
  function getModulusLengthOption(options) {
64739
65279
  var _a;
64740
65280
  const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048;
64741
65281
  if (typeof modulusLength !== 'number' || modulusLength < 2048) {
64742
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
65282
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
64743
65283
  }
64744
65284
  return modulusLength;
64745
65285
  }
64746
65286
  async function generateKeyPair(alg, options) {
64747
- var _a, _b, _c, _d;
65287
+ var _a, _b, _c;
64748
65288
  let algorithm;
64749
65289
  let keyUsages;
64750
65290
  switch (alg) {
@@ -64803,7 +65343,7 @@ async function generateKeyPair(alg, options) {
64803
65343
  algorithm = { name: crv };
64804
65344
  break;
64805
65345
  default:
64806
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported crv option provided');
65346
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported crv option provided');
64807
65347
  }
64808
65348
  break;
64809
65349
  case 'ECDH-ES':
@@ -64824,25 +65364,14 @@ async function generateKeyPair(alg, options) {
64824
65364
  algorithm = { name: crv };
64825
65365
  break;
64826
65366
  default:
64827
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448');
65367
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448');
64828
65368
  }
64829
65369
  break;
64830
65370
  }
64831
65371
  default:
64832
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64833
- }
64834
- try {
64835
- return (await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.generateKey(algorithm, (_c = options === null || options === void 0 ? void 0 : options.extractable) !== null && _c !== void 0 ? _c : false, keyUsages));
64836
- }
64837
- catch (err) {
64838
- if (algorithm.name === 'Ed25519' &&
64839
- (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' &&
64840
- (0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)()) {
64841
- algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };
64842
- return (await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.generateKey(algorithm, (_d = options === null || options === void 0 ? void 0 : options.extractable) !== null && _d !== void 0 ? _d : false, keyUsages));
64843
- }
64844
- throw err;
65372
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64845
65373
  }
65374
+ return (_webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.generateKey(algorithm, (_c = options === null || options === void 0 ? void 0 : options.extractable) !== null && _c !== void 0 ? _c : false, keyUsages));
64846
65375
  }
64847
65376
 
64848
65377
 
@@ -64917,11 +65446,9 @@ __webpack_require__.r(__webpack_exports__);
64917
65446
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
64918
65447
  /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
64919
65448
  /* harmony export */ });
64920
- /* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
64921
- /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
64922
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
64923
- /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
64924
-
65449
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
65450
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65451
+ /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
64925
65452
 
64926
65453
 
64927
65454
 
@@ -64940,7 +65467,7 @@ function subtleMapping(jwk) {
64940
65467
  case 'A128CBC-HS256':
64941
65468
  case 'A192CBC-HS384':
64942
65469
  case 'A256CBC-HS512':
64943
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`);
65470
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`);
64944
65471
  case 'A128GCM':
64945
65472
  case 'A192GCM':
64946
65473
  case 'A256GCM':
@@ -64963,7 +65490,7 @@ function subtleMapping(jwk) {
64963
65490
  keyUsages = ['deriveBits'];
64964
65491
  break;
64965
65492
  default:
64966
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65493
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64967
65494
  }
64968
65495
  break;
64969
65496
  }
@@ -64992,7 +65519,7 @@ function subtleMapping(jwk) {
64992
65519
  keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];
64993
65520
  break;
64994
65521
  default:
64995
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65522
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64996
65523
  }
64997
65524
  break;
64998
65525
  }
@@ -65018,7 +65545,7 @@ function subtleMapping(jwk) {
65018
65545
  keyUsages = jwk.d ? ['deriveBits'] : [];
65019
65546
  break;
65020
65547
  default:
65021
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65548
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65022
65549
  }
65023
65550
  break;
65024
65551
  }
@@ -65036,12 +65563,12 @@ function subtleMapping(jwk) {
65036
65563
  keyUsages = jwk.d ? ['deriveBits'] : [];
65037
65564
  break;
65038
65565
  default:
65039
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65566
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65040
65567
  }
65041
65568
  break;
65042
65569
  }
65043
65570
  default:
65044
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
65571
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
65045
65572
  }
65046
65573
  return { algorithm, keyUsages };
65047
65574
  }
@@ -65057,23 +65584,12 @@ const parse = async (jwk) => {
65057
65584
  (_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages,
65058
65585
  ];
65059
65586
  if (algorithm.name === 'PBKDF2') {
65060
- return _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.importKey('raw', (0,_base64url_js__WEBPACK_IMPORTED_MODULE_3__.decode)(jwk.k), ...rest);
65587
+ return _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.importKey('raw', (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.decode)(jwk.k), ...rest);
65061
65588
  }
65062
65589
  const keyData = { ...jwk };
65063
65590
  delete keyData.alg;
65064
65591
  delete keyData.use;
65065
- try {
65066
- return await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.importKey('jwk', keyData, ...rest);
65067
- }
65068
- catch (err) {
65069
- if (algorithm.name === 'Ed25519' &&
65070
- (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' &&
65071
- (0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)()) {
65072
- rest[0] = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };
65073
- return await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.importKey('jwk', keyData, ...rest);
65074
- }
65075
- throw err;
65076
- }
65592
+ return _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.importKey('jwk', keyData, ...rest);
65077
65593
  };
65078
65594
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (parse);
65079
65595
 
@@ -65315,9 +65831,7 @@ __webpack_require__.r(__webpack_exports__);
65315
65831
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
65316
65832
  /* harmony export */ "default": () => (/* binding */ subtleDsa)
65317
65833
  /* harmony export */ });
65318
- /* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
65319
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65320
-
65834
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65321
65835
 
65322
65836
  function subtleDsa(alg, algorithm) {
65323
65837
  const hash = `SHA-${alg.slice(-3)}`;
@@ -65339,12 +65853,9 @@ function subtleDsa(alg, algorithm) {
65339
65853
  case 'ES512':
65340
65854
  return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };
65341
65855
  case 'EdDSA':
65342
- if ((0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)() && algorithm.name === 'NODE-ED25519') {
65343
- return { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };
65344
- }
65345
65856
  return { name: algorithm.name };
65346
65857
  default:
65347
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
65858
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_0__.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
65348
65859
  }
65349
65860
  }
65350
65861