solid-ui 2.4.27-109c4946 → 2.4.27-12e3adbd

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,11 +4037,14 @@ 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
4050
  function generatePrivateKey() {
@@ -4024,66 +4053,208 @@ function generatePrivateKey() {
4024
4053
  function generatePublicKey(privateKey) {
4025
4054
  return (0, _utils.bytesToHex)(_secp256k.schnorr.getPublicKey(privateKey));
4026
4055
  }
4027
- function getPublicKey(webId) {
4028
- // find publickey
4029
- /* const url = new URL(webId)
4030
- url.hash = ''
4031
- store.fetcher.load(url.href)
4032
- let publicKey = store.any(store.sym(webId), store.sym(CERT +'publicKey')) */
4033
- var publicKey = publicKeyExists(webId);
4034
- return publicKey === null || publicKey === void 0 ? void 0 : publicKey.uri;
4035
- }
4036
- function publicKeyExists(webId) {
4037
- // find publickey
4038
- var url = new URL(webId);
4039
- url.hash = '';
4040
- _solidLogic.store.fetcher.load(url.href);
4041
- var publicKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'publicKey'));
4042
- return publicKey;
4043
- }
4044
- function privateKeyExists(webId) {
4045
- var url = new URL(webId);
4046
- var privateKeyUrl = url.hostname + '/profile/privateKey.ttl';
4047
- _solidLogic.store.fetcher.load(privateKeyUrl);
4048
- var privateKey = _solidLogic.store.any(_solidLogic.store.sym(webId), _solidLogic.store.sym(_signature.CERT + 'privateKey'));
4049
- return privateKey;
4050
- }
4051
- function getPrivateKey(_x) {
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);
4066
+ }
4067
+ function _getPublicKey() {
4068
+ _getPublicKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
4069
+ var publicKeyDoc, key;
4070
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
4071
+ while (1) switch (_context2.prev = _context2.next) {
4072
+ case 0:
4073
+ _context2.next = 2;
4074
+ return _solidLogic.store.fetcher.load(webId);
4075
+ case 2:
4076
+ _context2.next = 4;
4077
+ return (0, _accessData.pubKeyUrl)(webId);
4078
+ case 4:
4079
+ publicKeyDoc = _context2.sent;
4080
+ _context2.prev = 5;
4081
+ _context2.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 _context2.abrupt("return", key === null || key === void 0 ? void 0 : key.value);
4087
+ case 12:
4088
+ _context2.prev = 12;
4089
+ _context2.t0 = _context2["catch"](5);
4090
+ return _context2.abrupt("return", undefined);
4091
+ case 15:
4092
+ case "end":
4093
+ return _context2.stop();
4094
+ }
4095
+ }, _callee2, null, [[5, 12]]);
4096
+ }));
4097
+ return _getPublicKey.apply(this, arguments);
4098
+ }
4099
+ function getPrivateKey(_x2) {
4052
4100
  return _getPrivateKey.apply(this, arguments);
4053
4101
  }
4054
4102
  function _getPrivateKey() {
4055
- _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4056
- var url, privateKeyUrl, publicKey, privateKey, del, add;
4103
+ _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(webId) {
4104
+ var publicKeyDoc, privateKeyDoc, publicKey, privateKey, validPublicKey, del, add, newPublicKey, keyContainer;
4105
+ return _regenerator["default"].wrap(function _callee3$(_context3) {
4106
+ while (1) switch (_context3.prev = _context3.next) {
4107
+ case 0:
4108
+ _context3.next = 2;
4109
+ return _solidLogic.store.fetcher.load(webId);
4110
+ case 2:
4111
+ _context3.next = 4;
4112
+ return (0, _accessData.pubKeyUrl)(webId);
4113
+ case 4:
4114
+ publicKeyDoc = _context3.sent;
4115
+ _context3.next = 7;
4116
+ return (0, _accessData.privKeyUrl)(webId);
4117
+ case 7:
4118
+ privateKeyDoc = _context3.sent;
4119
+ _context3.next = 10;
4120
+ return (0, _accessData.getExistingPublicKey)(webId, publicKeyDoc);
4121
+ case 10:
4122
+ publicKey = _context3.sent;
4123
+ _context3.next = 13;
4124
+ return (0, _accessData.getExistingPrivateKey)(webId, privateKeyDoc);
4125
+ case 13:
4126
+ privateKey = _context3.sent;
4127
+ // is publicKey valid ?
4128
+ validPublicKey = true;
4129
+ if (privateKey && publicKey !== generatePublicKey(privateKey)) {
4130
+ 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;
4131
+ }
4132
+
4133
+ // create key pair or repair publicKey
4134
+ if (!(!privateKey || !publicKey || !validPublicKey)) {
4135
+ _context3.next = 34;
4136
+ break;
4137
+ }
4138
+ del = [];
4139
+ add = []; // if (privateKey) del.push($rdf.st(webId, store.sym(CERT + 'PrivateKey'), $rdf.lit(privateKey), store.sym(privateKeyDoc)))
4140
+ if (privateKey) {
4141
+ _context3.next = 24;
4142
+ break;
4143
+ }
4144
+ // add = []
4145
+ privateKey = generatePrivateKey();
4146
+ add = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PrivateKey'), $rdf.literal(privateKey), _solidLogic.store.sym(privateKeyDoc))];
4147
+ _context3.next = 24;
4148
+ return saveKey(privateKeyDoc, [], add, webId.uri);
4149
+ case 24:
4150
+ if (!(!publicKey || !validPublicKey)) {
4151
+ _context3.next = 31;
4152
+ break;
4153
+ }
4154
+ del = [];
4155
+ // delete invalid public key
4156
+ if (publicKey) {
4157
+ del = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PublicKey'), $rdf.lit(publicKey), _solidLogic.store.sym(publicKeyDoc))];
4158
+ debug.log(del);
4159
+ }
4160
+ // update new valid key
4161
+ newPublicKey = generatePublicKey(privateKey);
4162
+ add = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PublicKey'), $rdf.literal(newPublicKey), _solidLogic.store.sym(publicKeyDoc))];
4163
+ _context3.next = 31;
4164
+ return saveKey(publicKeyDoc, del, add);
4165
+ case 31:
4166
+ keyContainer = privateKeyDoc.substring(0, privateKeyDoc.lastIndexOf('/') + 1);
4167
+ _context3.next = 34;
4168
+ return (0, _acl.setAcl)(keyContainer, (0, _acl.keyContainerAclBody)(webId.uri));
4169
+ case 34:
4170
+ return _context3.abrupt("return", privateKey);
4171
+ case 35:
4172
+ case "end":
4173
+ return _context3.stop();
4174
+ }
4175
+ }, _callee3);
4176
+ }));
4177
+ return _getPrivateKey.apply(this, arguments);
4178
+ }
4179
+ var deleteKey = /*#__PURE__*/function () {
4180
+ var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(keyDoc) {
4181
+ var keyAclDoc, response;
4057
4182
  return _regenerator["default"].wrap(function _callee$(_context) {
4058
4183
  while (1) switch (_context.prev = _context.next) {
4059
4184
  case 0:
4060
- url = new URL(webId);
4061
- privateKeyUrl = url.hostname + '/profile/privateKey.ttl'; // find publickey
4062
- publicKey = publicKeyExists(webId); // find privateKey
4063
- privateKey = privateKeyExists(webId); // create key pair
4064
- if (!(!privateKey || !publicKey)) {
4185
+ _context.next = 2;
4186
+ return _solidLogic.store.fetcher.load(keyDoc);
4187
+ case 2:
4188
+ keyAclDoc = _solidLogic.store.any(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl'));
4189
+ if (!keyAclDoc) {
4190
+ _context.next = 16;
4191
+ break;
4192
+ }
4193
+ _context.prev = 4;
4194
+ _context.next = 7;
4195
+ return _solidLogic.store.fetcher.webOperation('DELETE', keyAclDoc.value);
4196
+ case 7:
4197
+ response = _context.sent;
4198
+ // this may fail if webId is not an owner
4199
+ debug.log('delete ' + keyAclDoc.value + ' ' + response.status); // should test 404 and 2xx
4200
+ _context.next = 16;
4201
+ break;
4202
+ case 11:
4203
+ _context.prev = 11;
4204
+ _context.t0 = _context["catch"](4);
4205
+ if (!(_context.t0.response.status !== 404)) {
4065
4206
  _context.next = 15;
4066
4207
  break;
4067
4208
  }
4068
- del = [];
4069
- add = [];
4070
- if (privateKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'privateKey'), privateKey, $rdf.sym(privateKeyUrl)));
4071
- if (publicKey) del.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'publicKey'), publicKey, $rdf.sym(url.href)));
4072
- privateKey = _solidLogic.store.sym(generatePrivateKey());
4073
- publicKey = _solidLogic.store.sym(generatePublicKey(privateKey.uri));
4074
- add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'privateKey'), $rdf.literal(privateKey.uri), $rdf.sym(privateKeyUrl)));
4075
- add.push($rdf.st($rdf.sym(webId), $rdf.sym(_signature.CERT + 'publicKey'), $rdf.literal(publicKey.uri), $rdf.sym(url.href)));
4076
- _context.next = 15;
4077
- return _solidLogic.store.updater.updateMany(del, add);
4209
+ throw new Error(_context.t0);
4078
4210
  case 15:
4079
- return _context.abrupt("return", privateKey.uri);
4211
+ debug.log('delete ' + keyAclDoc.value + ' ' + _context.t0.response.status); // should test 404 and 2xx
4080
4212
  case 16:
4081
4213
  case "end":
4082
4214
  return _context.stop();
4083
4215
  }
4084
- }, _callee);
4216
+ }, _callee, null, [[4, 11]]);
4085
4217
  }));
4086
- return _getPrivateKey.apply(this, arguments);
4218
+ return function deleteKey(_x3) {
4219
+ return _ref.apply(this, arguments);
4220
+ };
4221
+ }();
4222
+
4223
+ /**
4224
+ * delete acl if keydoc exists
4225
+ * create/edit keyDoc
4226
+ * set keyDoc acl
4227
+ */
4228
+ function saveKey(_x4, _x5, _x6) {
4229
+ return _saveKey.apply(this, arguments);
4230
+ }
4231
+ function _saveKey() {
4232
+ _saveKey = (0, _asyncToGenerator2["default"])(function (keyDoc, del, add) {
4233
+ var me = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
4234
+ return /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
4235
+ var aclBody;
4236
+ return _regenerator["default"].wrap(function _callee4$(_context4) {
4237
+ while (1) switch (_context4.prev = _context4.next) {
4238
+ case 0:
4239
+ _context4.next = 2;
4240
+ return deleteKey(keyDoc);
4241
+ case 2:
4242
+ _context4.next = 4;
4243
+ return _solidLogic.store.updater.updateMany(del, add);
4244
+ case 4:
4245
+ // or a promise store.updater.update ?
4246
+ // create READ only ACL
4247
+ aclBody = (0, _acl.keyAclBody)(keyDoc, me);
4248
+ _context4.next = 7;
4249
+ return (0, _acl.setAcl)(keyDoc, aclBody);
4250
+ case 7:
4251
+ case "end":
4252
+ return _context4.stop();
4253
+ }
4254
+ }, _callee4);
4255
+ })();
4256
+ });
4257
+ return _saveKey.apply(this, arguments);
4087
4258
  }
4088
4259
  //# sourceMappingURL=keys.js.map
4089
4260
 
@@ -4213,21 +4384,39 @@ function renderMessageRow(channelObject, message, fresh, options, userContext) {
4213
4384
  var creator = _solidLogic.store.any(message, ns.foaf('maker'));
4214
4385
  var date = _solidLogic.store.any(message, ns.dct('created'));
4215
4386
  var latestVersion = (0, _chatLogic.mostRecentVersion)(message);
4216
- var content = _solidLogic.store.any(latestVersion, ns.sioc('content'));
4217
- var signature = _solidLogic.store.any(message, $rdf.sym("".concat(_signature.SEC, "Proof")));
4387
+ var latestVersionCreator = _solidLogic.store.any(latestVersion, ns.foaf('maker'));
4218
4388
 
4219
- // verify signature
4389
+ // use latest content if same owner, else use original
4390
+ var msgId = creator.uri === latestVersionCreator.uri ? latestVersion : message;
4391
+ var content = _solidLogic.store.any(msgId, ns.sioc('content'));
4392
+ var signature = _solidLogic.store.any(msgId, $rdf.sym("".concat(_signature.SEC, "Proof")));
4393
+
4394
+ // set message object
4220
4395
  var msg = (0, _signature.getBlankMsg)();
4221
- msg.id = message;
4222
- msg.created = date;
4223
- // this is not correct.
4224
- // If the message has been edited/deleted we must verify the latest message and may be the intermediate ones
4225
- msg.content = content;
4226
- msg.maker = creator;
4227
-
4228
- // pubKey could be store in a cache for all makers
4229
- var pubKey = (0, _keys.getPublicKey)(creator); // alain no
4230
- if (!(0, _signature.verifySignature)(signature, msg, pubKey)) throw new Error();
4396
+ msg.id = msgId.uri;
4397
+ msg.created = _solidLogic.store.any(msgId, ns.dct('created')).value;
4398
+ msg.content = content.value;
4399
+ msg.maker = creator.uri;
4400
+
4401
+ // unsigned message
4402
+ if (!(signature !== null && signature !== void 0 && signature.value)) debug.warn(msgId.uri + ' is unsigned'); // TODO replace with UI (colored message ?)
4403
+
4404
+ // signed message, get public key and check signature
4405
+ else {
4406
+ (0, _keys.getPublicKey)(creator).then(function (publicKey) {
4407
+ debug.log(creator.uri + '\n' + msg.created + '\n' + msg.id + '\n' + publicKey);
4408
+ if (!publicKey) {
4409
+ // TODO try to recreate the publicKey
4410
+ // if(me.uri === creator.uri) await getPrivateKey(creator)
4411
+ debug.warn('message is signed but ' + creator.uri + ' is missing publicKey');
4412
+ }
4413
+ // check that publicKey is a valid hex string
4414
+ var regex = /[0-9A-Fa-f]{6}/g;
4415
+ if (!(publicKey !== null && publicKey !== void 0 && publicKey.match(regex))) debug.warn('invalid publicKey hex string\n' + creator.uri + '\n' + publicKey);
4416
+ // verify signature
4417
+ 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);
4418
+ });
4419
+ }
4231
4420
  var originalMessage = (0, _chatLogic.originalVersion)(message);
4232
4421
  var edited = !message.sameTerm(originalMessage);
4233
4422
  var sortDate = _solidLogic.store.the(originalMessage, ns.dct('created'), null, originalMessage.doc()); // In message
@@ -5021,17 +5210,15 @@ Object.defineProperty(exports, "__esModule", ({
5021
5210
  value: true
5022
5211
  }));
5023
5212
  exports.SEC = exports.CERT = void 0;
5024
- exports.finishMsg = finishMsg;
5025
5213
  exports.getBlankMsg = getBlankMsg;
5026
5214
  exports.getMsgHash = getMsgHash;
5027
5215
  exports.serializeMsg = serializeMsg;
5028
5216
  exports.signMsg = signMsg;
5029
5217
  exports.utf8Encoder = exports.utf8Decoder = void 0;
5030
- exports.validateMsg = validateMsg;
5031
5218
  exports.verifySignature = verifySignature;
5032
5219
  var _secp256k = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/secp256k1.js");
5033
- var _sha = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
5034
5220
  var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
5221
+ var _sha = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
5035
5222
  // import {utf8Encoder} from './utils'
5036
5223
  // import { getPublicKey } from './keys'
5037
5224
 
@@ -5041,7 +5228,7 @@ var utf8Encoder = new TextEncoder();
5041
5228
  exports.utf8Encoder = utf8Encoder;
5042
5229
  var SEC = 'https://w3id.org/security#'; // Proof, VerificationMethod
5043
5230
  exports.SEC = SEC;
5044
- var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivatKey, PublicKey
5231
+ var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivateKey, PublicKey
5045
5232
 
5046
5233
  /* eslint-disable no-unused-vars */
5047
5234
  /* export enum Kind {
@@ -5073,19 +5260,22 @@ function getBlankMsg() {
5073
5260
  id: '',
5074
5261
  created: '',
5075
5262
  dateDeleted: '',
5263
+ // TODO to remove if not used
5076
5264
  content: '',
5077
5265
  maker: '',
5078
- sig: ''
5266
+ sig: '' // TODO to remove if not used
5079
5267
  };
5080
5268
  }
5081
- function finishMsg(t, privateKey) {
5082
- // to update to chat message triples
5083
- var message = t;
5084
- // message.pubkey = getPublicKey(privateKey)
5085
- message.id = getMsgHash(message);
5086
- message.sig = signMsg(message, privateKey);
5087
- return message;
5088
- }
5269
+
5270
+ /* export function finishMsg (t: MsgTemplate, privateKey: string): Message {
5271
+ // to update to chat message triples
5272
+ const message = t as Message
5273
+ // message.pubkey = getPublicKey(privateKey)
5274
+ message.id = getMsgHash(message)
5275
+ message.sig = signMsg(message, privateKey)
5276
+ return message
5277
+ } */
5278
+
5089
5279
  function serializeMsg(msg) {
5090
5280
  // to update to chat messages triples
5091
5281
  /* if (!validateMsg(msg))
@@ -5097,27 +5287,29 @@ function getMsgHash(message) {
5097
5287
  var msgHash = (0, _sha.sha256)(utf8Encoder.encode(serializeMsg(message)));
5098
5288
  return (0, _utils.bytesToHex)(msgHash);
5099
5289
  }
5100
- var isRecord = function isRecord(obj) {
5101
- return obj instanceof Object;
5102
- };
5103
- function validateMsg(message) {
5104
- /* if (!isRecord(message)) return false
5290
+
5291
+ // const isRecord = (obj: unknown): obj is Record<string, unknown> => obj instanceof Object
5292
+
5293
+ /* export function validateMsg<T> (message: T): message is T & UnsignedMsg {
5294
+ if (!isRecord(message)) return false
5105
5295
  if (typeof message.kind !== 'number') return false
5106
5296
  if (typeof message.content !== 'string') return false
5107
5297
  if (typeof message.created_at !== 'number') return false
5108
5298
  if (typeof message.pubkey !== 'string') return false
5109
5299
  if (!message.pubkey.match(/^[a-f0-9]{64}$/)) return false
5110
- if (!Array.isArray(message.tags)) return false
5300
+
5301
+ if (!Array.isArray(message.tags)) return false
5111
5302
  for (let i = 0; i < message.tags.length; i++) {
5112
5303
  let tag = message.tags[i]
5113
5304
  if (!Array.isArray(tag)) return false
5114
5305
  for (let j = 0; j < tag.length; j++) {
5115
5306
  if (typeof tag[j] === 'object') return false
5116
5307
  }
5117
- } */
5308
+ }
5309
+
5310
+ return true
5311
+ } */
5118
5312
 
5119
- return true;
5120
- }
5121
5313
  function verifySignature(sig, message, pubKey) {
5122
5314
  return _secp256k.schnorr.verify(sig, getMsgHash(message), pubKey);
5123
5315
  }
@@ -13046,6 +13238,345 @@ function predParentOf(node) {
13046
13238
 
13047
13239
  /***/ }),
13048
13240
 
13241
+ /***/ "./lib/utils/keyHelpers/accessData.js":
13242
+ /*!********************************************!*\
13243
+ !*** ./lib/utils/keyHelpers/accessData.js ***!
13244
+ \********************************************/
13245
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
13246
+
13247
+ "use strict";
13248
+
13249
+
13250
+ var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
13251
+ var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
13252
+ Object.defineProperty(exports, "__esModule", ({
13253
+ value: true
13254
+ }));
13255
+ exports.getExistingPrivateKey = getExistingPrivateKey;
13256
+ exports.getExistingPublicKey = getExistingPublicKey;
13257
+ exports.getKeyIfExists = getKeyIfExists;
13258
+ exports.pubKeyUrl = exports.privKeyUrl = exports.getPodRoot = void 0;
13259
+ var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
13260
+ var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
13261
+ var debug = _interopRequireWildcard(__webpack_require__(/*! ../../debug */ "./lib/debug.js"));
13262
+ var _signature = __webpack_require__(/*! ../../chat/signature */ "./lib/chat/signature.js");
13263
+ var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js");
13264
+ var ns = _interopRequireWildcard(__webpack_require__(/*! ../../ns */ "./lib/ns.js"));
13265
+ 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); }
13266
+ 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; }
13267
+ var getPodRoot = /*#__PURE__*/function () {
13268
+ var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
13269
+ var _podRoot;
13270
+ var webIdURL, storages, podRoot, path, _res$headers$get, res;
13271
+ return _regenerator["default"].wrap(function _callee$(_context) {
13272
+ while (1) switch (_context.prev = _context.next) {
13273
+ case 0:
13274
+ webIdURL = new URL(webId.uri); // find storages in webId document
13275
+ _context.next = 3;
13276
+ return _solidLogic.store.fetcher.load(webId.uri);
13277
+ case 3:
13278
+ storages = _solidLogic.store.each(webId, ns.space('storage'), null, webId.doc());
13279
+ if (storages !== null && storages !== void 0 && storages.length) {
13280
+ _context.next = 19;
13281
+ break;
13282
+ }
13283
+ // find storage recursively in webId URL
13284
+ path = webIdURL.pathname;
13285
+ case 6:
13286
+ if (!path.length) {
13287
+ _context.next = 17;
13288
+ break;
13289
+ }
13290
+ path = path.substring(0, path.lastIndexOf('/'));
13291
+ podRoot = _solidLogic.store.sym(webIdURL.origin + path + '/');
13292
+ _context.next = 11;
13293
+ return _solidLogic.store.fetcher.webOperation('HEAD', podRoot.uri);
13294
+ case 11:
13295
+ res = _context.sent;
13296
+ if (!((_res$headers$get = res.headers.get('link')) !== null && _res$headers$get !== void 0 && _res$headers$get.includes(ns.space('Storage').value))) {
13297
+ _context.next = 14;
13298
+ break;
13299
+ }
13300
+ return _context.abrupt("break", 17);
13301
+ case 14:
13302
+ if (!path) debug.warn("Current user storage not found for\n".concat(webId));
13303
+ _context.next = 6;
13304
+ break;
13305
+ case 17:
13306
+ _context.next = 21;
13307
+ break;
13308
+ case 19:
13309
+ // give preference to storage in webId root
13310
+ podRoot = storages.find(function (storage) {
13311
+ return webIdURL.origin === new URL(storage.value).origin;
13312
+ });
13313
+ if (!podRoot) podRoot = storages[0];
13314
+ case 21:
13315
+ return _context.abrupt("return", (_podRoot = podRoot) === null || _podRoot === void 0 ? void 0 : _podRoot.value);
13316
+ case 22:
13317
+ case "end":
13318
+ return _context.stop();
13319
+ }
13320
+ }, _callee);
13321
+ }));
13322
+ return function getPodRoot(_x) {
13323
+ return _ref.apply(this, arguments);
13324
+ };
13325
+ }();
13326
+ exports.getPodRoot = getPodRoot;
13327
+ var pubKeyUrl = /*#__PURE__*/function () {
13328
+ var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
13329
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
13330
+ while (1) switch (_context2.prev = _context2.next) {
13331
+ case 0:
13332
+ _context2.prev = 0;
13333
+ _context2.next = 3;
13334
+ return getPodRoot(webId);
13335
+ case 3:
13336
+ _context2.t0 = _context2.sent;
13337
+ return _context2.abrupt("return", _context2.t0 + 'profile/keys/publicKey.ttl');
13338
+ case 7:
13339
+ _context2.prev = 7;
13340
+ _context2.t1 = _context2["catch"](0);
13341
+ throw new Error(_context2.t1);
13342
+ case 10:
13343
+ case "end":
13344
+ return _context2.stop();
13345
+ }
13346
+ }, _callee2, null, [[0, 7]]);
13347
+ }));
13348
+ return function pubKeyUrl(_x2) {
13349
+ return _ref2.apply(this, arguments);
13350
+ };
13351
+ }();
13352
+ exports.pubKeyUrl = pubKeyUrl;
13353
+ function getExistingPublicKey(_x3, _x4) {
13354
+ return _getExistingPublicKey.apply(this, arguments);
13355
+ }
13356
+ function _getExistingPublicKey() {
13357
+ _getExistingPublicKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(webId, publicKeyUrl) {
13358
+ return _regenerator["default"].wrap(function _callee4$(_context4) {
13359
+ while (1) switch (_context4.prev = _context4.next) {
13360
+ case 0:
13361
+ _context4.next = 2;
13362
+ return getKeyIfExists(webId, publicKeyUrl, 'PublicKey');
13363
+ case 2:
13364
+ return _context4.abrupt("return", _context4.sent);
13365
+ case 3:
13366
+ case "end":
13367
+ return _context4.stop();
13368
+ }
13369
+ }, _callee4);
13370
+ }));
13371
+ return _getExistingPublicKey.apply(this, arguments);
13372
+ }
13373
+ var privKeyUrl = /*#__PURE__*/function () {
13374
+ var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(webId) {
13375
+ return _regenerator["default"].wrap(function _callee3$(_context3) {
13376
+ while (1) switch (_context3.prev = _context3.next) {
13377
+ case 0:
13378
+ _context3.prev = 0;
13379
+ _context3.next = 3;
13380
+ return getPodRoot(webId);
13381
+ case 3:
13382
+ _context3.t0 = _context3.sent;
13383
+ return _context3.abrupt("return", _context3.t0 + 'profile/keys/privateKey.ttl');
13384
+ case 7:
13385
+ _context3.prev = 7;
13386
+ _context3.t1 = _context3["catch"](0);
13387
+ throw new Error(_context3.t1);
13388
+ case 10:
13389
+ case "end":
13390
+ return _context3.stop();
13391
+ }
13392
+ }, _callee3, null, [[0, 7]]);
13393
+ }));
13394
+ return function privKeyUrl(_x5) {
13395
+ return _ref3.apply(this, arguments);
13396
+ };
13397
+ }();
13398
+ exports.privKeyUrl = privKeyUrl;
13399
+ function getExistingPrivateKey(_x6, _x7) {
13400
+ return _getExistingPrivateKey.apply(this, arguments);
13401
+ }
13402
+ function _getExistingPrivateKey() {
13403
+ _getExistingPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(webId, privateKeyUrl) {
13404
+ return _regenerator["default"].wrap(function _callee5$(_context5) {
13405
+ while (1) switch (_context5.prev = _context5.next) {
13406
+ case 0:
13407
+ _context5.next = 2;
13408
+ return getKeyIfExists(webId, privateKeyUrl, 'PrivateKey');
13409
+ case 2:
13410
+ return _context5.abrupt("return", _context5.sent);
13411
+ case 3:
13412
+ case "end":
13413
+ return _context5.stop();
13414
+ }
13415
+ }, _callee5);
13416
+ }));
13417
+ return _getExistingPrivateKey.apply(this, arguments);
13418
+ }
13419
+ function getKeyIfExists(_x8, _x9, _x10) {
13420
+ return _getKeyIfExists.apply(this, arguments);
13421
+ }
13422
+ function _getKeyIfExists() {
13423
+ _getKeyIfExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(webId, keyUrl, keyType) {
13424
+ var key, _err$response, data, contentType, response;
13425
+ return _regenerator["default"].wrap(function _callee6$(_context6) {
13426
+ while (1) switch (_context6.prev = _context6.next) {
13427
+ case 0:
13428
+ _context6.prev = 0;
13429
+ _context6.next = 3;
13430
+ return _solidLogic.store.fetcher.load(keyUrl);
13431
+ case 3:
13432
+ key = _solidLogic.store.any(webId, _solidLogic.store.sym(_signature.CERT + keyType));
13433
+ return _context6.abrupt("return", key === null || key === void 0 ? void 0 : key.value);
13434
+ case 7:
13435
+ _context6.prev = 7;
13436
+ _context6.t0 = _context6["catch"](0);
13437
+ 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)) {
13438
+ _context6.next = 24;
13439
+ break;
13440
+ }
13441
+ _context6.prev = 10;
13442
+ // create resource
13443
+ data = '';
13444
+ contentType = 'text/turtle';
13445
+ _context6.next = 15;
13446
+ return _solidLogic.store.fetcher.webOperation('PUT', keyUrl, {
13447
+ data: data,
13448
+ contentType: contentType
13449
+ });
13450
+ case 15:
13451
+ response = _context6.sent;
13452
+ _context6.next = 22;
13453
+ break;
13454
+ case 18:
13455
+ _context6.prev = 18;
13456
+ _context6.t1 = _context6["catch"](10);
13457
+ debug.log('createIfNotExists doc FAILED: ' + keyUrl + ': ' + _context6.t1);
13458
+ throw _context6.t1;
13459
+ case 22:
13460
+ delete _solidLogic.store.fetcher.requested[keyUrl]; // delete cached 404 error
13461
+ return _context6.abrupt("return", undefined);
13462
+ case 24:
13463
+ debug.log('createIfNotExists doc FAILED: ' + keyUrl + ': ' + _context6.t0);
13464
+ throw _context6.t0;
13465
+ case 26:
13466
+ case "end":
13467
+ return _context6.stop();
13468
+ }
13469
+ }, _callee6, null, [[0, 7], [10, 18]]);
13470
+ }));
13471
+ return _getKeyIfExists.apply(this, arguments);
13472
+ }
13473
+ //# sourceMappingURL=accessData.js.map
13474
+
13475
+ /***/ }),
13476
+
13477
+ /***/ "./lib/utils/keyHelpers/acl.js":
13478
+ /*!*************************************!*\
13479
+ !*** ./lib/utils/keyHelpers/acl.js ***!
13480
+ \*************************************/
13481
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
13482
+
13483
+ "use strict";
13484
+
13485
+
13486
+ var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
13487
+ var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
13488
+ Object.defineProperty(exports, "__esModule", ({
13489
+ value: true
13490
+ }));
13491
+ exports.keyContainerAclBody = exports.keyAclBody = void 0;
13492
+ exports.setAcl = setAcl;
13493
+ var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
13494
+ var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
13495
+ var debug = _interopRequireWildcard(__webpack_require__(/*! ../../debug */ "./lib/debug.js"));
13496
+ var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js");
13497
+ 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); }
13498
+ 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; }
13499
+ /**
13500
+ * set ACL
13501
+ * @param keyDoc
13502
+ * @param aclBody
13503
+ */
13504
+ function setAcl(_x, _x2) {
13505
+ return _setAcl.apply(this, arguments);
13506
+ }
13507
+ /**
13508
+ * key container ACL
13509
+ * @param me
13510
+ * @returns aclBody
13511
+ */
13512
+ function _setAcl() {
13513
+ _setAcl = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(keyDoc, aclBody) {
13514
+ var keyAclDoc, _err$response;
13515
+ return _regenerator["default"].wrap(function _callee$(_context) {
13516
+ while (1) switch (_context.prev = _context.next) {
13517
+ case 0:
13518
+ _context.next = 2;
13519
+ return _solidLogic.store.fetcher.load(keyDoc);
13520
+ case 2:
13521
+ // FIXME: check the Why value on this quad:
13522
+ debug.log(_solidLogic.store.statementsMatching(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl')));
13523
+ keyAclDoc = _solidLogic.store.any(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl'));
13524
+ if (keyAclDoc) {
13525
+ _context.next = 6;
13526
+ break;
13527
+ }
13528
+ throw new Error('Key ACL doc not found!');
13529
+ case 6:
13530
+ _context.prev = 6;
13531
+ _context.next = 9;
13532
+ return _solidLogic.store.fetcher.webOperation('PUT', keyAclDoc.value, {
13533
+ data: aclBody,
13534
+ contentType: 'text/turtle'
13535
+ });
13536
+ case 9:
13537
+ _context.next = 16;
13538
+ break;
13539
+ case 11:
13540
+ _context.prev = 11;
13541
+ _context.t0 = _context["catch"](6);
13542
+ if (!((_context.t0 === null || _context.t0 === void 0 ? void 0 : (_err$response = _context.t0.response) === null || _err$response === void 0 ? void 0 : _err$response.status) !== 404)) {
13543
+ _context.next = 15;
13544
+ break;
13545
+ }
13546
+ throw new Error(_context.t0);
13547
+ case 15:
13548
+ debug.log('delete ' + keyAclDoc.value + ' ' + _context.t0.response.status); // should test 404 and 2xx
13549
+ case 16:
13550
+ case "end":
13551
+ return _context.stop();
13552
+ }
13553
+ }, _callee, null, [[6, 11]]);
13554
+ }));
13555
+ return _setAcl.apply(this, arguments);
13556
+ }
13557
+ var keyContainerAclBody = function keyContainerAclBody(me) {
13558
+ 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");
13559
+ return aclBody;
13560
+ };
13561
+
13562
+ /**
13563
+ * Read only ACL
13564
+ * @param keyDoc
13565
+ * @param me
13566
+ * @returns aclBody
13567
+ */
13568
+ exports.keyContainerAclBody = keyContainerAclBody;
13569
+ var keyAclBody = function keyAclBody(keyDoc, me) {
13570
+ var keyAgent = 'acl:agentClass foaf:Agent'; // publicKey
13571
+ if (me !== null && me !== void 0 && me.length) keyAgent = "acl:agent <".concat(me, ">"); // privateKey
13572
+ 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");
13573
+ return aclBody;
13574
+ };
13575
+ exports.keyAclBody = keyAclBody;
13576
+ //# sourceMappingURL=acl.js.map
13577
+
13578
+ /***/ }),
13579
+
13049
13580
  /***/ "./lib/utils/label.js":
13050
13581
  /*!****************************!*\
13051
13582
  !*** ./lib/utils/label.js ***!
@@ -13174,8 +13705,8 @@ Object.defineProperty(exports, "__esModule", ({
13174
13705
  }));
13175
13706
  exports.versionInfo = void 0;
13176
13707
  var versionInfo = {
13177
- buildTime: '2023-04-17T20:18:29Z',
13178
- commit: '109c494647e55d98f10d60fe5b5168e8704b3a8a',
13708
+ buildTime: '2023-05-17T23:41:51Z',
13709
+ commit: '12e3adbdbcc77e443fa4f8715e447549e2192111',
13179
13710
  npmInfo: {
13180
13711
  'solid-ui': '2.4.27',
13181
13712
  npm: '8.19.4',
@@ -25338,6 +25869,8 @@ __webpack_require__.r(__webpack_exports__);
25338
25869
  /* 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");
25339
25870
  /* harmony import */ var _inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0__);
25340
25871
  /* 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");
25872
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
25873
+
25341
25874
 
25342
25875
 
25343
25876
 
@@ -25491,7 +26024,7 @@ async function getTokens(issuer, client, data, dpop) {
25491
26024
  headers,
25492
26025
  body: new URLSearchParams(requestBody).toString(),
25493
26026
  };
25494
- const rawTokenResponse = await await fetch(issuer.tokenEndpoint, tokenRequestInit);
26027
+ const rawTokenResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, tokenRequestInit);
25495
26028
  const jsonTokenResponse = (await rawTokenResponse.json());
25496
26029
  const tokenResponse = validateTokenEndpointResponse(jsonTokenResponse, dpop);
25497
26030
  const webId = await (0,_inrupt_solid_client_authn_core__WEBPACK_IMPORTED_MODULE_1__.getWebidFromTokenPayload)(tokenResponse.id_token, issuer.jwksUri, issuer.issuer, client.clientId);
@@ -25575,7 +26108,7 @@ async function refresh(refreshToken, issuer, client, dpopKey) {
25575
26108
  else if (isValidUrl(client.clientId)) {
25576
26109
  requestBody.client_id = client.clientId;
25577
26110
  }
25578
- const rawResponse = await fetch(issuer.tokenEndpoint, {
26111
+ const rawResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, {
25579
26112
  method: "POST",
25580
26113
  body: new URLSearchParams(requestBody).toString(),
25581
26114
  headers: {
@@ -25690,8 +26223,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=
25690
26223
 
25691
26224
  Object.defineProperty(exports, "__esModule", ({ value: true }));
25692
26225
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26226
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
25693
26227
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
25694
- const globalFetch = (request, init) => window.fetch(request, init);
26228
+ const globalFetch = (request, init) => (0, universal_fetch_1.fetch)(request, init);
25695
26229
  class ClientAuthentication {
25696
26230
  constructor(loginHandler, redirectHandler, logoutHandler, sessionInfoManager, issuerConfigFetcher) {
25697
26231
  this.loginHandler = loginHandler;
@@ -26185,6 +26719,7 @@ exports["default"] = ClientRegistrar;
26185
26719
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26186
26720
  exports.WELL_KNOWN_OPENID_CONFIG = void 0;
26187
26721
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26722
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26188
26723
  exports.WELL_KNOWN_OPENID_CONFIG = ".well-known/openid-configuration";
26189
26724
  const issuerConfigKeyMap = {
26190
26725
  issuer: {
@@ -26291,7 +26826,7 @@ class IssuerConfigFetcher {
26291
26826
  async fetchConfig(issuer) {
26292
26827
  let issuerConfig;
26293
26828
  const openIdConfigUrl = new URL(exports.WELL_KNOWN_OPENID_CONFIG, issuer.endsWith("/") ? issuer : `${issuer}/`).href;
26294
- const issuerConfigRequestBody = await window.fetch(openIdConfigUrl);
26829
+ const issuerConfigRequestBody = await (0, universal_fetch_1.fetch)(openIdConfigUrl);
26295
26830
  try {
26296
26831
  issuerConfig = processConfig(await issuerConfigRequestBody.json());
26297
26832
  }
@@ -26394,6 +26929,7 @@ exports["default"] = Redirector;
26394
26929
 
26395
26930
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26396
26931
  exports.AuthCodeRedirectHandler = void 0;
26932
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26397
26933
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26398
26934
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
26399
26935
  class AuthCodeRedirectHandler {
@@ -26457,7 +26993,7 @@ class AuthCodeRedirectHandler {
26457
26993
  tokenRefresher: this.tokerRefresher,
26458
26994
  };
26459
26995
  }
26460
- const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(fetch, tokens.accessToken, {
26996
+ const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(universal_fetch_1.fetch, tokens.accessToken, {
26461
26997
  dpopKey: tokens.dpopKey,
26462
26998
  refreshOptions,
26463
26999
  eventEmitter,
@@ -26695,11 +27231,12 @@ exports.SessionInfoManager = exports.clear = exports.getUnauthenticatedSession =
26695
27231
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26696
27232
  const uuid_1 = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-browser/node_modules/uuid/dist/commonjs-browser/index.js");
26697
27233
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
27234
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26698
27235
  function getUnauthenticatedSession() {
26699
27236
  return {
26700
27237
  isLoggedIn: false,
26701
27238
  sessionId: (0, uuid_1.v4)(),
26702
- fetch,
27239
+ fetch: universal_fetch_1.fetch,
26703
27240
  };
26704
27241
  }
26705
27242
  exports.getUnauthenticatedSession = getUnauthenticatedSession;
@@ -27852,513 +28389,513 @@ exports["default"] = _default;
27852
28389
 
27853
28390
 
27854
28391
  var events = __webpack_require__(/*! events */ "./node_modules/events/events.js");
27855
- var crossFetch = __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js");
28392
+ var universalFetch = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
27856
28393
  var jose = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
27857
28394
  var uuid = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-core/node_modules/uuid/dist/commonjs-browser/index.js");
27858
28395
 
27859
- const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
27860
- const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
27861
- const EVENTS = {
27862
- ERROR: "error",
27863
- LOGIN: "login",
27864
- LOGOUT: "logout",
27865
- NEW_REFRESH_TOKEN: "newRefreshToken",
27866
- SESSION_EXPIRED: "sessionExpired",
27867
- SESSION_EXTENDED: "sessionExtended",
27868
- SESSION_RESTORED: "sessionRestore",
27869
- TIMEOUT_SET: "timeoutSet",
27870
- };
27871
- const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
27872
- const SCOPE_OPENID = "openid";
27873
- const SCOPE_OFFLINE = "offline_access";
27874
- const SCOPE_WEBID = "webid";
28396
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
28397
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
28398
+ const EVENTS = {
28399
+ ERROR: "error",
28400
+ LOGIN: "login",
28401
+ LOGOUT: "logout",
28402
+ NEW_REFRESH_TOKEN: "newRefreshToken",
28403
+ SESSION_EXPIRED: "sessionExpired",
28404
+ SESSION_EXTENDED: "sessionExtended",
28405
+ SESSION_RESTORED: "sessionRestore",
28406
+ TIMEOUT_SET: "timeoutSet",
28407
+ };
28408
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
28409
+ const SCOPE_OPENID = "openid";
28410
+ const SCOPE_OFFLINE = "offline_access";
28411
+ const SCOPE_WEBID = "webid";
27875
28412
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
27876
28413
 
27877
- const buildProxyHandler = (toExclude, errorMessage) => ({
27878
- get(target, prop, receiver) {
27879
- if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&
27880
- Object.getOwnPropertyNames(toExclude).includes(prop)) {
27881
- throw new Error(`${errorMessage}: [${prop}] is not supported`);
27882
- }
27883
- return Reflect.get(target, prop, receiver);
27884
- },
28414
+ const buildProxyHandler = (toExclude, errorMessage) => ({
28415
+ get(target, prop, receiver) {
28416
+ if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&
28417
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
28418
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
28419
+ }
28420
+ return Reflect.get(target, prop, receiver);
28421
+ },
27885
28422
  });
27886
28423
 
27887
- class AggregateHandler {
27888
- constructor(handleables) {
27889
- this.handleables = handleables;
27890
- }
27891
- async getProperHandler(params) {
27892
- const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
27893
- for (let i = 0; i < canHandleList.length; i += 1) {
27894
- if (canHandleList[i]) {
27895
- return this.handleables[i];
27896
- }
27897
- }
27898
- return null;
27899
- }
27900
- async canHandle(...params) {
27901
- return (await this.getProperHandler(params)) !== null;
27902
- }
27903
- async handle(...params) {
27904
- const handler = await this.getProperHandler(params);
27905
- if (handler) {
27906
- return handler.handle(...params);
27907
- }
27908
- throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
27909
- .map((param) => {
27910
- try {
27911
- return JSON.stringify(param);
27912
- }
27913
- catch (err) {
27914
- return param.toString();
27915
- }
27916
- })
27917
- .join(", ")}`);
27918
- }
28424
+ class AggregateHandler {
28425
+ constructor(handleables) {
28426
+ this.handleables = handleables;
28427
+ }
28428
+ async getProperHandler(params) {
28429
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
28430
+ for (let i = 0; i < canHandleList.length; i += 1) {
28431
+ if (canHandleList[i]) {
28432
+ return this.handleables[i];
28433
+ }
28434
+ }
28435
+ return null;
28436
+ }
28437
+ async canHandle(...params) {
28438
+ return (await this.getProperHandler(params)) !== null;
28439
+ }
28440
+ async handle(...params) {
28441
+ const handler = await this.getProperHandler(params);
28442
+ if (handler) {
28443
+ return handler.handle(...params);
28444
+ }
28445
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
28446
+ .map((param) => {
28447
+ try {
28448
+ return JSON.stringify(param);
28449
+ }
28450
+ catch (err) {
28451
+ return param.toString();
28452
+ }
28453
+ })
28454
+ .join(", ")}`);
28455
+ }
27919
28456
  }
27920
28457
 
27921
- async function fetchJwks(jwksIri, issuerIri) {
27922
- const jwksResponse = await crossFetch.fetch(jwksIri);
27923
- if (jwksResponse.status !== 200) {
27924
- throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
27925
- }
27926
- let jwk;
27927
- try {
27928
- jwk = (await jwksResponse.json()).keys[0];
27929
- }
27930
- catch (e) {
27931
- throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
27932
- }
27933
- return jwk;
27934
- }
27935
- async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
27936
- const jwk = await fetchJwks(jwksIri, issuerIri);
27937
- let payload;
27938
- try {
27939
- const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {
27940
- issuer: issuerIri,
27941
- audience: clientId,
27942
- });
27943
- payload = verifiedPayload;
27944
- }
27945
- catch (e) {
27946
- throw new Error(`Token verification failed: ${e.stack}`);
27947
- }
27948
- if (typeof payload.webid === "string") {
27949
- return payload.webid;
27950
- }
27951
- if (typeof payload.sub !== "string") {
27952
- throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
27953
- }
27954
- try {
27955
- new URL(payload.sub);
27956
- return payload.sub;
27957
- }
27958
- catch (e) {
27959
- throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
27960
- }
28458
+ async function fetchJwks(jwksIri, issuerIri) {
28459
+ const jwksResponse = await universalFetch.fetch(jwksIri);
28460
+ if (jwksResponse.status !== 200) {
28461
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
28462
+ }
28463
+ let jwk;
28464
+ try {
28465
+ jwk = (await jwksResponse.json()).keys[0];
28466
+ }
28467
+ catch (e) {
28468
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
28469
+ }
28470
+ return jwk;
28471
+ }
28472
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
28473
+ const jwk = await fetchJwks(jwksIri, issuerIri);
28474
+ let payload;
28475
+ try {
28476
+ const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {
28477
+ issuer: issuerIri,
28478
+ audience: clientId,
28479
+ });
28480
+ payload = verifiedPayload;
28481
+ }
28482
+ catch (e) {
28483
+ throw new Error(`Token verification failed: ${e.stack}`);
28484
+ }
28485
+ if (typeof payload.webid === "string") {
28486
+ return payload.webid;
28487
+ }
28488
+ if (typeof payload.sub !== "string") {
28489
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
28490
+ }
28491
+ try {
28492
+ new URL(payload.sub);
28493
+ return payload.sub;
28494
+ }
28495
+ catch (e) {
28496
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
28497
+ }
27961
28498
  }
27962
28499
 
27963
- function isValidRedirectUrl(redirectUrl) {
27964
- try {
27965
- const urlObject = new URL(redirectUrl);
27966
- return urlObject.hash === "";
27967
- }
27968
- catch (e) {
27969
- return false;
27970
- }
28500
+ function isValidRedirectUrl(redirectUrl) {
28501
+ try {
28502
+ const urlObject = new URL(redirectUrl);
28503
+ return urlObject.hash === "";
28504
+ }
28505
+ catch (e) {
28506
+ return false;
28507
+ }
27971
28508
  }
27972
28509
 
27973
- function isSupportedTokenType(token) {
27974
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
28510
+ function isSupportedTokenType(token) {
28511
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
27975
28512
  }
27976
28513
 
27977
28514
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
27978
28515
 
27979
- function isValidUrl(url) {
27980
- try {
27981
- new URL(url);
27982
- return true;
27983
- }
27984
- catch (_a) {
27985
- return false;
27986
- }
27987
- }
27988
- function determineSigningAlg(supported, preferred) {
27989
- var _a;
27990
- return ((_a = preferred.find((signingAlg) => {
27991
- return supported.includes(signingAlg);
27992
- })) !== null && _a !== void 0 ? _a : null);
27993
- }
27994
- function determineClientType(options, issuerConfig) {
27995
- if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
27996
- return "static";
27997
- }
27998
- if (issuerConfig.scopesSupported.includes("webid") &&
27999
- options.clientId !== undefined &&
28000
- isValidUrl(options.clientId)) {
28001
- return "solid-oidc";
28002
- }
28003
- return "dynamic";
28004
- }
28005
- async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
28006
- const clientType = determineClientType(options, issuerConfig);
28007
- if (clientType === "dynamic") {
28008
- return clientRegistrar.getClient({
28009
- sessionId: options.sessionId,
28010
- clientName: options.clientName,
28011
- redirectUrl: options.redirectUrl,
28012
- }, issuerConfig);
28013
- }
28014
- await storageUtility.setForUser(options.sessionId, {
28015
- clientId: options.clientId,
28016
- });
28017
- if (options.clientSecret) {
28018
- await storageUtility.setForUser(options.sessionId, {
28019
- clientSecret: options.clientSecret,
28020
- });
28021
- }
28022
- if (options.clientName) {
28023
- await storageUtility.setForUser(options.sessionId, {
28024
- clientName: options.clientName,
28025
- });
28026
- }
28027
- return {
28028
- clientId: options.clientId,
28029
- clientSecret: options.clientSecret,
28030
- clientName: options.clientName,
28031
- clientType,
28032
- };
28516
+ function isValidUrl(url) {
28517
+ try {
28518
+ new URL(url);
28519
+ return true;
28520
+ }
28521
+ catch (_a) {
28522
+ return false;
28523
+ }
28524
+ }
28525
+ function determineSigningAlg(supported, preferred) {
28526
+ var _a;
28527
+ return ((_a = preferred.find((signingAlg) => {
28528
+ return supported.includes(signingAlg);
28529
+ })) !== null && _a !== void 0 ? _a : null);
28530
+ }
28531
+ function determineClientType(options, issuerConfig) {
28532
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
28533
+ return "static";
28534
+ }
28535
+ if (issuerConfig.scopesSupported.includes("webid") &&
28536
+ options.clientId !== undefined &&
28537
+ isValidUrl(options.clientId)) {
28538
+ return "solid-oidc";
28539
+ }
28540
+ return "dynamic";
28541
+ }
28542
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
28543
+ const clientType = determineClientType(options, issuerConfig);
28544
+ if (clientType === "dynamic") {
28545
+ return clientRegistrar.getClient({
28546
+ sessionId: options.sessionId,
28547
+ clientName: options.clientName,
28548
+ redirectUrl: options.redirectUrl,
28549
+ }, issuerConfig);
28550
+ }
28551
+ await storageUtility.setForUser(options.sessionId, {
28552
+ clientId: options.clientId,
28553
+ });
28554
+ if (options.clientSecret) {
28555
+ await storageUtility.setForUser(options.sessionId, {
28556
+ clientSecret: options.clientSecret,
28557
+ });
28558
+ }
28559
+ if (options.clientName) {
28560
+ await storageUtility.setForUser(options.sessionId, {
28561
+ clientName: options.clientName,
28562
+ });
28563
+ }
28564
+ return {
28565
+ clientId: options.clientId,
28566
+ clientSecret: options.clientSecret,
28567
+ clientName: options.clientName,
28568
+ clientType,
28569
+ };
28033
28570
  }
28034
28571
 
28035
- async function getSessionIdFromOauthState(storageUtility, oauthState) {
28036
- return storageUtility.getForUser(oauthState, "sessionId");
28037
- }
28038
- async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
28039
- try {
28040
- const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
28041
- storageUtility.getForUser(sessionId, "issuer", {
28042
- errorIfNull: true,
28043
- }),
28044
- storageUtility.getForUser(sessionId, "codeVerifier"),
28045
- storageUtility.getForUser(sessionId, "redirectUrl"),
28046
- storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
28047
- ]);
28048
- await storageUtility.deleteForUser(sessionId, "codeVerifier");
28049
- const issuerConfig = await configFetcher.fetchConfig(issuerIri);
28050
- return {
28051
- codeVerifier,
28052
- redirectUrl: storedRedirectIri,
28053
- issuerConfig,
28054
- dpop: dpop === "true",
28055
- };
28056
- }
28057
- catch (e) {
28058
- throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
28059
- }
28060
- }
28061
- async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
28062
- if (refreshToken !== undefined) {
28063
- await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
28064
- }
28065
- if (webId !== undefined) {
28066
- await storageUtility.setForUser(sessionId, { webId }, { secure });
28067
- }
28068
- if (isLoggedIn !== undefined) {
28069
- await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
28070
- }
28071
- if (dpopKey !== undefined) {
28072
- await storageUtility.setForUser(sessionId, {
28073
- publicKey: JSON.stringify(dpopKey.publicKey),
28074
- privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),
28075
- }, { secure });
28076
- }
28077
- }
28078
- class StorageUtility {
28079
- constructor(secureStorage, insecureStorage) {
28080
- this.secureStorage = secureStorage;
28081
- this.insecureStorage = insecureStorage;
28082
- }
28083
- getKey(userId) {
28084
- return `solidClientAuthenticationUser:${userId}`;
28085
- }
28086
- async getUserData(userId, secure) {
28087
- const stored = await (secure
28088
- ? this.secureStorage
28089
- : this.insecureStorage).get(this.getKey(userId));
28090
- if (stored === undefined) {
28091
- return {};
28092
- }
28093
- try {
28094
- return JSON.parse(stored);
28095
- }
28096
- catch (err) {
28097
- throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
28098
- }
28099
- }
28100
- async setUserData(userId, data, secure) {
28101
- await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
28102
- }
28103
- async get(key, options) {
28104
- const value = await ((options === null || options === void 0 ? void 0 : options.secure)
28105
- ? this.secureStorage
28106
- : this.insecureStorage).get(key);
28107
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28108
- throw new Error(`[${key}] is not stored`);
28109
- }
28110
- return value;
28111
- }
28112
- async set(key, value, options) {
28113
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
28114
- }
28115
- async delete(key, options) {
28116
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
28117
- }
28118
- async getForUser(userId, key, options) {
28119
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28120
- let value;
28121
- if (!userData || !userData[key]) {
28122
- value = undefined;
28123
- }
28124
- value = userData[key];
28125
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28126
- throw new Error(`Field [${key}] for user [${userId}] is not stored`);
28127
- }
28128
- return value || undefined;
28129
- }
28130
- async setForUser(userId, values, options) {
28131
- let userData;
28132
- try {
28133
- userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28134
- }
28135
- catch (_a) {
28136
- userData = {};
28137
- }
28138
- await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
28139
- }
28140
- async deleteForUser(userId, key, options) {
28141
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28142
- delete userData[key];
28143
- await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
28144
- }
28145
- async deleteAllUserData(userId, options) {
28146
- await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
28147
- }
28572
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
28573
+ return storageUtility.getForUser(oauthState, "sessionId");
28574
+ }
28575
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
28576
+ try {
28577
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
28578
+ storageUtility.getForUser(sessionId, "issuer", {
28579
+ errorIfNull: true,
28580
+ }),
28581
+ storageUtility.getForUser(sessionId, "codeVerifier"),
28582
+ storageUtility.getForUser(sessionId, "redirectUrl"),
28583
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
28584
+ ]);
28585
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
28586
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
28587
+ return {
28588
+ codeVerifier,
28589
+ redirectUrl: storedRedirectIri,
28590
+ issuerConfig,
28591
+ dpop: dpop === "true",
28592
+ };
28593
+ }
28594
+ catch (e) {
28595
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
28596
+ }
28597
+ }
28598
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
28599
+ if (refreshToken !== undefined) {
28600
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
28601
+ }
28602
+ if (webId !== undefined) {
28603
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
28604
+ }
28605
+ if (isLoggedIn !== undefined) {
28606
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
28607
+ }
28608
+ if (dpopKey !== undefined) {
28609
+ await storageUtility.setForUser(sessionId, {
28610
+ publicKey: JSON.stringify(dpopKey.publicKey),
28611
+ privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),
28612
+ }, { secure });
28613
+ }
28614
+ }
28615
+ class StorageUtility {
28616
+ constructor(secureStorage, insecureStorage) {
28617
+ this.secureStorage = secureStorage;
28618
+ this.insecureStorage = insecureStorage;
28619
+ }
28620
+ getKey(userId) {
28621
+ return `solidClientAuthenticationUser:${userId}`;
28622
+ }
28623
+ async getUserData(userId, secure) {
28624
+ const stored = await (secure
28625
+ ? this.secureStorage
28626
+ : this.insecureStorage).get(this.getKey(userId));
28627
+ if (stored === undefined) {
28628
+ return {};
28629
+ }
28630
+ try {
28631
+ return JSON.parse(stored);
28632
+ }
28633
+ catch (err) {
28634
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
28635
+ }
28636
+ }
28637
+ async setUserData(userId, data, secure) {
28638
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
28639
+ }
28640
+ async get(key, options) {
28641
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
28642
+ ? this.secureStorage
28643
+ : this.insecureStorage).get(key);
28644
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28645
+ throw new Error(`[${key}] is not stored`);
28646
+ }
28647
+ return value;
28648
+ }
28649
+ async set(key, value, options) {
28650
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
28651
+ }
28652
+ async delete(key, options) {
28653
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
28654
+ }
28655
+ async getForUser(userId, key, options) {
28656
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28657
+ let value;
28658
+ if (!userData || !userData[key]) {
28659
+ value = undefined;
28660
+ }
28661
+ value = userData[key];
28662
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28663
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
28664
+ }
28665
+ return value || undefined;
28666
+ }
28667
+ async setForUser(userId, values, options) {
28668
+ let userData;
28669
+ try {
28670
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28671
+ }
28672
+ catch (_a) {
28673
+ userData = {};
28674
+ }
28675
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
28676
+ }
28677
+ async deleteForUser(userId, key, options) {
28678
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28679
+ delete userData[key];
28680
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
28681
+ }
28682
+ async deleteAllUserData(userId, options) {
28683
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
28684
+ }
28148
28685
  }
28149
28686
 
28150
- class InMemoryStorage {
28151
- constructor() {
28152
- this.map = {};
28153
- }
28154
- async get(key) {
28155
- return this.map[key] || undefined;
28156
- }
28157
- async set(key, value) {
28158
- this.map[key] = value;
28159
- }
28160
- async delete(key) {
28161
- delete this.map[key];
28162
- }
28687
+ class InMemoryStorage {
28688
+ constructor() {
28689
+ this.map = {};
28690
+ }
28691
+ async get(key) {
28692
+ return this.map[key] || undefined;
28693
+ }
28694
+ async set(key, value) {
28695
+ this.map[key] = value;
28696
+ }
28697
+ async delete(key) {
28698
+ delete this.map[key];
28699
+ }
28163
28700
  }
28164
28701
 
28165
- class ConfigurationError extends Error {
28166
- constructor(message) {
28167
- super(message);
28168
- }
28702
+ class ConfigurationError extends Error {
28703
+ constructor(message) {
28704
+ super(message);
28705
+ }
28169
28706
  }
28170
28707
 
28171
- class NotImplementedError extends Error {
28172
- constructor(methodName) {
28173
- super(`[${methodName}] is not implemented`);
28174
- }
28708
+ class NotImplementedError extends Error {
28709
+ constructor(methodName) {
28710
+ super(`[${methodName}] is not implemented`);
28711
+ }
28175
28712
  }
28176
28713
 
28177
- class InvalidResponseError extends Error {
28178
- constructor(missingFields) {
28179
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28180
- this.missingFields = missingFields;
28181
- }
28714
+ class InvalidResponseError extends Error {
28715
+ constructor(missingFields) {
28716
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28717
+ this.missingFields = missingFields;
28718
+ }
28182
28719
  }
28183
28720
 
28184
- class OidcProviderError extends Error {
28185
- constructor(message, error, errorDescription) {
28186
- super(message);
28187
- this.error = error;
28188
- this.errorDescription = errorDescription;
28189
- }
28721
+ class OidcProviderError extends Error {
28722
+ constructor(message, error, errorDescription) {
28723
+ super(message);
28724
+ this.error = error;
28725
+ this.errorDescription = errorDescription;
28726
+ }
28190
28727
  }
28191
28728
 
28192
- function normalizeHTU(audience) {
28193
- const audienceUrl = new URL(audience);
28194
- return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
28195
- }
28196
- async function createDpopHeader(audience, method, dpopKey) {
28197
- return new jose.SignJWT({
28198
- htu: normalizeHTU(audience),
28199
- htm: method.toUpperCase(),
28200
- jti: uuid.v4(),
28201
- })
28202
- .setProtectedHeader({
28203
- alg: PREFERRED_SIGNING_ALG[0],
28204
- jwk: dpopKey.publicKey,
28205
- typ: "dpop+jwt",
28206
- })
28207
- .setIssuedAt()
28208
- .sign(dpopKey.privateKey, {});
28209
- }
28210
- async function generateDpopKeyPair() {
28211
- const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);
28212
- const dpopKeyPair = {
28213
- privateKey,
28214
- publicKey: await jose.exportJWK(publicKey),
28215
- };
28216
- [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
28217
- return dpopKeyPair;
28729
+ function normalizeHTU(audience) {
28730
+ const audienceUrl = new URL(audience);
28731
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
28732
+ }
28733
+ async function createDpopHeader(audience, method, dpopKey) {
28734
+ return new jose.SignJWT({
28735
+ htu: normalizeHTU(audience),
28736
+ htm: method.toUpperCase(),
28737
+ jti: uuid.v4(),
28738
+ })
28739
+ .setProtectedHeader({
28740
+ alg: PREFERRED_SIGNING_ALG[0],
28741
+ jwk: dpopKey.publicKey,
28742
+ typ: "dpop+jwt",
28743
+ })
28744
+ .setIssuedAt()
28745
+ .sign(dpopKey.privateKey, {});
28746
+ }
28747
+ async function generateDpopKeyPair() {
28748
+ const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);
28749
+ const dpopKeyPair = {
28750
+ privateKey,
28751
+ publicKey: await jose.exportJWK(publicKey),
28752
+ };
28753
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
28754
+ return dpopKeyPair;
28218
28755
  }
28219
28756
 
28220
- const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
28221
- function isExpectedAuthError(statusCode) {
28222
- return [401, 403].includes(statusCode);
28223
- }
28224
- async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
28225
- var _a;
28226
- const headers = new crossFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28227
- headers.set("Authorization", `DPoP ${authToken}`);
28228
- headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
28229
- return {
28230
- ...defaultOptions,
28231
- headers,
28232
- };
28233
- }
28234
- async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
28235
- if (dpopKey !== undefined) {
28236
- return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
28237
- }
28238
- const headers = new crossFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28239
- headers.set("Authorization", `Bearer ${authToken}`);
28240
- return {
28241
- ...defaultOptions,
28242
- headers,
28243
- };
28244
- }
28245
- async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
28246
- return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
28247
- }
28248
- async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
28249
- var _a;
28250
- const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
28251
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
28252
- if (typeof tokenSet.refreshToken === "string") {
28253
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
28254
- }
28255
- return {
28256
- accessToken: tokenSet.accessToken,
28257
- refreshToken: tokenSet.refreshToken,
28258
- expiresIn: tokenSet.expiresIn,
28259
- };
28260
- }
28261
- const computeRefreshDelay = (expiresIn) => {
28262
- if (expiresIn !== undefined) {
28263
- return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
28264
- ?
28265
- expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
28266
- : expiresIn;
28267
- }
28268
- return DEFAULT_EXPIRATION_TIME_SECONDS;
28269
- };
28270
- async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
28271
- var _a;
28272
- let currentAccessToken = accessToken;
28273
- let latestTimeout;
28274
- const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
28275
- if (currentRefreshOptions !== undefined) {
28276
- const proactivelyRefreshToken = async () => {
28277
- var _a, _b, _c, _d;
28278
- try {
28279
- const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
28280
- currentAccessToken = refreshedAccessToken;
28281
- if (refreshToken !== undefined) {
28282
- currentRefreshOptions.refreshToken = refreshToken;
28283
- }
28284
- clearTimeout(latestTimeout);
28285
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
28286
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28287
- }
28288
- catch (e) {
28289
- if (e instanceof OidcProviderError) {
28290
- (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
28291
- (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
28292
- }
28293
- if (e instanceof InvalidResponseError &&
28294
- e.missingFields.includes("access_token")) {
28295
- (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
28296
- }
28297
- }
28298
- };
28299
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
28300
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28301
- }
28302
- else if (options !== undefined && options.eventEmitter !== undefined) {
28303
- const expirationTimeout = setTimeout(() => {
28304
- options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
28305
- }, computeRefreshDelay(options.expiresIn) * 1000);
28306
- options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
28307
- }
28308
- return async (url, requestInit) => {
28309
- let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
28310
- const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
28311
- if (response.ok || failedButNotExpectedAuthError) {
28312
- return response;
28313
- }
28314
- const hasBeenRedirected = response.url !== url;
28315
- if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
28316
- response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
28317
- }
28318
- return response;
28319
- };
28757
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
28758
+ function isExpectedAuthError(statusCode) {
28759
+ return [401, 403].includes(statusCode);
28760
+ }
28761
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
28762
+ var _a;
28763
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28764
+ headers.set("Authorization", `DPoP ${authToken}`);
28765
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
28766
+ return {
28767
+ ...defaultOptions,
28768
+ headers,
28769
+ };
28770
+ }
28771
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
28772
+ if (dpopKey !== undefined) {
28773
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
28774
+ }
28775
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28776
+ headers.set("Authorization", `Bearer ${authToken}`);
28777
+ return {
28778
+ ...defaultOptions,
28779
+ headers,
28780
+ };
28781
+ }
28782
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
28783
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
28784
+ }
28785
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
28786
+ var _a;
28787
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
28788
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
28789
+ if (typeof tokenSet.refreshToken === "string") {
28790
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
28791
+ }
28792
+ return {
28793
+ accessToken: tokenSet.accessToken,
28794
+ refreshToken: tokenSet.refreshToken,
28795
+ expiresIn: tokenSet.expiresIn,
28796
+ };
28797
+ }
28798
+ const computeRefreshDelay = (expiresIn) => {
28799
+ if (expiresIn !== undefined) {
28800
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
28801
+ ?
28802
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
28803
+ : expiresIn;
28804
+ }
28805
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
28806
+ };
28807
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
28808
+ var _a;
28809
+ let currentAccessToken = accessToken;
28810
+ let latestTimeout;
28811
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
28812
+ if (currentRefreshOptions !== undefined) {
28813
+ const proactivelyRefreshToken = async () => {
28814
+ var _a, _b, _c, _d;
28815
+ try {
28816
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
28817
+ currentAccessToken = refreshedAccessToken;
28818
+ if (refreshToken !== undefined) {
28819
+ currentRefreshOptions.refreshToken = refreshToken;
28820
+ }
28821
+ clearTimeout(latestTimeout);
28822
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
28823
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28824
+ }
28825
+ catch (e) {
28826
+ if (e instanceof OidcProviderError) {
28827
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
28828
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
28829
+ }
28830
+ if (e instanceof InvalidResponseError &&
28831
+ e.missingFields.includes("access_token")) {
28832
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
28833
+ }
28834
+ }
28835
+ };
28836
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
28837
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28838
+ }
28839
+ else if (options !== undefined && options.eventEmitter !== undefined) {
28840
+ const expirationTimeout = setTimeout(() => {
28841
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
28842
+ }, computeRefreshDelay(options.expiresIn) * 1000);
28843
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
28844
+ }
28845
+ return async (url, requestInit) => {
28846
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
28847
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
28848
+ if (response.ok || failedButNotExpectedAuthError) {
28849
+ return response;
28850
+ }
28851
+ const hasBeenRedirected = response.url !== url;
28852
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
28853
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
28854
+ }
28855
+ return response;
28856
+ };
28320
28857
  }
28321
28858
 
28322
- const StorageUtilityGetResponse = "getResponse";
28323
- const StorageUtilityMock = {
28324
- get: async (key, options) => StorageUtilityGetResponse,
28325
- set: async (key, value) => {
28326
- },
28327
- delete: async (key) => {
28328
- },
28329
- getForUser: async (userId, key, options) => StorageUtilityGetResponse,
28330
- setForUser: async (userId, values, options) => {
28331
- },
28332
- deleteForUser: async (userId, key, options) => {
28333
- },
28334
- deleteAllUserData: async (userId, options) => {
28335
- },
28336
- };
28337
- const mockStorage = (stored) => {
28338
- const store = stored;
28339
- return {
28340
- get: async (key) => {
28341
- if (store[key] === undefined) {
28342
- return undefined;
28343
- }
28344
- if (typeof store[key] === "string") {
28345
- return store[key];
28346
- }
28347
- return JSON.stringify(store[key]);
28348
- },
28349
- set: async (key, value) => {
28350
- store[key] = value;
28351
- },
28352
- delete: async (key) => {
28353
- delete store[key];
28354
- },
28355
- };
28356
- };
28357
- const mockStorageUtility = (stored, isSecure = false) => {
28358
- if (isSecure) {
28359
- return new StorageUtility(mockStorage(stored), mockStorage({}));
28360
- }
28361
- return new StorageUtility(mockStorage({}), mockStorage(stored));
28859
+ const StorageUtilityGetResponse = "getResponse";
28860
+ const StorageUtilityMock = {
28861
+ get: async (key, options) => StorageUtilityGetResponse,
28862
+ set: async (key, value) => {
28863
+ },
28864
+ delete: async (key) => {
28865
+ },
28866
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
28867
+ setForUser: async (userId, values, options) => {
28868
+ },
28869
+ deleteForUser: async (userId, key, options) => {
28870
+ },
28871
+ deleteAllUserData: async (userId, options) => {
28872
+ },
28873
+ };
28874
+ const mockStorage = (stored) => {
28875
+ const store = stored;
28876
+ return {
28877
+ get: async (key) => {
28878
+ if (store[key] === undefined) {
28879
+ return undefined;
28880
+ }
28881
+ if (typeof store[key] === "string") {
28882
+ return store[key];
28883
+ }
28884
+ return JSON.stringify(store[key]);
28885
+ },
28886
+ set: async (key, value) => {
28887
+ store[key] = value;
28888
+ },
28889
+ delete: async (key) => {
28890
+ delete store[key];
28891
+ },
28892
+ };
28893
+ };
28894
+ const mockStorageUtility = (stored, isSecure = false) => {
28895
+ if (isSecure) {
28896
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
28897
+ }
28898
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
28362
28899
  };
28363
28900
 
28364
28901
  exports.AggregateHandler = AggregateHandler;
@@ -29582,6 +30119,29 @@ function validate(uuid) {
29582
30119
 
29583
30120
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validate);
29584
30121
 
30122
+ /***/ }),
30123
+
30124
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js":
30125
+ /*!********************************************************************!*\
30126
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.js ***!
30127
+ \********************************************************************/
30128
+ /***/ ((__unused_webpack_module, exports) => {
30129
+
30130
+ "use strict";
30131
+
30132
+
30133
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
30134
+
30135
+ var indexBrowser = globalThis.fetch;
30136
+ const { fetch, Response, Request, Headers } = globalThis;
30137
+
30138
+ exports.Headers = Headers;
30139
+ exports.Request = Request;
30140
+ exports.Response = Response;
30141
+ exports["default"] = indexBrowser;
30142
+ exports.fetch = fetch;
30143
+
30144
+
29585
30145
  /***/ }),
29586
30146
 
29587
30147
  /***/ "./node_modules/@noble/curves/_shortw_utils.js":
@@ -60226,522 +60786,545 @@ __webpack_require__.r(__webpack_exports__);
60226
60786
  /* harmony export */ "saveSessionInfoToStorage": () => (/* binding */ saveSessionInfoToStorage)
60227
60787
  /* harmony export */ });
60228
60788
  /* harmony import */ var events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js");
60229
- /* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js");
60230
- /* harmony import */ var jose__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
60789
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
60790
+ /* harmony import */ var jose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
60231
60791
  /* 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");
60232
60792
 
60233
60793
 
60234
60794
 
60235
60795
 
60236
60796
 
60237
- const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
60238
- const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
60239
- const EVENTS = {
60240
- ERROR: "error",
60241
- LOGIN: "login",
60242
- LOGOUT: "logout",
60243
- NEW_REFRESH_TOKEN: "newRefreshToken",
60244
- SESSION_EXPIRED: "sessionExpired",
60245
- SESSION_EXTENDED: "sessionExtended",
60246
- SESSION_RESTORED: "sessionRestore",
60247
- TIMEOUT_SET: "timeoutSet",
60248
- };
60249
- const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
60250
- const SCOPE_OPENID = "openid";
60251
- const SCOPE_OFFLINE = "offline_access";
60252
- const SCOPE_WEBID = "webid";
60797
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
60798
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
60799
+ const EVENTS = {
60800
+ ERROR: "error",
60801
+ LOGIN: "login",
60802
+ LOGOUT: "logout",
60803
+ NEW_REFRESH_TOKEN: "newRefreshToken",
60804
+ SESSION_EXPIRED: "sessionExpired",
60805
+ SESSION_EXTENDED: "sessionExtended",
60806
+ SESSION_RESTORED: "sessionRestore",
60807
+ TIMEOUT_SET: "timeoutSet",
60808
+ };
60809
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
60810
+ const SCOPE_OPENID = "openid";
60811
+ const SCOPE_OFFLINE = "offline_access";
60812
+ const SCOPE_WEBID = "webid";
60253
60813
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
60254
60814
 
60255
- const buildProxyHandler = (toExclude, errorMessage) => ({
60256
- get(target, prop, receiver) {
60257
- if (!Object.getOwnPropertyNames(events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter).includes(prop) &&
60258
- Object.getOwnPropertyNames(toExclude).includes(prop)) {
60259
- throw new Error(`${errorMessage}: [${prop}] is not supported`);
60260
- }
60261
- return Reflect.get(target, prop, receiver);
60262
- },
60815
+ const buildProxyHandler = (toExclude, errorMessage) => ({
60816
+ get(target, prop, receiver) {
60817
+ if (!Object.getOwnPropertyNames(events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter).includes(prop) &&
60818
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
60819
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
60820
+ }
60821
+ return Reflect.get(target, prop, receiver);
60822
+ },
60263
60823
  });
60264
60824
 
60265
- class AggregateHandler {
60266
- constructor(handleables) {
60267
- this.handleables = handleables;
60268
- }
60269
- async getProperHandler(params) {
60270
- const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
60271
- for (let i = 0; i < canHandleList.length; i += 1) {
60272
- if (canHandleList[i]) {
60273
- return this.handleables[i];
60274
- }
60275
- }
60276
- return null;
60277
- }
60278
- async canHandle(...params) {
60279
- return (await this.getProperHandler(params)) !== null;
60280
- }
60281
- async handle(...params) {
60282
- const handler = await this.getProperHandler(params);
60283
- if (handler) {
60284
- return handler.handle(...params);
60285
- }
60286
- throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
60287
- .map((param) => {
60288
- try {
60289
- return JSON.stringify(param);
60290
- }
60291
- catch (err) {
60292
- return param.toString();
60293
- }
60294
- })
60295
- .join(", ")}`);
60296
- }
60825
+ class AggregateHandler {
60826
+ constructor(handleables) {
60827
+ this.handleables = handleables;
60828
+ }
60829
+ async getProperHandler(params) {
60830
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
60831
+ for (let i = 0; i < canHandleList.length; i += 1) {
60832
+ if (canHandleList[i]) {
60833
+ return this.handleables[i];
60834
+ }
60835
+ }
60836
+ return null;
60837
+ }
60838
+ async canHandle(...params) {
60839
+ return (await this.getProperHandler(params)) !== null;
60840
+ }
60841
+ async handle(...params) {
60842
+ const handler = await this.getProperHandler(params);
60843
+ if (handler) {
60844
+ return handler.handle(...params);
60845
+ }
60846
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
60847
+ .map((param) => {
60848
+ try {
60849
+ return JSON.stringify(param);
60850
+ }
60851
+ catch (err) {
60852
+ return param.toString();
60853
+ }
60854
+ })
60855
+ .join(", ")}`);
60856
+ }
60297
60857
  }
60298
60858
 
60299
- async function fetchJwks(jwksIri, issuerIri) {
60300
- const jwksResponse = await (0,cross_fetch__WEBPACK_IMPORTED_MODULE_1__.fetch)(jwksIri);
60301
- if (jwksResponse.status !== 200) {
60302
- throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
60303
- }
60304
- let jwk;
60305
- try {
60306
- jwk = (await jwksResponse.json()).keys[0];
60307
- }
60308
- catch (e) {
60309
- throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
60310
- }
60311
- return jwk;
60312
- }
60313
- async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
60314
- const jwk = await fetchJwks(jwksIri, issuerIri);
60315
- let payload;
60316
- try {
60317
- const { payload: verifiedPayload } = await (0,jose__WEBPACK_IMPORTED_MODULE_2__.jwtVerify)(idToken, await (0,jose__WEBPACK_IMPORTED_MODULE_2__.importJWK)(jwk), {
60318
- issuer: issuerIri,
60319
- audience: clientId,
60320
- });
60321
- payload = verifiedPayload;
60322
- }
60323
- catch (e) {
60324
- throw new Error(`Token verification failed: ${e.stack}`);
60325
- }
60326
- if (typeof payload.webid === "string") {
60327
- return payload.webid;
60328
- }
60329
- if (typeof payload.sub !== "string") {
60330
- throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
60331
- }
60332
- try {
60333
- new URL(payload.sub);
60334
- return payload.sub;
60335
- }
60336
- catch (e) {
60337
- throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
60338
- }
60859
+ async function fetchJwks(jwksIri, issuerIri) {
60860
+ const jwksResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(jwksIri);
60861
+ if (jwksResponse.status !== 200) {
60862
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
60863
+ }
60864
+ let jwk;
60865
+ try {
60866
+ jwk = (await jwksResponse.json()).keys[0];
60867
+ }
60868
+ catch (e) {
60869
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
60870
+ }
60871
+ return jwk;
60872
+ }
60873
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
60874
+ const jwk = await fetchJwks(jwksIri, issuerIri);
60875
+ let payload;
60876
+ try {
60877
+ const { payload: verifiedPayload } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.jwtVerify)(idToken, await (0,jose__WEBPACK_IMPORTED_MODULE_1__.importJWK)(jwk), {
60878
+ issuer: issuerIri,
60879
+ audience: clientId,
60880
+ });
60881
+ payload = verifiedPayload;
60882
+ }
60883
+ catch (e) {
60884
+ throw new Error(`Token verification failed: ${e.stack}`);
60885
+ }
60886
+ if (typeof payload.webid === "string") {
60887
+ return payload.webid;
60888
+ }
60889
+ if (typeof payload.sub !== "string") {
60890
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
60891
+ }
60892
+ try {
60893
+ new URL(payload.sub);
60894
+ return payload.sub;
60895
+ }
60896
+ catch (e) {
60897
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
60898
+ }
60339
60899
  }
60340
60900
 
60341
- function isValidRedirectUrl(redirectUrl) {
60342
- try {
60343
- const urlObject = new URL(redirectUrl);
60344
- return urlObject.hash === "";
60345
- }
60346
- catch (e) {
60347
- return false;
60348
- }
60901
+ function isValidRedirectUrl(redirectUrl) {
60902
+ try {
60903
+ const urlObject = new URL(redirectUrl);
60904
+ return urlObject.hash === "";
60905
+ }
60906
+ catch (e) {
60907
+ return false;
60908
+ }
60349
60909
  }
60350
60910
 
60351
- function isSupportedTokenType(token) {
60352
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60911
+ function isSupportedTokenType(token) {
60912
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60353
60913
  }
60354
60914
 
60355
60915
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
60356
60916
 
60357
- function isValidUrl(url) {
60358
- try {
60359
- new URL(url);
60360
- return true;
60361
- }
60362
- catch (_a) {
60363
- return false;
60364
- }
60365
- }
60366
- function determineSigningAlg(supported, preferred) {
60367
- var _a;
60368
- return ((_a = preferred.find((signingAlg) => {
60369
- return supported.includes(signingAlg);
60370
- })) !== null && _a !== void 0 ? _a : null);
60371
- }
60372
- function determineClientType(options, issuerConfig) {
60373
- if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
60374
- return "static";
60375
- }
60376
- if (issuerConfig.scopesSupported.includes("webid") &&
60377
- options.clientId !== undefined &&
60378
- isValidUrl(options.clientId)) {
60379
- return "solid-oidc";
60380
- }
60381
- return "dynamic";
60382
- }
60383
- async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
60384
- const clientType = determineClientType(options, issuerConfig);
60385
- if (clientType === "dynamic") {
60386
- return clientRegistrar.getClient({
60387
- sessionId: options.sessionId,
60388
- clientName: options.clientName,
60389
- redirectUrl: options.redirectUrl,
60390
- }, issuerConfig);
60391
- }
60392
- await storageUtility.setForUser(options.sessionId, {
60393
- clientId: options.clientId,
60394
- });
60395
- if (options.clientSecret) {
60396
- await storageUtility.setForUser(options.sessionId, {
60397
- clientSecret: options.clientSecret,
60398
- });
60399
- }
60400
- if (options.clientName) {
60401
- await storageUtility.setForUser(options.sessionId, {
60402
- clientName: options.clientName,
60403
- });
60404
- }
60405
- return {
60406
- clientId: options.clientId,
60407
- clientSecret: options.clientSecret,
60408
- clientName: options.clientName,
60409
- clientType,
60410
- };
60917
+ function isValidUrl(url) {
60918
+ try {
60919
+ new URL(url);
60920
+ return true;
60921
+ }
60922
+ catch (_a) {
60923
+ return false;
60924
+ }
60925
+ }
60926
+ function determineSigningAlg(supported, preferred) {
60927
+ var _a;
60928
+ return ((_a = preferred.find((signingAlg) => {
60929
+ return supported.includes(signingAlg);
60930
+ })) !== null && _a !== void 0 ? _a : null);
60931
+ }
60932
+ function determineClientType(options, issuerConfig) {
60933
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
60934
+ return "static";
60935
+ }
60936
+ if (issuerConfig.scopesSupported.includes("webid") &&
60937
+ options.clientId !== undefined &&
60938
+ isValidUrl(options.clientId)) {
60939
+ return "solid-oidc";
60940
+ }
60941
+ return "dynamic";
60942
+ }
60943
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
60944
+ const clientType = determineClientType(options, issuerConfig);
60945
+ if (clientType === "dynamic") {
60946
+ return clientRegistrar.getClient({
60947
+ sessionId: options.sessionId,
60948
+ clientName: options.clientName,
60949
+ redirectUrl: options.redirectUrl,
60950
+ }, issuerConfig);
60951
+ }
60952
+ await storageUtility.setForUser(options.sessionId, {
60953
+ clientId: options.clientId,
60954
+ });
60955
+ if (options.clientSecret) {
60956
+ await storageUtility.setForUser(options.sessionId, {
60957
+ clientSecret: options.clientSecret,
60958
+ });
60959
+ }
60960
+ if (options.clientName) {
60961
+ await storageUtility.setForUser(options.sessionId, {
60962
+ clientName: options.clientName,
60963
+ });
60964
+ }
60965
+ return {
60966
+ clientId: options.clientId,
60967
+ clientSecret: options.clientSecret,
60968
+ clientName: options.clientName,
60969
+ clientType,
60970
+ };
60411
60971
  }
60412
60972
 
60413
- async function getSessionIdFromOauthState(storageUtility, oauthState) {
60414
- return storageUtility.getForUser(oauthState, "sessionId");
60415
- }
60416
- async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
60417
- try {
60418
- const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
60419
- storageUtility.getForUser(sessionId, "issuer", {
60420
- errorIfNull: true,
60421
- }),
60422
- storageUtility.getForUser(sessionId, "codeVerifier"),
60423
- storageUtility.getForUser(sessionId, "redirectUrl"),
60424
- storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
60425
- ]);
60426
- await storageUtility.deleteForUser(sessionId, "codeVerifier");
60427
- const issuerConfig = await configFetcher.fetchConfig(issuerIri);
60428
- return {
60429
- codeVerifier,
60430
- redirectUrl: storedRedirectIri,
60431
- issuerConfig,
60432
- dpop: dpop === "true",
60433
- };
60434
- }
60435
- catch (e) {
60436
- throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
60437
- }
60438
- }
60439
- async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
60440
- if (refreshToken !== undefined) {
60441
- await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
60442
- }
60443
- if (webId !== undefined) {
60444
- await storageUtility.setForUser(sessionId, { webId }, { secure });
60445
- }
60446
- if (isLoggedIn !== undefined) {
60447
- await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
60448
- }
60449
- if (dpopKey !== undefined) {
60450
- await storageUtility.setForUser(sessionId, {
60451
- publicKey: JSON.stringify(dpopKey.publicKey),
60452
- privateKey: JSON.stringify(await (0,jose__WEBPACK_IMPORTED_MODULE_2__.exportJWK)(dpopKey.privateKey)),
60453
- }, { secure });
60454
- }
60455
- }
60456
- class StorageUtility {
60457
- constructor(secureStorage, insecureStorage) {
60458
- this.secureStorage = secureStorage;
60459
- this.insecureStorage = insecureStorage;
60460
- }
60461
- getKey(userId) {
60462
- return `solidClientAuthenticationUser:${userId}`;
60463
- }
60464
- async getUserData(userId, secure) {
60465
- const stored = await (secure
60466
- ? this.secureStorage
60467
- : this.insecureStorage).get(this.getKey(userId));
60468
- if (stored === undefined) {
60469
- return {};
60470
- }
60471
- try {
60472
- return JSON.parse(stored);
60473
- }
60474
- catch (err) {
60475
- throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
60476
- }
60477
- }
60478
- async setUserData(userId, data, secure) {
60479
- await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
60480
- }
60481
- async get(key, options) {
60482
- const value = await ((options === null || options === void 0 ? void 0 : options.secure)
60483
- ? this.secureStorage
60484
- : this.insecureStorage).get(key);
60485
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60486
- throw new Error(`[${key}] is not stored`);
60487
- }
60488
- return value;
60489
- }
60490
- async set(key, value, options) {
60491
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
60492
- }
60493
- async delete(key, options) {
60494
- return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
60495
- }
60496
- async getForUser(userId, key, options) {
60497
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60498
- let value;
60499
- if (!userData || !userData[key]) {
60500
- value = undefined;
60501
- }
60502
- value = userData[key];
60503
- if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
60504
- throw new Error(`Field [${key}] for user [${userId}] is not stored`);
60505
- }
60506
- return value || undefined;
60507
- }
60508
- async setForUser(userId, values, options) {
60509
- let userData;
60510
- try {
60511
- userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60512
- }
60513
- catch (_a) {
60514
- userData = {};
60515
- }
60516
- await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
60517
- }
60518
- async deleteForUser(userId, key, options) {
60519
- const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
60520
- delete userData[key];
60521
- await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
60522
- }
60523
- async deleteAllUserData(userId, options) {
60524
- await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
60525
- }
60973
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
60974
+ return storageUtility.getForUser(oauthState, "sessionId");
60975
+ }
60976
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
60977
+ try {
60978
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
60979
+ storageUtility.getForUser(sessionId, "issuer", {
60980
+ errorIfNull: true,
60981
+ }),
60982
+ storageUtility.getForUser(sessionId, "codeVerifier"),
60983
+ storageUtility.getForUser(sessionId, "redirectUrl"),
60984
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
60985
+ ]);
60986
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
60987
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
60988
+ return {
60989
+ codeVerifier,
60990
+ redirectUrl: storedRedirectIri,
60991
+ issuerConfig,
60992
+ dpop: dpop === "true",
60993
+ };
60994
+ }
60995
+ catch (e) {
60996
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
60997
+ }
60998
+ }
60999
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
61000
+ if (refreshToken !== undefined) {
61001
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
61002
+ }
61003
+ if (webId !== undefined) {
61004
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
61005
+ }
61006
+ if (isLoggedIn !== undefined) {
61007
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
61008
+ }
61009
+ if (dpopKey !== undefined) {
61010
+ await storageUtility.setForUser(sessionId, {
61011
+ publicKey: JSON.stringify(dpopKey.publicKey),
61012
+ privateKey: JSON.stringify(await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(dpopKey.privateKey)),
61013
+ }, { secure });
61014
+ }
61015
+ }
61016
+ class StorageUtility {
61017
+ constructor(secureStorage, insecureStorage) {
61018
+ this.secureStorage = secureStorage;
61019
+ this.insecureStorage = insecureStorage;
61020
+ }
61021
+ getKey(userId) {
61022
+ return `solidClientAuthenticationUser:${userId}`;
61023
+ }
61024
+ async getUserData(userId, secure) {
61025
+ const stored = await (secure
61026
+ ? this.secureStorage
61027
+ : this.insecureStorage).get(this.getKey(userId));
61028
+ if (stored === undefined) {
61029
+ return {};
61030
+ }
61031
+ try {
61032
+ return JSON.parse(stored);
61033
+ }
61034
+ catch (err) {
61035
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
61036
+ }
61037
+ }
61038
+ async setUserData(userId, data, secure) {
61039
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
61040
+ }
61041
+ async get(key, options) {
61042
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
61043
+ ? this.secureStorage
61044
+ : this.insecureStorage).get(key);
61045
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
61046
+ throw new Error(`[${key}] is not stored`);
61047
+ }
61048
+ return value;
61049
+ }
61050
+ async set(key, value, options) {
61051
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
61052
+ }
61053
+ async delete(key, options) {
61054
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
61055
+ }
61056
+ async getForUser(userId, key, options) {
61057
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61058
+ let value;
61059
+ if (!userData || !userData[key]) {
61060
+ value = undefined;
61061
+ }
61062
+ value = userData[key];
61063
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
61064
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
61065
+ }
61066
+ return value || undefined;
61067
+ }
61068
+ async setForUser(userId, values, options) {
61069
+ let userData;
61070
+ try {
61071
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61072
+ }
61073
+ catch (_a) {
61074
+ userData = {};
61075
+ }
61076
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
61077
+ }
61078
+ async deleteForUser(userId, key, options) {
61079
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61080
+ delete userData[key];
61081
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
61082
+ }
61083
+ async deleteAllUserData(userId, options) {
61084
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
61085
+ }
60526
61086
  }
60527
61087
 
60528
- class InMemoryStorage {
60529
- constructor() {
60530
- this.map = {};
60531
- }
60532
- async get(key) {
60533
- return this.map[key] || undefined;
60534
- }
60535
- async set(key, value) {
60536
- this.map[key] = value;
60537
- }
60538
- async delete(key) {
60539
- delete this.map[key];
60540
- }
61088
+ class InMemoryStorage {
61089
+ constructor() {
61090
+ this.map = {};
61091
+ }
61092
+ async get(key) {
61093
+ return this.map[key] || undefined;
61094
+ }
61095
+ async set(key, value) {
61096
+ this.map[key] = value;
61097
+ }
61098
+ async delete(key) {
61099
+ delete this.map[key];
61100
+ }
60541
61101
  }
60542
61102
 
60543
- class ConfigurationError extends Error {
60544
- constructor(message) {
60545
- super(message);
60546
- }
61103
+ class ConfigurationError extends Error {
61104
+ constructor(message) {
61105
+ super(message);
61106
+ }
60547
61107
  }
60548
61108
 
60549
- class NotImplementedError extends Error {
60550
- constructor(methodName) {
60551
- super(`[${methodName}] is not implemented`);
60552
- }
61109
+ class NotImplementedError extends Error {
61110
+ constructor(methodName) {
61111
+ super(`[${methodName}] is not implemented`);
61112
+ }
60553
61113
  }
60554
61114
 
60555
- class InvalidResponseError extends Error {
60556
- constructor(missingFields) {
60557
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
60558
- this.missingFields = missingFields;
60559
- }
61115
+ class InvalidResponseError extends Error {
61116
+ constructor(missingFields) {
61117
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
61118
+ this.missingFields = missingFields;
61119
+ }
60560
61120
  }
60561
61121
 
60562
- class OidcProviderError extends Error {
60563
- constructor(message, error, errorDescription) {
60564
- super(message);
60565
- this.error = error;
60566
- this.errorDescription = errorDescription;
60567
- }
61122
+ class OidcProviderError extends Error {
61123
+ constructor(message, error, errorDescription) {
61124
+ super(message);
61125
+ this.error = error;
61126
+ this.errorDescription = errorDescription;
61127
+ }
60568
61128
  }
60569
61129
 
60570
- function normalizeHTU(audience) {
60571
- const audienceUrl = new URL(audience);
60572
- return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
60573
- }
60574
- async function createDpopHeader(audience, method, dpopKey) {
60575
- return new jose__WEBPACK_IMPORTED_MODULE_2__.SignJWT({
60576
- htu: normalizeHTU(audience),
60577
- htm: method.toUpperCase(),
60578
- jti: (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])(),
60579
- })
60580
- .setProtectedHeader({
60581
- alg: PREFERRED_SIGNING_ALG[0],
60582
- jwk: dpopKey.publicKey,
60583
- typ: "dpop+jwt",
60584
- })
60585
- .setIssuedAt()
60586
- .sign(dpopKey.privateKey, {});
60587
- }
60588
- async function generateDpopKeyPair() {
60589
- const { privateKey, publicKey } = await (0,jose__WEBPACK_IMPORTED_MODULE_2__.generateKeyPair)(PREFERRED_SIGNING_ALG[0]);
60590
- const dpopKeyPair = {
60591
- privateKey,
60592
- publicKey: await (0,jose__WEBPACK_IMPORTED_MODULE_2__.exportJWK)(publicKey),
60593
- };
60594
- [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
60595
- return dpopKeyPair;
61130
+ function normalizeHTU(audience) {
61131
+ const audienceUrl = new URL(audience);
61132
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
61133
+ }
61134
+ async function createDpopHeader(audience, method, dpopKey) {
61135
+ return new jose__WEBPACK_IMPORTED_MODULE_1__.SignJWT({
61136
+ htu: normalizeHTU(audience),
61137
+ htm: method.toUpperCase(),
61138
+ jti: (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])(),
61139
+ })
61140
+ .setProtectedHeader({
61141
+ alg: PREFERRED_SIGNING_ALG[0],
61142
+ jwk: dpopKey.publicKey,
61143
+ typ: "dpop+jwt",
61144
+ })
61145
+ .setIssuedAt()
61146
+ .sign(dpopKey.privateKey, {});
61147
+ }
61148
+ async function generateDpopKeyPair() {
61149
+ const { privateKey, publicKey } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)(PREFERRED_SIGNING_ALG[0]);
61150
+ const dpopKeyPair = {
61151
+ privateKey,
61152
+ publicKey: await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(publicKey),
61153
+ };
61154
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
61155
+ return dpopKeyPair;
60596
61156
  }
60597
61157
 
60598
- const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
60599
- function isExpectedAuthError(statusCode) {
60600
- return [401, 403].includes(statusCode);
60601
- }
60602
- async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
60603
- var _a;
60604
- const headers = new cross_fetch__WEBPACK_IMPORTED_MODULE_1__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60605
- headers.set("Authorization", `DPoP ${authToken}`);
60606
- headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
60607
- return {
60608
- ...defaultOptions,
60609
- headers,
60610
- };
60611
- }
60612
- async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
60613
- if (dpopKey !== undefined) {
60614
- return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
60615
- }
60616
- const headers = new cross_fetch__WEBPACK_IMPORTED_MODULE_1__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
60617
- headers.set("Authorization", `Bearer ${authToken}`);
60618
- return {
60619
- ...defaultOptions,
60620
- headers,
60621
- };
60622
- }
60623
- async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
60624
- return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
60625
- }
60626
- async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
60627
- var _a;
60628
- const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
60629
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
60630
- if (typeof tokenSet.refreshToken === "string") {
60631
- eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
60632
- }
60633
- return {
60634
- accessToken: tokenSet.accessToken,
60635
- refreshToken: tokenSet.refreshToken,
60636
- expiresIn: tokenSet.expiresIn,
60637
- };
60638
- }
60639
- const computeRefreshDelay = (expiresIn) => {
60640
- if (expiresIn !== undefined) {
60641
- return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
60642
- ?
60643
- expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
60644
- : expiresIn;
60645
- }
60646
- return DEFAULT_EXPIRATION_TIME_SECONDS;
60647
- };
60648
- async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
60649
- var _a;
60650
- let currentAccessToken = accessToken;
60651
- let latestTimeout;
60652
- const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
60653
- if (currentRefreshOptions !== undefined) {
60654
- const proactivelyRefreshToken = async () => {
60655
- var _a, _b, _c, _d;
60656
- try {
60657
- const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
60658
- currentAccessToken = refreshedAccessToken;
60659
- if (refreshToken !== undefined) {
60660
- currentRefreshOptions.refreshToken = refreshToken;
60661
- }
60662
- clearTimeout(latestTimeout);
60663
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
60664
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60665
- }
60666
- catch (e) {
60667
- if (e instanceof OidcProviderError) {
60668
- (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
60669
- (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
60670
- }
60671
- if (e instanceof InvalidResponseError &&
60672
- e.missingFields.includes("access_token")) {
60673
- (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
60674
- }
60675
- }
60676
- };
60677
- latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
60678
- (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
60679
- }
60680
- else if (options !== undefined && options.eventEmitter !== undefined) {
60681
- const expirationTimeout = setTimeout(() => {
60682
- options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
60683
- }, computeRefreshDelay(options.expiresIn) * 1000);
60684
- options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
60685
- }
60686
- return async (url, requestInit) => {
60687
- let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
60688
- const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
60689
- if (response.ok || failedButNotExpectedAuthError) {
60690
- return response;
60691
- }
60692
- const hasBeenRedirected = response.url !== url;
60693
- if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
60694
- response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
60695
- }
60696
- return response;
60697
- };
61158
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
61159
+ function isExpectedAuthError(statusCode) {
61160
+ return [401, 403].includes(statusCode);
61161
+ }
61162
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
61163
+ var _a;
61164
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
61165
+ headers.set("Authorization", `DPoP ${authToken}`);
61166
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
61167
+ return {
61168
+ ...defaultOptions,
61169
+ headers,
61170
+ };
61171
+ }
61172
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
61173
+ if (dpopKey !== undefined) {
61174
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
61175
+ }
61176
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
61177
+ headers.set("Authorization", `Bearer ${authToken}`);
61178
+ return {
61179
+ ...defaultOptions,
61180
+ headers,
61181
+ };
61182
+ }
61183
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
61184
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
61185
+ }
61186
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
61187
+ var _a;
61188
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
61189
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
61190
+ if (typeof tokenSet.refreshToken === "string") {
61191
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
61192
+ }
61193
+ return {
61194
+ accessToken: tokenSet.accessToken,
61195
+ refreshToken: tokenSet.refreshToken,
61196
+ expiresIn: tokenSet.expiresIn,
61197
+ };
61198
+ }
61199
+ const computeRefreshDelay = (expiresIn) => {
61200
+ if (expiresIn !== undefined) {
61201
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
61202
+ ?
61203
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
61204
+ : expiresIn;
61205
+ }
61206
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
61207
+ };
61208
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
61209
+ var _a;
61210
+ let currentAccessToken = accessToken;
61211
+ let latestTimeout;
61212
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
61213
+ if (currentRefreshOptions !== undefined) {
61214
+ const proactivelyRefreshToken = async () => {
61215
+ var _a, _b, _c, _d;
61216
+ try {
61217
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
61218
+ currentAccessToken = refreshedAccessToken;
61219
+ if (refreshToken !== undefined) {
61220
+ currentRefreshOptions.refreshToken = refreshToken;
61221
+ }
61222
+ clearTimeout(latestTimeout);
61223
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
61224
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
61225
+ }
61226
+ catch (e) {
61227
+ if (e instanceof OidcProviderError) {
61228
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
61229
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
61230
+ }
61231
+ if (e instanceof InvalidResponseError &&
61232
+ e.missingFields.includes("access_token")) {
61233
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
61234
+ }
61235
+ }
61236
+ };
61237
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
61238
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
61239
+ }
61240
+ else if (options !== undefined && options.eventEmitter !== undefined) {
61241
+ const expirationTimeout = setTimeout(() => {
61242
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
61243
+ }, computeRefreshDelay(options.expiresIn) * 1000);
61244
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
61245
+ }
61246
+ return async (url, requestInit) => {
61247
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
61248
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
61249
+ if (response.ok || failedButNotExpectedAuthError) {
61250
+ return response;
61251
+ }
61252
+ const hasBeenRedirected = response.url !== url;
61253
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
61254
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
61255
+ }
61256
+ return response;
61257
+ };
60698
61258
  }
60699
61259
 
60700
- const StorageUtilityGetResponse = "getResponse";
60701
- const StorageUtilityMock = {
60702
- get: async (key, options) => StorageUtilityGetResponse,
60703
- set: async (key, value) => {
60704
- },
60705
- delete: async (key) => {
60706
- },
60707
- getForUser: async (userId, key, options) => StorageUtilityGetResponse,
60708
- setForUser: async (userId, values, options) => {
60709
- },
60710
- deleteForUser: async (userId, key, options) => {
60711
- },
60712
- deleteAllUserData: async (userId, options) => {
60713
- },
60714
- };
60715
- const mockStorage = (stored) => {
60716
- const store = stored;
60717
- return {
60718
- get: async (key) => {
60719
- if (store[key] === undefined) {
60720
- return undefined;
60721
- }
60722
- if (typeof store[key] === "string") {
60723
- return store[key];
60724
- }
60725
- return JSON.stringify(store[key]);
60726
- },
60727
- set: async (key, value) => {
60728
- store[key] = value;
60729
- },
60730
- delete: async (key) => {
60731
- delete store[key];
60732
- },
60733
- };
60734
- };
60735
- const mockStorageUtility = (stored, isSecure = false) => {
60736
- if (isSecure) {
60737
- return new StorageUtility(mockStorage(stored), mockStorage({}));
60738
- }
60739
- return new StorageUtility(mockStorage({}), mockStorage(stored));
61260
+ const StorageUtilityGetResponse = "getResponse";
61261
+ const StorageUtilityMock = {
61262
+ get: async (key, options) => StorageUtilityGetResponse,
61263
+ set: async (key, value) => {
61264
+ },
61265
+ delete: async (key) => {
61266
+ },
61267
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
61268
+ setForUser: async (userId, values, options) => {
61269
+ },
61270
+ deleteForUser: async (userId, key, options) => {
61271
+ },
61272
+ deleteAllUserData: async (userId, options) => {
61273
+ },
61274
+ };
61275
+ const mockStorage = (stored) => {
61276
+ const store = stored;
61277
+ return {
61278
+ get: async (key) => {
61279
+ if (store[key] === undefined) {
61280
+ return undefined;
61281
+ }
61282
+ if (typeof store[key] === "string") {
61283
+ return store[key];
61284
+ }
61285
+ return JSON.stringify(store[key]);
61286
+ },
61287
+ set: async (key, value) => {
61288
+ store[key] = value;
61289
+ },
61290
+ delete: async (key) => {
61291
+ delete store[key];
61292
+ },
61293
+ };
61294
+ };
61295
+ const mockStorageUtility = (stored, isSecure = false) => {
61296
+ if (isSecure) {
61297
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
61298
+ }
61299
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
60740
61300
  };
60741
61301
 
60742
61302
 
60743
61303
 
60744
61304
 
61305
+ /***/ }),
61306
+
61307
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs":
61308
+ /*!*********************************************************************!*\
61309
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs ***!
61310
+ \*********************************************************************/
61311
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
61312
+
61313
+ "use strict";
61314
+ __webpack_require__.r(__webpack_exports__);
61315
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
61316
+ /* harmony export */ "Headers": () => (/* binding */ Headers),
61317
+ /* harmony export */ "Request": () => (/* binding */ Request),
61318
+ /* harmony export */ "Response": () => (/* binding */ Response),
61319
+ /* harmony export */ "default": () => (/* binding */ indexBrowser),
61320
+ /* harmony export */ "fetch": () => (/* binding */ fetch)
61321
+ /* harmony export */ });
61322
+ var indexBrowser = globalThis.fetch;
61323
+ const { fetch, Response, Request, Headers } = globalThis;
61324
+
61325
+
61326
+
61327
+
60745
61328
  /***/ }),
60746
61329
 
60747
61330
  /***/ "./node_modules/jose/dist/browser/index.js":
@@ -61809,14 +62392,17 @@ __webpack_require__.r(__webpack_exports__);
61809
62392
  /* harmony export */ "createRemoteJWKSet": () => (/* binding */ createRemoteJWKSet)
61810
62393
  /* harmony export */ });
61811
62394
  /* 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");
61812
- /* harmony import */ var _runtime_env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../runtime/env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
61813
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
61814
- /* harmony import */ var _local_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./local.js */ "./node_modules/jose/dist/browser/jwks/local.js");
61815
-
62395
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
62396
+ /* harmony import */ var _local_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./local.js */ "./node_modules/jose/dist/browser/jwks/local.js");
61816
62397
 
61817
62398
 
61818
62399
 
61819
- class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
62400
+ function isCloudflareWorkers() {
62401
+ return (typeof WebSocketPair !== 'undefined' ||
62402
+ (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
62403
+ (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
62404
+ }
62405
+ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_2__.LocalJWKSet {
61820
62406
  constructor(url, options) {
61821
62407
  super({ keys: [] });
61822
62408
  this._jwks = undefined;
@@ -61849,7 +62435,7 @@ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
61849
62435
  return await super.getKey(protectedHeader, token);
61850
62436
  }
61851
62437
  catch (err) {
61852
- if (err instanceof _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JWKSNoMatchingKey) {
62438
+ if (err instanceof _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JWKSNoMatchingKey) {
61853
62439
  if (this.coolingDown() === false) {
61854
62440
  await this.reload();
61855
62441
  return super.getKey(protectedHeader, token);
@@ -61859,13 +62445,13 @@ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
61859
62445
  }
61860
62446
  }
61861
62447
  async reload() {
61862
- if (this._pendingFetch && (0,_runtime_env_js__WEBPACK_IMPORTED_MODULE_1__.isCloudflareWorkers)()) {
62448
+ if (this._pendingFetch && isCloudflareWorkers()) {
61863
62449
  this._pendingFetch = undefined;
61864
62450
  }
61865
62451
  this._pendingFetch || (this._pendingFetch = (0,_runtime_fetch_jwks_js__WEBPACK_IMPORTED_MODULE_0__["default"])(this._url, this._timeoutDuration, this._options)
61866
62452
  .then((json) => {
61867
- if (!(0,_local_js__WEBPACK_IMPORTED_MODULE_3__.isJWKSLike)(json)) {
61868
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JWKSInvalid('JSON Web Key Set malformed');
62453
+ if (!(0,_local_js__WEBPACK_IMPORTED_MODULE_2__.isJWKSLike)(json)) {
62454
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JWKSInvalid('JSON Web Key Set malformed');
61869
62455
  }
61870
62456
  this._jwks = { keys: json.keys };
61871
62457
  this._jwksTimestamp = Date.now();
@@ -63053,8 +63639,6 @@ __webpack_require__.r(__webpack_exports__);
63053
63639
  /* harmony export */ "checkEncCryptoKey": () => (/* binding */ checkEncCryptoKey),
63054
63640
  /* harmony export */ "checkSigCryptoKey": () => (/* binding */ checkSigCryptoKey)
63055
63641
  /* harmony export */ });
63056
- /* harmony import */ var _runtime_env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../runtime/env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
63057
-
63058
63642
  function unusable(name, prop = 'algorithm.name') {
63059
63643
  return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
63060
63644
  }
@@ -63129,11 +63713,6 @@ function checkSigCryptoKey(key, alg, ...usages) {
63129
63713
  }
63130
63714
  case 'EdDSA': {
63131
63715
  if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {
63132
- if ((0,_runtime_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)()) {
63133
- if (isAlgorithm(key.algorithm, 'NODE-ED25519'))
63134
- break;
63135
- throw unusable('Ed25519, Ed448, or NODE-ED25519');
63136
- }
63137
63716
  throw unusable('Ed25519 or Ed448');
63138
63717
  }
63139
63718
  break;
@@ -63964,14 +64543,12 @@ __webpack_require__.r(__webpack_exports__);
63964
64543
  /* harmony export */ "toPKCS8": () => (/* binding */ toPKCS8),
63965
64544
  /* harmony export */ "toSPKI": () => (/* binding */ toSPKI)
63966
64545
  /* harmony export */ });
63967
- /* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
63968
- /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
63969
- /* 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");
63970
- /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
63971
- /* 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");
63972
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
63973
- /* 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");
63974
-
64546
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
64547
+ /* 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");
64548
+ /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
64549
+ /* 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");
64550
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
64551
+ /* 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");
63975
64552
 
63976
64553
 
63977
64554
 
@@ -63979,8 +64556,8 @@ __webpack_require__.r(__webpack_exports__);
63979
64556
 
63980
64557
 
63981
64558
  const genericExport = async (keyType, keyFormat, key) => {
63982
- if (!(0,_webcrypto_js__WEBPACK_IMPORTED_MODULE_1__.isCryptoKey)(key)) {
63983
- throw new TypeError((0,_lib_invalid_key_input_js__WEBPACK_IMPORTED_MODULE_2__["default"])(key, ..._is_key_like_js__WEBPACK_IMPORTED_MODULE_6__.types));
64559
+ if (!(0,_webcrypto_js__WEBPACK_IMPORTED_MODULE_0__.isCryptoKey)(key)) {
64560
+ throw new TypeError((0,_lib_invalid_key_input_js__WEBPACK_IMPORTED_MODULE_1__["default"])(key, ..._is_key_like_js__WEBPACK_IMPORTED_MODULE_5__.types));
63984
64561
  }
63985
64562
  if (!key.extractable) {
63986
64563
  throw new TypeError('CryptoKey is not extractable');
@@ -63988,7 +64565,7 @@ const genericExport = async (keyType, keyFormat, key) => {
63988
64565
  if (key.type !== keyType) {
63989
64566
  throw new TypeError(`key is not a ${keyType} key`);
63990
64567
  }
63991
- 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`);
64568
+ 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`);
63992
64569
  };
63993
64570
  const toSPKI = (key) => {
63994
64571
  return genericExport('public', 'spki', key);
@@ -64026,11 +64603,11 @@ const getNamedCurve = (keyData) => {
64026
64603
  case findOid(keyData, [0x2b, 0x65, 0x71]):
64027
64604
  return 'Ed448';
64028
64605
  default:
64029
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_5__.JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');
64606
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_4__.JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');
64030
64607
  }
64031
64608
  };
64032
64609
  const genericImport = async (replace, keyFormat, pem, alg, options) => {
64033
- var _a, _b;
64610
+ var _a;
64034
64611
  let algorithm;
64035
64612
  let keyUsages;
64036
64613
  const keyData = new Uint8Array(atob(pem.replace(replace, ''))
@@ -64086,20 +64663,9 @@ const genericImport = async (replace, keyFormat, pem, alg, options) => {
64086
64663
  keyUsages = isPublic ? ['verify'] : ['sign'];
64087
64664
  break;
64088
64665
  default:
64089
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_5__.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
64090
- }
64091
- try {
64092
- 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);
64093
- }
64094
- catch (err) {
64095
- if (algorithm.name === 'Ed25519' &&
64096
- (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' &&
64097
- (0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)()) {
64098
- algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };
64099
- 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);
64100
- }
64101
- throw err;
64666
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_4__.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
64102
64667
  }
64668
+ 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);
64103
64669
  };
64104
64670
  const fromPKCS8 = (pem, alg, options) => {
64105
64671
  return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options);
@@ -64168,12 +64734,12 @@ function parseElement(bytes) {
64168
64734
  }
64169
64735
  function spkiFromX509(buf) {
64170
64736
  const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);
64171
- return (0,_base64url_js__WEBPACK_IMPORTED_MODULE_3__.encodeBase64)(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);
64737
+ return (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.encodeBase64)(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);
64172
64738
  }
64173
64739
  function getSPKI(x509) {
64174
64740
  const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '');
64175
- const raw = (0,_base64url_js__WEBPACK_IMPORTED_MODULE_3__.decodeBase64)(pem);
64176
- return (0,_lib_format_pem_js__WEBPACK_IMPORTED_MODULE_4__["default"])(spkiFromX509(raw), 'PUBLIC KEY');
64741
+ const raw = (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.decodeBase64)(pem);
64742
+ return (0,_lib_format_pem_js__WEBPACK_IMPORTED_MODULE_3__["default"])(spkiFromX509(raw), 'PUBLIC KEY');
64177
64743
  }
64178
64744
  const fromX509 = (pem, alg, options) => {
64179
64745
  let spki;
@@ -64601,26 +65167,6 @@ const encrypt = async (enc, plaintext, cek, iv, aad) => {
64601
65167
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (encrypt);
64602
65168
 
64603
65169
 
64604
- /***/ }),
64605
-
64606
- /***/ "./node_modules/jose/dist/browser/runtime/env.js":
64607
- /*!*******************************************************!*\
64608
- !*** ./node_modules/jose/dist/browser/runtime/env.js ***!
64609
- \*******************************************************/
64610
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
64611
-
64612
- "use strict";
64613
- __webpack_require__.r(__webpack_exports__);
64614
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
64615
- /* harmony export */ "isCloudflareWorkers": () => (/* binding */ isCloudflareWorkers)
64616
- /* harmony export */ });
64617
- function isCloudflareWorkers() {
64618
- return (typeof WebSocketPair !== 'undefined' ||
64619
- (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
64620
- (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
64621
- }
64622
-
64623
-
64624
65170
  /***/ }),
64625
65171
 
64626
65172
  /***/ "./node_modules/jose/dist/browser/runtime/fetch_jwks.js":
@@ -64685,11 +65231,9 @@ __webpack_require__.r(__webpack_exports__);
64685
65231
  /* harmony export */ "generateKeyPair": () => (/* binding */ generateKeyPair),
64686
65232
  /* harmony export */ "generateSecret": () => (/* binding */ generateSecret)
64687
65233
  /* harmony export */ });
64688
- /* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
64689
- /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
64690
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
64691
- /* harmony import */ var _random_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./random.js */ "./node_modules/jose/dist/browser/runtime/random.js");
64692
-
65234
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
65235
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65236
+ /* harmony import */ var _random_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./random.js */ "./node_modules/jose/dist/browser/runtime/random.js");
64693
65237
 
64694
65238
 
64695
65239
 
@@ -64710,7 +65254,7 @@ async function generateSecret(alg, options) {
64710
65254
  case 'A192CBC-HS384':
64711
65255
  case 'A256CBC-HS512':
64712
65256
  length = parseInt(alg.slice(-3), 10);
64713
- return (0,_random_js__WEBPACK_IMPORTED_MODULE_3__["default"])(new Uint8Array(length >> 3));
65257
+ return (0,_random_js__WEBPACK_IMPORTED_MODULE_2__["default"])(new Uint8Array(length >> 3));
64714
65258
  case 'A128KW':
64715
65259
  case 'A192KW':
64716
65260
  case 'A256KW':
@@ -64729,20 +65273,20 @@ async function generateSecret(alg, options) {
64729
65273
  keyUsages = ['encrypt', 'decrypt'];
64730
65274
  break;
64731
65275
  default:
64732
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65276
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64733
65277
  }
64734
- 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);
65278
+ 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);
64735
65279
  }
64736
65280
  function getModulusLengthOption(options) {
64737
65281
  var _a;
64738
65282
  const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048;
64739
65283
  if (typeof modulusLength !== 'number' || modulusLength < 2048) {
64740
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
65284
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
64741
65285
  }
64742
65286
  return modulusLength;
64743
65287
  }
64744
65288
  async function generateKeyPair(alg, options) {
64745
- var _a, _b, _c, _d;
65289
+ var _a, _b, _c;
64746
65290
  let algorithm;
64747
65291
  let keyUsages;
64748
65292
  switch (alg) {
@@ -64801,7 +65345,7 @@ async function generateKeyPair(alg, options) {
64801
65345
  algorithm = { name: crv };
64802
65346
  break;
64803
65347
  default:
64804
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported crv option provided');
65348
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported crv option provided');
64805
65349
  }
64806
65350
  break;
64807
65351
  case 'ECDH-ES':
@@ -64822,25 +65366,14 @@ async function generateKeyPair(alg, options) {
64822
65366
  algorithm = { name: crv };
64823
65367
  break;
64824
65368
  default:
64825
- 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');
65369
+ 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');
64826
65370
  }
64827
65371
  break;
64828
65372
  }
64829
65373
  default:
64830
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64831
- }
64832
- try {
64833
- 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));
64834
- }
64835
- catch (err) {
64836
- if (algorithm.name === 'Ed25519' &&
64837
- (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' &&
64838
- (0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)()) {
64839
- algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };
64840
- 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));
64841
- }
64842
- throw err;
65374
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64843
65375
  }
65376
+ 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));
64844
65377
  }
64845
65378
 
64846
65379
 
@@ -64915,11 +65448,9 @@ __webpack_require__.r(__webpack_exports__);
64915
65448
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
64916
65449
  /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
64917
65450
  /* harmony export */ });
64918
- /* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
64919
- /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
64920
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
64921
- /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
64922
-
65451
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
65452
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65453
+ /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
64923
65454
 
64924
65455
 
64925
65456
 
@@ -64938,7 +65469,7 @@ function subtleMapping(jwk) {
64938
65469
  case 'A128CBC-HS256':
64939
65470
  case 'A192CBC-HS384':
64940
65471
  case 'A256CBC-HS512':
64941
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`);
65472
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`);
64942
65473
  case 'A128GCM':
64943
65474
  case 'A192GCM':
64944
65475
  case 'A256GCM':
@@ -64961,7 +65492,7 @@ function subtleMapping(jwk) {
64961
65492
  keyUsages = ['deriveBits'];
64962
65493
  break;
64963
65494
  default:
64964
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65495
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64965
65496
  }
64966
65497
  break;
64967
65498
  }
@@ -64990,7 +65521,7 @@ function subtleMapping(jwk) {
64990
65521
  keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];
64991
65522
  break;
64992
65523
  default:
64993
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65524
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64994
65525
  }
64995
65526
  break;
64996
65527
  }
@@ -65016,7 +65547,7 @@ function subtleMapping(jwk) {
65016
65547
  keyUsages = jwk.d ? ['deriveBits'] : [];
65017
65548
  break;
65018
65549
  default:
65019
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65550
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65020
65551
  }
65021
65552
  break;
65022
65553
  }
@@ -65034,12 +65565,12 @@ function subtleMapping(jwk) {
65034
65565
  keyUsages = jwk.d ? ['deriveBits'] : [];
65035
65566
  break;
65036
65567
  default:
65037
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65568
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65038
65569
  }
65039
65570
  break;
65040
65571
  }
65041
65572
  default:
65042
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
65573
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
65043
65574
  }
65044
65575
  return { algorithm, keyUsages };
65045
65576
  }
@@ -65055,23 +65586,12 @@ const parse = async (jwk) => {
65055
65586
  (_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages,
65056
65587
  ];
65057
65588
  if (algorithm.name === 'PBKDF2') {
65058
- return _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.importKey('raw', (0,_base64url_js__WEBPACK_IMPORTED_MODULE_3__.decode)(jwk.k), ...rest);
65589
+ return _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.importKey('raw', (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.decode)(jwk.k), ...rest);
65059
65590
  }
65060
65591
  const keyData = { ...jwk };
65061
65592
  delete keyData.alg;
65062
65593
  delete keyData.use;
65063
- try {
65064
- return await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.importKey('jwk', keyData, ...rest);
65065
- }
65066
- catch (err) {
65067
- if (algorithm.name === 'Ed25519' &&
65068
- (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' &&
65069
- (0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)()) {
65070
- rest[0] = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };
65071
- return await _webcrypto_js__WEBPACK_IMPORTED_MODULE_1__["default"].subtle.importKey('jwk', keyData, ...rest);
65072
- }
65073
- throw err;
65074
- }
65594
+ return _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.importKey('jwk', keyData, ...rest);
65075
65595
  };
65076
65596
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (parse);
65077
65597
 
@@ -65313,9 +65833,7 @@ __webpack_require__.r(__webpack_exports__);
65313
65833
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
65314
65834
  /* harmony export */ "default": () => (/* binding */ subtleDsa)
65315
65835
  /* harmony export */ });
65316
- /* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./node_modules/jose/dist/browser/runtime/env.js");
65317
- /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65318
-
65836
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65319
65837
 
65320
65838
  function subtleDsa(alg, algorithm) {
65321
65839
  const hash = `SHA-${alg.slice(-3)}`;
@@ -65337,12 +65855,9 @@ function subtleDsa(alg, algorithm) {
65337
65855
  case 'ES512':
65338
65856
  return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };
65339
65857
  case 'EdDSA':
65340
- if ((0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isCloudflareWorkers)() && algorithm.name === 'NODE-ED25519') {
65341
- return { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' };
65342
- }
65343
65858
  return { name: algorithm.name };
65344
65859
  default:
65345
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
65860
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_0__.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
65346
65861
  }
65347
65862
  }
65348
65863