solid-ui 2.4.27-109c4946 → 2.4.27-17005e61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/solid-ui.js CHANGED
@@ -2655,7 +2655,7 @@ var ChatChannel = /*#__PURE__*/function () {
2655
2655
  var oldMsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2656
2656
  var deleteIt = arguments.length > 2 ? arguments[2] : undefined;
2657
2657
  return /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
2658
- var sts, now, timestamp, dateStamp, chatDocument, message, me, msg, privateKey, errMsg;
2658
+ var sts, now, timestamp, dateStamp, chatDocument, message, me, msg, oldMsgMaker, errMsg, privateKey, pubKey, sig, _errMsg;
2659
2659
  return _regenerator["default"].wrap(function _callee2$(_context2) {
2660
2660
  while (1) switch (_context2.prev = _context2.next) {
2661
2661
  case 0:
@@ -2666,57 +2666,84 @@ 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 = 36;
2689
2707
  break;
2690
2708
  }
2691
2709
  sts.push($rdf.st(message, ns.foaf('maker'), me, chatDocument));
2692
- msg.maker = me;
2693
- // privateKey the cached private key of me, cache should be deleted after a certain time
2694
- _context2.next = 19;
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
+ // const pubKey0 = '023a9da707bee1302f66083c9d95673ff969b41607a66f52686fa774d64ceb87'
2719
+ pubKey = (0, _keys.getPublicKey)(me.uri);
2720
+ sig = (0, _signature.signMsg)(msg, privateKey);
2721
+ /* const verify = verifySignature(sig, msg, pubKey) // alain to remove
2722
+ debug.warn('sig ' + sig)
2723
+ debug.warn('verifySign ' + verify)
2724
+ debug.warn(msg) */
2725
+ sts.push($rdf.st(message, $rdf.sym("".concat(_signature.SEC, "Proof")), $rdf.lit(sig), chatDocument));
2726
+ case 36:
2727
+ _context2.prev = 36;
2728
+ _context2.next = 39;
2702
2729
  return _solidLogic.store.updater.update([], sts);
2703
- case 24:
2704
- _context2.next = 32;
2730
+ case 39:
2731
+ _context2.next = 47;
2705
2732
  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:
2733
+ case 41:
2734
+ _context2.prev = 41;
2735
+ _context2.t0 = _context2["catch"](36);
2736
+ _errMsg = 'Error saving chat message: ' + _context2.t0;
2737
+ debug.warn(_errMsg);
2738
+ alert(_errMsg);
2739
+ throw new Error(_errMsg);
2740
+ case 47:
2714
2741
  return _context2.abrupt("return", message);
2715
- case 33:
2742
+ case 48:
2716
2743
  case "end":
2717
2744
  return _context2.stop();
2718
2745
  }
2719
- }, _callee2, null, [[21, 26]]);
2746
+ }, _callee2, null, [[36, 41]]);
2720
2747
  })();
2721
2748
  });
2722
2749
  function updateMessage(_x2) {
@@ -4011,11 +4038,13 @@ exports.getPrivateKey = getPrivateKey;
4011
4038
  exports.getPublicKey = getPublicKey;
4012
4039
  var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
4013
4040
  var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
4041
+ var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js"));
4014
4042
  var _secp256k = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/secp256k1.js");
4015
4043
  var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
4016
4044
  var _signature = __webpack_require__(/*! ./signature */ "./lib/chat/signature.js");
4017
4045
  var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js");
4018
4046
  var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"));
4047
+ var _cryptoKeyHelpers = __webpack_require__(/*! ../utils/cryptoKeyHelpers */ "./lib/utils/cryptoKeyHelpers.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,67 +4053,275 @@ 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) {
4052
- return _getPrivateKey.apply(this, arguments);
4056
+ function getPublicKey(_x) {
4057
+ return _getPublicKey.apply(this, arguments);
4053
4058
  }
4054
- function _getPrivateKey() {
4055
- _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4056
- var url, privateKeyUrl, publicKey, privateKey, del, add;
4059
+ function _getPublicKey() {
4060
+ _getPublicKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
4061
+ var publicKeyDoc, key;
4057
4062
  return _regenerator["default"].wrap(function _callee$(_context) {
4058
4063
  while (1) switch (_context.prev = _context.next) {
4059
4064
  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)) {
4065
- _context.next = 15;
4065
+ _context.next = 2;
4066
+ return _solidLogic.store.fetcher.load(webId);
4067
+ case 2:
4068
+ _context.next = 4;
4069
+ return (0, _cryptoKeyHelpers.pubKeyUrl)(webId);
4070
+ case 4:
4071
+ publicKeyDoc = _context.sent;
4072
+ _context.prev = 5;
4073
+ _context.next = 8;
4074
+ return _solidLogic.store.fetcher.load(publicKeyDoc);
4075
+ case 8:
4076
+ // url.href)
4077
+ key = _solidLogic.store.any(webId, _solidLogic.store.sym(_signature.CERT + 'PublicKey'));
4078
+ return _context.abrupt("return", key === null || key === void 0 ? void 0 : key.value);
4079
+ case 12:
4080
+ _context.prev = 12;
4081
+ _context.t0 = _context["catch"](5);
4082
+ return _context.abrupt("return", undefined);
4083
+ case 15:
4084
+ case "end":
4085
+ return _context.stop();
4086
+ }
4087
+ }, _callee, null, [[5, 12]]);
4088
+ }));
4089
+ return _getPublicKey.apply(this, arguments);
4090
+ }
4091
+ function getPrivateKey(_x2) {
4092
+ return _getPrivateKey.apply(this, arguments);
4093
+ }
4094
+ /**
4095
+ * key container ACL
4096
+ * @param me
4097
+ * @returns aclBody
4098
+ */
4099
+ function _getPrivateKey() {
4100
+ _getPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
4101
+ var publicKeyDoc, privateKeyDoc, publicKey, privateKey, validPublicKey, del, add, newPublicKey, keyContainer;
4102
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
4103
+ while (1) switch (_context2.prev = _context2.next) {
4104
+ case 0:
4105
+ _context2.next = 2;
4106
+ return _solidLogic.store.fetcher.load(webId);
4107
+ case 2:
4108
+ _context2.next = 4;
4109
+ return (0, _cryptoKeyHelpers.pubKeyUrl)(webId);
4110
+ case 4:
4111
+ publicKeyDoc = _context2.sent;
4112
+ _context2.next = 7;
4113
+ return (0, _cryptoKeyHelpers.privKeyUrl)(webId);
4114
+ case 7:
4115
+ privateKeyDoc = _context2.sent;
4116
+ _context2.next = 10;
4117
+ return (0, _cryptoKeyHelpers.publicKeyExists)(webId);
4118
+ case 10:
4119
+ publicKey = _context2.sent;
4120
+ _context2.next = 13;
4121
+ return (0, _cryptoKeyHelpers.privateKeyExists)(webId);
4122
+ case 13:
4123
+ privateKey = _context2.sent;
4124
+ // is publicKey valid ?
4125
+ validPublicKey = true;
4126
+ if (privateKey && publicKey !== generatePublicKey(privateKey)) {
4127
+ 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;
4128
+ }
4129
+
4130
+ // create key pair or repair publicKey
4131
+ if (!(!privateKey || !publicKey || !validPublicKey)) {
4132
+ _context2.next = 34;
4066
4133
  break;
4067
4134
  }
4068
4135
  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);
4078
- case 15:
4079
- return _context.abrupt("return", privateKey.uri);
4080
- case 16:
4136
+ add = []; // if (privateKey) del.push($rdf.st(webId, store.sym(CERT + 'PrivateKey'), $rdf.lit(privateKey), store.sym(privateKeyDoc)))
4137
+ if (privateKey) {
4138
+ _context2.next = 24;
4139
+ break;
4140
+ }
4141
+ // add = []
4142
+ privateKey = generatePrivateKey();
4143
+ add = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PrivateKey'), $rdf.literal(privateKey), _solidLogic.store.sym(privateKeyDoc))];
4144
+ _context2.next = 24;
4145
+ return saveKey(privateKeyDoc, [], add, webId.uri);
4146
+ case 24:
4147
+ if (!(!publicKey || !validPublicKey)) {
4148
+ _context2.next = 31;
4149
+ break;
4150
+ }
4151
+ del = [];
4152
+ // delete invalid public key
4153
+ if (publicKey) {
4154
+ del = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PublicKey'), $rdf.lit(publicKey), _solidLogic.store.sym(publicKeyDoc))];
4155
+ debug.log(del);
4156
+ }
4157
+ // update new valid key
4158
+ newPublicKey = generatePublicKey(privateKey);
4159
+ add = [$rdf.st(webId, _solidLogic.store.sym(_signature.CERT + 'PublicKey'), $rdf.literal(newPublicKey), _solidLogic.store.sym(publicKeyDoc))];
4160
+ _context2.next = 31;
4161
+ return saveKey(publicKeyDoc, del, add);
4162
+ case 31:
4163
+ keyContainer = privateKeyDoc.substring(0, privateKeyDoc.lastIndexOf('/') + 1);
4164
+ _context2.next = 34;
4165
+ return setAcl(keyContainer, keyContainerAclBody(webId.uri));
4166
+ case 34:
4167
+ return _context2.abrupt("return", privateKey);
4168
+ case 35:
4081
4169
  case "end":
4082
- return _context.stop();
4170
+ return _context2.stop();
4083
4171
  }
4084
- }, _callee);
4172
+ }, _callee2);
4085
4173
  }));
4086
4174
  return _getPrivateKey.apply(this, arguments);
4087
4175
  }
4176
+ var keyContainerAclBody = function keyContainerAclBody(me) {
4177
+ 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");
4178
+ return aclBody;
4179
+ };
4180
+
4181
+ /**
4182
+ * Read only ACL
4183
+ * @param keyDoc
4184
+ * @param me
4185
+ * @returns aclBody
4186
+ */
4187
+ var keyAclBody = function keyAclBody(keyDoc, me) {
4188
+ var keyAgent = 'acl:agentClass foaf:Agent'; // publicKey
4189
+ if (me !== null && me !== void 0 && me.length) keyAgent = "acl:agent <".concat(me, ">"); // privateKey
4190
+ 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");
4191
+ return aclBody;
4192
+ };
4193
+
4194
+ /**
4195
+ * set ACL
4196
+ * @param keyDoc
4197
+ * @param aclBody
4198
+ */
4199
+ function setAcl(_x3, _x4) {
4200
+ return _setAcl.apply(this, arguments);
4201
+ }
4202
+ /**
4203
+ * delete acl if keydoc exists
4204
+ * create/edit keyDoc
4205
+ * set keyDoc acl
4206
+ */
4207
+ function _setAcl() {
4208
+ _setAcl = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(keyDoc, aclBody) {
4209
+ var keyAclDoc, response, aclResponse;
4210
+ return _regenerator["default"].wrap(function _callee3$(_context3) {
4211
+ while (1) switch (_context3.prev = _context3.next) {
4212
+ case 0:
4213
+ _context3.next = 2;
4214
+ return _solidLogic.store.fetcher.load(keyDoc);
4215
+ case 2:
4216
+ // FIXME: check the Why value on this quad:
4217
+ debug.log(_solidLogic.store.statementsMatching(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl')));
4218
+ keyAclDoc = _solidLogic.store.any(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl'));
4219
+ if (keyAclDoc) {
4220
+ _context3.next = 6;
4221
+ break;
4222
+ }
4223
+ throw new Error('Key ACL doc not found!');
4224
+ case 6:
4225
+ _context3.prev = 6;
4226
+ _context3.next = 9;
4227
+ return _solidLogic.store.fetcher.webOperation('DELETE', keyAclDoc.value);
4228
+ case 9:
4229
+ response = _context3.sent;
4230
+ // this may fail if webId is not an owner
4231
+ debug.log('delete ' + keyAclDoc.value + ' ' + response.status); // should test 404 and 2xx
4232
+ _context3.next = 18;
4233
+ break;
4234
+ case 13:
4235
+ _context3.prev = 13;
4236
+ _context3.t0 = _context3["catch"](6);
4237
+ if (!(_context3.t0.response.status !== 404)) {
4238
+ _context3.next = 17;
4239
+ break;
4240
+ }
4241
+ throw new Error(_context3.t0);
4242
+ case 17:
4243
+ debug.log('delete ' + keyAclDoc.value + ' ' + _context3.t0.response.status); // should test 404 and 2xx
4244
+ case 18:
4245
+ _context3.next = 20;
4246
+ return _solidLogic.store.fetcher.webOperation('PUT', keyAclDoc.value, {
4247
+ data: aclBody,
4248
+ contentType: 'text/turtle'
4249
+ });
4250
+ case 20:
4251
+ aclResponse = _context3.sent;
4252
+ case 21:
4253
+ case "end":
4254
+ return _context3.stop();
4255
+ }
4256
+ }, _callee3, null, [[6, 13]]);
4257
+ }));
4258
+ return _setAcl.apply(this, arguments);
4259
+ }
4260
+ function saveKey(_x5, _x6, _x7) {
4261
+ return _saveKey.apply(this, arguments);
4262
+ }
4263
+ function _saveKey() {
4264
+ _saveKey = (0, _asyncToGenerator2["default"])(function (keyDoc, del, add) {
4265
+ var me = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
4266
+ return /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
4267
+ var keyAclDoc, response, aclBody;
4268
+ return _regenerator["default"].wrap(function _callee4$(_context4) {
4269
+ while (1) switch (_context4.prev = _context4.next) {
4270
+ case 0:
4271
+ _context4.next = 2;
4272
+ return _solidLogic.store.fetcher.load(keyDoc);
4273
+ case 2:
4274
+ _context4.prev = 2;
4275
+ // get keyAcldoc
4276
+ keyAclDoc = _solidLogic.store.any(_solidLogic.store.sym(keyDoc), _solidLogic.store.sym('http://www.iana.org/assignments/link-relations/acl'));
4277
+ if (!keyAclDoc) {
4278
+ _context4.next = 17;
4279
+ break;
4280
+ }
4281
+ _context4.prev = 5;
4282
+ _context4.next = 8;
4283
+ return _solidLogic.store.fetcher.webOperation('DELETE', keyAclDoc.value);
4284
+ case 8:
4285
+ response = _context4.sent;
4286
+ // this may fail if webId is not an owner
4287
+ debug.log('delete ' + keyAclDoc.value + ' ' + response.status); // should test 404 and 2xx
4288
+ _context4.next = 17;
4289
+ break;
4290
+ case 12:
4291
+ _context4.prev = 12;
4292
+ _context4.t0 = _context4["catch"](5);
4293
+ if (!(_context4.t0.response.status !== 404)) {
4294
+ _context4.next = 16;
4295
+ break;
4296
+ }
4297
+ throw new Error(_context4.t0);
4298
+ case 16:
4299
+ debug.log('delete ' + keyAclDoc.value + ' ' + _context4.t0.response.status); // should test 404 and 2xx
4300
+ case 17:
4301
+ _context4.next = 19;
4302
+ return _solidLogic.store.updater.updateMany(del, add);
4303
+ case 19:
4304
+ // or a promise store.updater.update ?
4305
+ // create READ only ACL
4306
+ aclBody = keyAclBody(keyDoc, me);
4307
+ _context4.next = 22;
4308
+ return setAcl(keyDoc, aclBody);
4309
+ case 22:
4310
+ _context4.next = 27;
4311
+ break;
4312
+ case 24:
4313
+ _context4.prev = 24;
4314
+ _context4.t1 = _context4["catch"](2);
4315
+ throw new Error(_context4.t1);
4316
+ case 27:
4317
+ case "end":
4318
+ return _context4.stop();
4319
+ }
4320
+ }, _callee4, null, [[2, 24], [5, 12]]);
4321
+ })();
4322
+ });
4323
+ return _saveKey.apply(this, arguments);
4324
+ }
4088
4325
  //# sourceMappingURL=keys.js.map
4089
4326
 
4090
4327
  /***/ }),
@@ -4213,21 +4450,39 @@ function renderMessageRow(channelObject, message, fresh, options, userContext) {
4213
4450
  var creator = _solidLogic.store.any(message, ns.foaf('maker'));
4214
4451
  var date = _solidLogic.store.any(message, ns.dct('created'));
4215
4452
  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")));
4453
+ var latestVersionCreator = _solidLogic.store.any(latestVersion, ns.foaf('maker'));
4218
4454
 
4219
- // verify signature
4455
+ // use latest content if same owner, else use original
4456
+ var msgId = creator.uri === latestVersionCreator.uri ? latestVersion : message;
4457
+ var content = _solidLogic.store.any(msgId, ns.sioc('content'));
4458
+ var signature = _solidLogic.store.any(msgId, $rdf.sym("".concat(_signature.SEC, "Proof")));
4459
+
4460
+ // set message object
4220
4461
  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();
4462
+ msg.id = msgId.uri;
4463
+ msg.created = _solidLogic.store.any(msgId, ns.dct('created')).value;
4464
+ msg.content = content.value;
4465
+ msg.maker = creator.uri;
4466
+
4467
+ // unsigned message
4468
+ if (!(signature !== null && signature !== void 0 && signature.value)) debug.warn(msgId.uri + ' is unsigned'); // TODO replace with UI (colored message ?)
4469
+
4470
+ // signed message, get public key and check signature
4471
+ else {
4472
+ (0, _keys.getPublicKey)(creator.uri).then(function (publicKey) {
4473
+ debug.log(creator.uri + '\n' + msg.created + '\n' + msg.id + '\n' + publicKey);
4474
+ if (!publicKey) {
4475
+ // TODO try to recreate the publicKey
4476
+ // if(me.uri === creator.uri) await getPrivateKey(creator)
4477
+ debug.warn('message is signed but ' + creator.uri + ' is missing publicKey');
4478
+ }
4479
+ // check that publicKey is a valid hex string
4480
+ var regex = /[0-9A-Fa-f]{6}/g;
4481
+ if (!(publicKey !== null && publicKey !== void 0 && publicKey.match(regex))) debug.warn('invalid publicKey hex string\n' + creator.uri + '\n' + publicKey);
4482
+ // verify signature
4483
+ 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);
4484
+ });
4485
+ }
4231
4486
  var originalMessage = (0, _chatLogic.originalVersion)(message);
4232
4487
  var edited = !message.sameTerm(originalMessage);
4233
4488
  var sortDate = _solidLogic.store.the(originalMessage, ns.dct('created'), null, originalMessage.doc()); // In message
@@ -5030,8 +5285,8 @@ exports.utf8Encoder = exports.utf8Decoder = void 0;
5030
5285
  exports.validateMsg = validateMsg;
5031
5286
  exports.verifySignature = verifySignature;
5032
5287
  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
5288
  var _utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
5289
+ var _sha = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
5035
5290
  // import {utf8Encoder} from './utils'
5036
5291
  // import { getPublicKey } from './keys'
5037
5292
 
@@ -5041,7 +5296,7 @@ var utf8Encoder = new TextEncoder();
5041
5296
  exports.utf8Encoder = utf8Encoder;
5042
5297
  var SEC = 'https://w3id.org/security#'; // Proof, VerificationMethod
5043
5298
  exports.SEC = SEC;
5044
- var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivatKey, PublicKey
5299
+ var CERT = 'http://www.w3.org/ns/auth/cert#'; // PrivateKey, PublicKey
5045
5300
 
5046
5301
  /* eslint-disable no-unused-vars */
5047
5302
  /* export enum Kind {
@@ -12328,6 +12583,251 @@ function isLight(x) {
12328
12583
 
12329
12584
  /***/ }),
12330
12585
 
12586
+ /***/ "./lib/utils/cryptoKeyHelpers.js":
12587
+ /*!***************************************!*\
12588
+ !*** ./lib/utils/cryptoKeyHelpers.js ***!
12589
+ \***************************************/
12590
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
12591
+
12592
+ "use strict";
12593
+
12594
+
12595
+ var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js");
12596
+ var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
12597
+ Object.defineProperty(exports, "__esModule", ({
12598
+ value: true
12599
+ }));
12600
+ exports.privKeyUrl = void 0;
12601
+ exports.privateKeyExists = privateKeyExists;
12602
+ exports.pubKeyUrl = void 0;
12603
+ exports.publicKeyExists = publicKeyExists;
12604
+ var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"));
12605
+ var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
12606
+ var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js"));
12607
+ var _signature = __webpack_require__(/*! ../chat/signature */ "./lib/chat/signature.js");
12608
+ var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js");
12609
+ var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js"));
12610
+ 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); }
12611
+ 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; }
12612
+ var getPodRoot = /*#__PURE__*/function () {
12613
+ var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(webId) {
12614
+ var _podRoot;
12615
+ var webIdURL, storages, podRoot, path, _res$headers$get, res;
12616
+ return _regenerator["default"].wrap(function _callee$(_context) {
12617
+ while (1) switch (_context.prev = _context.next) {
12618
+ case 0:
12619
+ webIdURL = new URL(webId.uri); // find storages in webId document
12620
+ _context.next = 3;
12621
+ return _solidLogic.store.fetcher.load(webId.uri);
12622
+ case 3:
12623
+ storages = _solidLogic.store.each(webId, ns.space('storage'), null, webId.doc());
12624
+ if (storages !== null && storages !== void 0 && storages.length) {
12625
+ _context.next = 19;
12626
+ break;
12627
+ }
12628
+ // find storage recursively in webId URL
12629
+ path = webIdURL.pathname;
12630
+ case 6:
12631
+ if (!path.length) {
12632
+ _context.next = 17;
12633
+ break;
12634
+ }
12635
+ path = path.substring(0, path.lastIndexOf('/'));
12636
+ podRoot = _solidLogic.store.sym(webIdURL.origin + path + '/');
12637
+ _context.next = 11;
12638
+ return _solidLogic.store.fetcher.webOperation('HEAD', podRoot.uri);
12639
+ case 11:
12640
+ res = _context.sent;
12641
+ if (!((_res$headers$get = res.headers.get('link')) !== null && _res$headers$get !== void 0 && _res$headers$get.includes(ns.space('Storage').value))) {
12642
+ _context.next = 14;
12643
+ break;
12644
+ }
12645
+ return _context.abrupt("break", 17);
12646
+ case 14:
12647
+ if (!path) debug.warn("Current user storage not found for\n".concat(webId));
12648
+ _context.next = 6;
12649
+ break;
12650
+ case 17:
12651
+ _context.next = 21;
12652
+ break;
12653
+ case 19:
12654
+ // give preference to storage in webId root
12655
+ podRoot = storages.find(function (storage) {
12656
+ return webIdURL.origin === new URL(storage.value).origin;
12657
+ });
12658
+ if (!podRoot) podRoot = storages[0];
12659
+ case 21:
12660
+ return _context.abrupt("return", (_podRoot = podRoot) === null || _podRoot === void 0 ? void 0 : _podRoot.value);
12661
+ case 22:
12662
+ case "end":
12663
+ return _context.stop();
12664
+ }
12665
+ }, _callee);
12666
+ }));
12667
+ return function getPodRoot(_x) {
12668
+ return _ref.apply(this, arguments);
12669
+ };
12670
+ }();
12671
+ var pubKeyUrl = /*#__PURE__*/function () {
12672
+ var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(webId) {
12673
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
12674
+ while (1) switch (_context2.prev = _context2.next) {
12675
+ case 0:
12676
+ _context2.prev = 0;
12677
+ _context2.next = 3;
12678
+ return getPodRoot(webId);
12679
+ case 3:
12680
+ _context2.t0 = _context2.sent;
12681
+ return _context2.abrupt("return", _context2.t0 + 'profile/keys/publicKey.ttl');
12682
+ case 7:
12683
+ _context2.prev = 7;
12684
+ _context2.t1 = _context2["catch"](0);
12685
+ throw new Error(_context2.t1);
12686
+ case 10:
12687
+ case "end":
12688
+ return _context2.stop();
12689
+ }
12690
+ }, _callee2, null, [[0, 7]]);
12691
+ }));
12692
+ return function pubKeyUrl(_x2) {
12693
+ return _ref2.apply(this, arguments);
12694
+ };
12695
+ }();
12696
+ exports.pubKeyUrl = pubKeyUrl;
12697
+ function publicKeyExists(_x3) {
12698
+ return _publicKeyExists.apply(this, arguments);
12699
+ }
12700
+ function _publicKeyExists() {
12701
+ _publicKeyExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(webId) {
12702
+ var publicKeyUrl;
12703
+ return _regenerator["default"].wrap(function _callee4$(_context4) {
12704
+ while (1) switch (_context4.prev = _context4.next) {
12705
+ case 0:
12706
+ _context4.next = 2;
12707
+ return pubKeyUrl(webId);
12708
+ case 2:
12709
+ publicKeyUrl = _context4.sent;
12710
+ _context4.next = 5;
12711
+ return keyExists(webId, publicKeyUrl, 'PublicKey');
12712
+ case 5:
12713
+ return _context4.abrupt("return", _context4.sent);
12714
+ case 6:
12715
+ case "end":
12716
+ return _context4.stop();
12717
+ }
12718
+ }, _callee4);
12719
+ }));
12720
+ return _publicKeyExists.apply(this, arguments);
12721
+ }
12722
+ var privKeyUrl = /*#__PURE__*/function () {
12723
+ var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(webId) {
12724
+ return _regenerator["default"].wrap(function _callee3$(_context3) {
12725
+ while (1) switch (_context3.prev = _context3.next) {
12726
+ case 0:
12727
+ _context3.prev = 0;
12728
+ _context3.next = 3;
12729
+ return getPodRoot(webId);
12730
+ case 3:
12731
+ _context3.t0 = _context3.sent;
12732
+ return _context3.abrupt("return", _context3.t0 + 'profile/keys/privateKey.ttl');
12733
+ case 7:
12734
+ _context3.prev = 7;
12735
+ _context3.t1 = _context3["catch"](0);
12736
+ throw new Error(_context3.t1);
12737
+ case 10:
12738
+ case "end":
12739
+ return _context3.stop();
12740
+ }
12741
+ }, _callee3, null, [[0, 7]]);
12742
+ }));
12743
+ return function privKeyUrl(_x4) {
12744
+ return _ref3.apply(this, arguments);
12745
+ };
12746
+ }();
12747
+ exports.privKeyUrl = privKeyUrl;
12748
+ function privateKeyExists(_x5) {
12749
+ return _privateKeyExists.apply(this, arguments);
12750
+ }
12751
+ function _privateKeyExists() {
12752
+ _privateKeyExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(webId) {
12753
+ var privateKeyUrl;
12754
+ return _regenerator["default"].wrap(function _callee5$(_context5) {
12755
+ while (1) switch (_context5.prev = _context5.next) {
12756
+ case 0:
12757
+ _context5.next = 2;
12758
+ return privKeyUrl(webId);
12759
+ case 2:
12760
+ privateKeyUrl = _context5.sent;
12761
+ _context5.next = 5;
12762
+ return keyExists(webId, privateKeyUrl, 'PrivateKey');
12763
+ case 5:
12764
+ return _context5.abrupt("return", _context5.sent);
12765
+ case 6:
12766
+ case "end":
12767
+ return _context5.stop();
12768
+ }
12769
+ }, _callee5);
12770
+ }));
12771
+ return _privateKeyExists.apply(this, arguments);
12772
+ }
12773
+ function keyExists(_x6, _x7, _x8) {
12774
+ return _keyExists.apply(this, arguments);
12775
+ }
12776
+ function _keyExists() {
12777
+ _keyExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(webId, keyUrl, keyType) {
12778
+ var key, _err$response, data, contentType, response;
12779
+ return _regenerator["default"].wrap(function _callee6$(_context6) {
12780
+ while (1) switch (_context6.prev = _context6.next) {
12781
+ case 0:
12782
+ _context6.prev = 0;
12783
+ _context6.next = 3;
12784
+ return _solidLogic.store.fetcher.load(keyUrl);
12785
+ case 3:
12786
+ key = _solidLogic.store.any(webId, _solidLogic.store.sym(_signature.CERT + keyType));
12787
+ return _context6.abrupt("return", key === null || key === void 0 ? void 0 : key.value);
12788
+ case 7:
12789
+ _context6.prev = 7;
12790
+ _context6.t0 = _context6["catch"](0);
12791
+ 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)) {
12792
+ _context6.next = 24;
12793
+ break;
12794
+ }
12795
+ _context6.prev = 10;
12796
+ // create privateKey resource
12797
+ data = '';
12798
+ contentType = 'text/turtle';
12799
+ _context6.next = 15;
12800
+ return _solidLogic.store.fetcher.webOperation('PUT', keyUrl, {
12801
+ data: data,
12802
+ contentType: contentType
12803
+ });
12804
+ case 15:
12805
+ response = _context6.sent;
12806
+ _context6.next = 22;
12807
+ break;
12808
+ case 18:
12809
+ _context6.prev = 18;
12810
+ _context6.t1 = _context6["catch"](10);
12811
+ debug.log('createIfNotExists doc FAILED: ' + keyUrl + ': ' + _context6.t1);
12812
+ throw _context6.t1;
12813
+ case 22:
12814
+ delete _solidLogic.store.fetcher.requested[keyUrl]; // delete cached 404 error
12815
+ return _context6.abrupt("return", undefined);
12816
+ case 24:
12817
+ debug.log('createIfNotExists doc FAILED: ' + keyUrl + ': ' + _context6.t0);
12818
+ throw _context6.t0;
12819
+ case 26:
12820
+ case "end":
12821
+ return _context6.stop();
12822
+ }
12823
+ }, _callee6, null, [[0, 7], [10, 18]]);
12824
+ }));
12825
+ return _keyExists.apply(this, arguments);
12826
+ }
12827
+ //# sourceMappingURL=cryptoKeyHelpers.js.map
12828
+
12829
+ /***/ }),
12830
+
12331
12831
  /***/ "./lib/utils/headerFooterHelpers.js":
12332
12832
  /*!******************************************!*\
12333
12833
  !*** ./lib/utils/headerFooterHelpers.js ***!
@@ -13174,8 +13674,8 @@ Object.defineProperty(exports, "__esModule", ({
13174
13674
  }));
13175
13675
  exports.versionInfo = void 0;
13176
13676
  var versionInfo = {
13177
- buildTime: '2023-04-17T20:18:29Z',
13178
- commit: '109c494647e55d98f10d60fe5b5168e8704b3a8a',
13677
+ buildTime: '2023-05-06T21:42:04Z',
13678
+ commit: '17005e619868ccdb8e3bcdeb178376f49054d7c7',
13179
13679
  npmInfo: {
13180
13680
  'solid-ui': '2.4.27',
13181
13681
  npm: '8.19.4',
@@ -25338,6 +25838,8 @@ __webpack_require__.r(__webpack_exports__);
25338
25838
  /* 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
25839
  /* harmony import */ var _inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_inrupt_oidc_client__WEBPACK_IMPORTED_MODULE_0__);
25340
25840
  /* 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");
25841
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
25842
+
25341
25843
 
25342
25844
 
25343
25845
 
@@ -25491,7 +25993,7 @@ async function getTokens(issuer, client, data, dpop) {
25491
25993
  headers,
25492
25994
  body: new URLSearchParams(requestBody).toString(),
25493
25995
  };
25494
- const rawTokenResponse = await await fetch(issuer.tokenEndpoint, tokenRequestInit);
25996
+ const rawTokenResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, tokenRequestInit);
25495
25997
  const jsonTokenResponse = (await rawTokenResponse.json());
25496
25998
  const tokenResponse = validateTokenEndpointResponse(jsonTokenResponse, dpop);
25497
25999
  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 +26077,7 @@ async function refresh(refreshToken, issuer, client, dpopKey) {
25575
26077
  else if (isValidUrl(client.clientId)) {
25576
26078
  requestBody.client_id = client.clientId;
25577
26079
  }
25578
- const rawResponse = await fetch(issuer.tokenEndpoint, {
26080
+ const rawResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(issuer.tokenEndpoint, {
25579
26081
  method: "POST",
25580
26082
  body: new URLSearchParams(requestBody).toString(),
25581
26083
  headers: {
@@ -25690,8 +26192,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
26192
 
25691
26193
  Object.defineProperty(exports, "__esModule", ({ value: true }));
25692
26194
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26195
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
25693
26196
  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);
26197
+ const globalFetch = (request, init) => (0, universal_fetch_1.fetch)(request, init);
25695
26198
  class ClientAuthentication {
25696
26199
  constructor(loginHandler, redirectHandler, logoutHandler, sessionInfoManager, issuerConfigFetcher) {
25697
26200
  this.loginHandler = loginHandler;
@@ -26185,6 +26688,7 @@ exports["default"] = ClientRegistrar;
26185
26688
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26186
26689
  exports.WELL_KNOWN_OPENID_CONFIG = void 0;
26187
26690
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26691
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26188
26692
  exports.WELL_KNOWN_OPENID_CONFIG = ".well-known/openid-configuration";
26189
26693
  const issuerConfigKeyMap = {
26190
26694
  issuer: {
@@ -26291,7 +26795,7 @@ class IssuerConfigFetcher {
26291
26795
  async fetchConfig(issuer) {
26292
26796
  let issuerConfig;
26293
26797
  const openIdConfigUrl = new URL(exports.WELL_KNOWN_OPENID_CONFIG, issuer.endsWith("/") ? issuer : `${issuer}/`).href;
26294
- const issuerConfigRequestBody = await window.fetch(openIdConfigUrl);
26798
+ const issuerConfigRequestBody = await (0, universal_fetch_1.fetch)(openIdConfigUrl);
26295
26799
  try {
26296
26800
  issuerConfig = processConfig(await issuerConfigRequestBody.json());
26297
26801
  }
@@ -26394,6 +26898,7 @@ exports["default"] = Redirector;
26394
26898
 
26395
26899
  Object.defineProperty(exports, "__esModule", ({ value: true }));
26396
26900
  exports.AuthCodeRedirectHandler = void 0;
26901
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26397
26902
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26398
26903
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
26399
26904
  class AuthCodeRedirectHandler {
@@ -26457,7 +26962,7 @@ class AuthCodeRedirectHandler {
26457
26962
  tokenRefresher: this.tokerRefresher,
26458
26963
  };
26459
26964
  }
26460
- const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(fetch, tokens.accessToken, {
26965
+ const authFetch = await (0, solid_client_authn_core_1.buildAuthenticatedFetch)(universal_fetch_1.fetch, tokens.accessToken, {
26461
26966
  dpopKey: tokens.dpopKey,
26462
26967
  refreshOptions,
26463
26968
  eventEmitter,
@@ -26695,11 +27200,12 @@ exports.SessionInfoManager = exports.clear = exports.getUnauthenticatedSession =
26695
27200
  const solid_client_authn_core_1 = __webpack_require__(/*! @inrupt/solid-client-authn-core */ "./node_modules/@inrupt/solid-client-authn-core/dist/index.js");
26696
27201
  const uuid_1 = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-browser/node_modules/uuid/dist/commonjs-browser/index.js");
26697
27202
  const oidc_client_ext_1 = __webpack_require__(/*! @inrupt/oidc-client-ext */ "./node_modules/@inrupt/oidc-client-ext/dist/index.es.js");
27203
+ const universal_fetch_1 = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
26698
27204
  function getUnauthenticatedSession() {
26699
27205
  return {
26700
27206
  isLoggedIn: false,
26701
27207
  sessionId: (0, uuid_1.v4)(),
26702
- fetch,
27208
+ fetch: universal_fetch_1.fetch,
26703
27209
  };
26704
27210
  }
26705
27211
  exports.getUnauthenticatedSession = getUnauthenticatedSession;
@@ -27852,513 +28358,513 @@ exports["default"] = _default;
27852
28358
 
27853
28359
 
27854
28360
  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");
28361
+ var universalFetch = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js");
27856
28362
  var jose = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
27857
28363
  var uuid = __webpack_require__(/*! uuid */ "./node_modules/@inrupt/solid-client-authn-core/node_modules/uuid/dist/commonjs-browser/index.js");
27858
28364
 
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";
28365
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
28366
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
28367
+ const EVENTS = {
28368
+ ERROR: "error",
28369
+ LOGIN: "login",
28370
+ LOGOUT: "logout",
28371
+ NEW_REFRESH_TOKEN: "newRefreshToken",
28372
+ SESSION_EXPIRED: "sessionExpired",
28373
+ SESSION_EXTENDED: "sessionExtended",
28374
+ SESSION_RESTORED: "sessionRestore",
28375
+ TIMEOUT_SET: "timeoutSet",
28376
+ };
28377
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
28378
+ const SCOPE_OPENID = "openid";
28379
+ const SCOPE_OFFLINE = "offline_access";
28380
+ const SCOPE_WEBID = "webid";
27875
28381
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
27876
28382
 
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
- },
28383
+ const buildProxyHandler = (toExclude, errorMessage) => ({
28384
+ get(target, prop, receiver) {
28385
+ if (!Object.getOwnPropertyNames(events.EventEmitter).includes(prop) &&
28386
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
28387
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
28388
+ }
28389
+ return Reflect.get(target, prop, receiver);
28390
+ },
27885
28391
  });
27886
28392
 
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
- }
28393
+ class AggregateHandler {
28394
+ constructor(handleables) {
28395
+ this.handleables = handleables;
28396
+ }
28397
+ async getProperHandler(params) {
28398
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
28399
+ for (let i = 0; i < canHandleList.length; i += 1) {
28400
+ if (canHandleList[i]) {
28401
+ return this.handleables[i];
28402
+ }
28403
+ }
28404
+ return null;
28405
+ }
28406
+ async canHandle(...params) {
28407
+ return (await this.getProperHandler(params)) !== null;
28408
+ }
28409
+ async handle(...params) {
28410
+ const handler = await this.getProperHandler(params);
28411
+ if (handler) {
28412
+ return handler.handle(...params);
28413
+ }
28414
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
28415
+ .map((param) => {
28416
+ try {
28417
+ return JSON.stringify(param);
28418
+ }
28419
+ catch (err) {
28420
+ return param.toString();
28421
+ }
28422
+ })
28423
+ .join(", ")}`);
28424
+ }
27919
28425
  }
27920
28426
 
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
- }
28427
+ async function fetchJwks(jwksIri, issuerIri) {
28428
+ const jwksResponse = await universalFetch.fetch(jwksIri);
28429
+ if (jwksResponse.status !== 200) {
28430
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
28431
+ }
28432
+ let jwk;
28433
+ try {
28434
+ jwk = (await jwksResponse.json()).keys[0];
28435
+ }
28436
+ catch (e) {
28437
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
28438
+ }
28439
+ return jwk;
28440
+ }
28441
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
28442
+ const jwk = await fetchJwks(jwksIri, issuerIri);
28443
+ let payload;
28444
+ try {
28445
+ const { payload: verifiedPayload } = await jose.jwtVerify(idToken, await jose.importJWK(jwk), {
28446
+ issuer: issuerIri,
28447
+ audience: clientId,
28448
+ });
28449
+ payload = verifiedPayload;
28450
+ }
28451
+ catch (e) {
28452
+ throw new Error(`Token verification failed: ${e.stack}`);
28453
+ }
28454
+ if (typeof payload.webid === "string") {
28455
+ return payload.webid;
28456
+ }
28457
+ if (typeof payload.sub !== "string") {
28458
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
28459
+ }
28460
+ try {
28461
+ new URL(payload.sub);
28462
+ return payload.sub;
28463
+ }
28464
+ catch (e) {
28465
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
28466
+ }
27961
28467
  }
27962
28468
 
27963
- function isValidRedirectUrl(redirectUrl) {
27964
- try {
27965
- const urlObject = new URL(redirectUrl);
27966
- return urlObject.hash === "";
27967
- }
27968
- catch (e) {
27969
- return false;
27970
- }
28469
+ function isValidRedirectUrl(redirectUrl) {
28470
+ try {
28471
+ const urlObject = new URL(redirectUrl);
28472
+ return urlObject.hash === "";
28473
+ }
28474
+ catch (e) {
28475
+ return false;
28476
+ }
27971
28477
  }
27972
28478
 
27973
- function isSupportedTokenType(token) {
27974
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
28479
+ function isSupportedTokenType(token) {
28480
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
27975
28481
  }
27976
28482
 
27977
28483
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
27978
28484
 
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
- };
28485
+ function isValidUrl(url) {
28486
+ try {
28487
+ new URL(url);
28488
+ return true;
28489
+ }
28490
+ catch (_a) {
28491
+ return false;
28492
+ }
28493
+ }
28494
+ function determineSigningAlg(supported, preferred) {
28495
+ var _a;
28496
+ return ((_a = preferred.find((signingAlg) => {
28497
+ return supported.includes(signingAlg);
28498
+ })) !== null && _a !== void 0 ? _a : null);
28499
+ }
28500
+ function determineClientType(options, issuerConfig) {
28501
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
28502
+ return "static";
28503
+ }
28504
+ if (issuerConfig.scopesSupported.includes("webid") &&
28505
+ options.clientId !== undefined &&
28506
+ isValidUrl(options.clientId)) {
28507
+ return "solid-oidc";
28508
+ }
28509
+ return "dynamic";
28510
+ }
28511
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
28512
+ const clientType = determineClientType(options, issuerConfig);
28513
+ if (clientType === "dynamic") {
28514
+ return clientRegistrar.getClient({
28515
+ sessionId: options.sessionId,
28516
+ clientName: options.clientName,
28517
+ redirectUrl: options.redirectUrl,
28518
+ }, issuerConfig);
28519
+ }
28520
+ await storageUtility.setForUser(options.sessionId, {
28521
+ clientId: options.clientId,
28522
+ });
28523
+ if (options.clientSecret) {
28524
+ await storageUtility.setForUser(options.sessionId, {
28525
+ clientSecret: options.clientSecret,
28526
+ });
28527
+ }
28528
+ if (options.clientName) {
28529
+ await storageUtility.setForUser(options.sessionId, {
28530
+ clientName: options.clientName,
28531
+ });
28532
+ }
28533
+ return {
28534
+ clientId: options.clientId,
28535
+ clientSecret: options.clientSecret,
28536
+ clientName: options.clientName,
28537
+ clientType,
28538
+ };
28033
28539
  }
28034
28540
 
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
- }
28541
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
28542
+ return storageUtility.getForUser(oauthState, "sessionId");
28543
+ }
28544
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
28545
+ try {
28546
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
28547
+ storageUtility.getForUser(sessionId, "issuer", {
28548
+ errorIfNull: true,
28549
+ }),
28550
+ storageUtility.getForUser(sessionId, "codeVerifier"),
28551
+ storageUtility.getForUser(sessionId, "redirectUrl"),
28552
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
28553
+ ]);
28554
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
28555
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
28556
+ return {
28557
+ codeVerifier,
28558
+ redirectUrl: storedRedirectIri,
28559
+ issuerConfig,
28560
+ dpop: dpop === "true",
28561
+ };
28562
+ }
28563
+ catch (e) {
28564
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
28565
+ }
28566
+ }
28567
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
28568
+ if (refreshToken !== undefined) {
28569
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
28570
+ }
28571
+ if (webId !== undefined) {
28572
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
28573
+ }
28574
+ if (isLoggedIn !== undefined) {
28575
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
28576
+ }
28577
+ if (dpopKey !== undefined) {
28578
+ await storageUtility.setForUser(sessionId, {
28579
+ publicKey: JSON.stringify(dpopKey.publicKey),
28580
+ privateKey: JSON.stringify(await jose.exportJWK(dpopKey.privateKey)),
28581
+ }, { secure });
28582
+ }
28583
+ }
28584
+ class StorageUtility {
28585
+ constructor(secureStorage, insecureStorage) {
28586
+ this.secureStorage = secureStorage;
28587
+ this.insecureStorage = insecureStorage;
28588
+ }
28589
+ getKey(userId) {
28590
+ return `solidClientAuthenticationUser:${userId}`;
28591
+ }
28592
+ async getUserData(userId, secure) {
28593
+ const stored = await (secure
28594
+ ? this.secureStorage
28595
+ : this.insecureStorage).get(this.getKey(userId));
28596
+ if (stored === undefined) {
28597
+ return {};
28598
+ }
28599
+ try {
28600
+ return JSON.parse(stored);
28601
+ }
28602
+ catch (err) {
28603
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
28604
+ }
28605
+ }
28606
+ async setUserData(userId, data, secure) {
28607
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
28608
+ }
28609
+ async get(key, options) {
28610
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
28611
+ ? this.secureStorage
28612
+ : this.insecureStorage).get(key);
28613
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28614
+ throw new Error(`[${key}] is not stored`);
28615
+ }
28616
+ return value;
28617
+ }
28618
+ async set(key, value, options) {
28619
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
28620
+ }
28621
+ async delete(key, options) {
28622
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
28623
+ }
28624
+ async getForUser(userId, key, options) {
28625
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28626
+ let value;
28627
+ if (!userData || !userData[key]) {
28628
+ value = undefined;
28629
+ }
28630
+ value = userData[key];
28631
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
28632
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
28633
+ }
28634
+ return value || undefined;
28635
+ }
28636
+ async setForUser(userId, values, options) {
28637
+ let userData;
28638
+ try {
28639
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28640
+ }
28641
+ catch (_a) {
28642
+ userData = {};
28643
+ }
28644
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
28645
+ }
28646
+ async deleteForUser(userId, key, options) {
28647
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
28648
+ delete userData[key];
28649
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
28650
+ }
28651
+ async deleteAllUserData(userId, options) {
28652
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
28653
+ }
28148
28654
  }
28149
28655
 
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
- }
28656
+ class InMemoryStorage {
28657
+ constructor() {
28658
+ this.map = {};
28659
+ }
28660
+ async get(key) {
28661
+ return this.map[key] || undefined;
28662
+ }
28663
+ async set(key, value) {
28664
+ this.map[key] = value;
28665
+ }
28666
+ async delete(key) {
28667
+ delete this.map[key];
28668
+ }
28163
28669
  }
28164
28670
 
28165
- class ConfigurationError extends Error {
28166
- constructor(message) {
28167
- super(message);
28168
- }
28671
+ class ConfigurationError extends Error {
28672
+ constructor(message) {
28673
+ super(message);
28674
+ }
28169
28675
  }
28170
28676
 
28171
- class NotImplementedError extends Error {
28172
- constructor(methodName) {
28173
- super(`[${methodName}] is not implemented`);
28174
- }
28677
+ class NotImplementedError extends Error {
28678
+ constructor(methodName) {
28679
+ super(`[${methodName}] is not implemented`);
28680
+ }
28175
28681
  }
28176
28682
 
28177
- class InvalidResponseError extends Error {
28178
- constructor(missingFields) {
28179
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28180
- this.missingFields = missingFields;
28181
- }
28683
+ class InvalidResponseError extends Error {
28684
+ constructor(missingFields) {
28685
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
28686
+ this.missingFields = missingFields;
28687
+ }
28182
28688
  }
28183
28689
 
28184
- class OidcProviderError extends Error {
28185
- constructor(message, error, errorDescription) {
28186
- super(message);
28187
- this.error = error;
28188
- this.errorDescription = errorDescription;
28189
- }
28690
+ class OidcProviderError extends Error {
28691
+ constructor(message, error, errorDescription) {
28692
+ super(message);
28693
+ this.error = error;
28694
+ this.errorDescription = errorDescription;
28695
+ }
28190
28696
  }
28191
28697
 
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;
28698
+ function normalizeHTU(audience) {
28699
+ const audienceUrl = new URL(audience);
28700
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
28701
+ }
28702
+ async function createDpopHeader(audience, method, dpopKey) {
28703
+ return new jose.SignJWT({
28704
+ htu: normalizeHTU(audience),
28705
+ htm: method.toUpperCase(),
28706
+ jti: uuid.v4(),
28707
+ })
28708
+ .setProtectedHeader({
28709
+ alg: PREFERRED_SIGNING_ALG[0],
28710
+ jwk: dpopKey.publicKey,
28711
+ typ: "dpop+jwt",
28712
+ })
28713
+ .setIssuedAt()
28714
+ .sign(dpopKey.privateKey, {});
28715
+ }
28716
+ async function generateDpopKeyPair() {
28717
+ const { privateKey, publicKey } = await jose.generateKeyPair(PREFERRED_SIGNING_ALG[0]);
28718
+ const dpopKeyPair = {
28719
+ privateKey,
28720
+ publicKey: await jose.exportJWK(publicKey),
28721
+ };
28722
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
28723
+ return dpopKeyPair;
28218
28724
  }
28219
28725
 
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
- };
28726
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
28727
+ function isExpectedAuthError(statusCode) {
28728
+ return [401, 403].includes(statusCode);
28729
+ }
28730
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
28731
+ var _a;
28732
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28733
+ headers.set("Authorization", `DPoP ${authToken}`);
28734
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
28735
+ return {
28736
+ ...defaultOptions,
28737
+ headers,
28738
+ };
28739
+ }
28740
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
28741
+ if (dpopKey !== undefined) {
28742
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
28743
+ }
28744
+ const headers = new universalFetch.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
28745
+ headers.set("Authorization", `Bearer ${authToken}`);
28746
+ return {
28747
+ ...defaultOptions,
28748
+ headers,
28749
+ };
28750
+ }
28751
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
28752
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
28753
+ }
28754
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
28755
+ var _a;
28756
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
28757
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
28758
+ if (typeof tokenSet.refreshToken === "string") {
28759
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
28760
+ }
28761
+ return {
28762
+ accessToken: tokenSet.accessToken,
28763
+ refreshToken: tokenSet.refreshToken,
28764
+ expiresIn: tokenSet.expiresIn,
28765
+ };
28766
+ }
28767
+ const computeRefreshDelay = (expiresIn) => {
28768
+ if (expiresIn !== undefined) {
28769
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
28770
+ ?
28771
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
28772
+ : expiresIn;
28773
+ }
28774
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
28775
+ };
28776
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
28777
+ var _a;
28778
+ let currentAccessToken = accessToken;
28779
+ let latestTimeout;
28780
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
28781
+ if (currentRefreshOptions !== undefined) {
28782
+ const proactivelyRefreshToken = async () => {
28783
+ var _a, _b, _c, _d;
28784
+ try {
28785
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
28786
+ currentAccessToken = refreshedAccessToken;
28787
+ if (refreshToken !== undefined) {
28788
+ currentRefreshOptions.refreshToken = refreshToken;
28789
+ }
28790
+ clearTimeout(latestTimeout);
28791
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
28792
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28793
+ }
28794
+ catch (e) {
28795
+ if (e instanceof OidcProviderError) {
28796
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
28797
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
28798
+ }
28799
+ if (e instanceof InvalidResponseError &&
28800
+ e.missingFields.includes("access_token")) {
28801
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
28802
+ }
28803
+ }
28804
+ };
28805
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
28806
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
28807
+ }
28808
+ else if (options !== undefined && options.eventEmitter !== undefined) {
28809
+ const expirationTimeout = setTimeout(() => {
28810
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
28811
+ }, computeRefreshDelay(options.expiresIn) * 1000);
28812
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
28813
+ }
28814
+ return async (url, requestInit) => {
28815
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
28816
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
28817
+ if (response.ok || failedButNotExpectedAuthError) {
28818
+ return response;
28819
+ }
28820
+ const hasBeenRedirected = response.url !== url;
28821
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
28822
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
28823
+ }
28824
+ return response;
28825
+ };
28320
28826
  }
28321
28827
 
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));
28828
+ const StorageUtilityGetResponse = "getResponse";
28829
+ const StorageUtilityMock = {
28830
+ get: async (key, options) => StorageUtilityGetResponse,
28831
+ set: async (key, value) => {
28832
+ },
28833
+ delete: async (key) => {
28834
+ },
28835
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
28836
+ setForUser: async (userId, values, options) => {
28837
+ },
28838
+ deleteForUser: async (userId, key, options) => {
28839
+ },
28840
+ deleteAllUserData: async (userId, options) => {
28841
+ },
28842
+ };
28843
+ const mockStorage = (stored) => {
28844
+ const store = stored;
28845
+ return {
28846
+ get: async (key) => {
28847
+ if (store[key] === undefined) {
28848
+ return undefined;
28849
+ }
28850
+ if (typeof store[key] === "string") {
28851
+ return store[key];
28852
+ }
28853
+ return JSON.stringify(store[key]);
28854
+ },
28855
+ set: async (key, value) => {
28856
+ store[key] = value;
28857
+ },
28858
+ delete: async (key) => {
28859
+ delete store[key];
28860
+ },
28861
+ };
28862
+ };
28863
+ const mockStorageUtility = (stored, isSecure = false) => {
28864
+ if (isSecure) {
28865
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
28866
+ }
28867
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
28362
28868
  };
28363
28869
 
28364
28870
  exports.AggregateHandler = AggregateHandler;
@@ -29582,6 +30088,29 @@ function validate(uuid) {
29582
30088
 
29583
30089
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validate);
29584
30090
 
30091
+ /***/ }),
30092
+
30093
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.js":
30094
+ /*!********************************************************************!*\
30095
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.js ***!
30096
+ \********************************************************************/
30097
+ /***/ ((__unused_webpack_module, exports) => {
30098
+
30099
+ "use strict";
30100
+
30101
+
30102
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
30103
+
30104
+ var indexBrowser = globalThis.fetch;
30105
+ const { fetch, Response, Request, Headers } = globalThis;
30106
+
30107
+ exports.Headers = Headers;
30108
+ exports.Request = Request;
30109
+ exports.Response = Response;
30110
+ exports["default"] = indexBrowser;
30111
+ exports.fetch = fetch;
30112
+
30113
+
29585
30114
  /***/ }),
29586
30115
 
29587
30116
  /***/ "./node_modules/@noble/curves/_shortw_utils.js":
@@ -60226,522 +60755,545 @@ __webpack_require__.r(__webpack_exports__);
60226
60755
  /* harmony export */ "saveSessionInfoToStorage": () => (/* binding */ saveSessionInfoToStorage)
60227
60756
  /* harmony export */ });
60228
60757
  /* 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");
60758
+ /* harmony import */ var _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @inrupt/universal-fetch */ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs");
60759
+ /* harmony import */ var jose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jose */ "./node_modules/jose/dist/browser/index.js");
60231
60760
  /* 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
60761
 
60233
60762
 
60234
60763
 
60235
60764
 
60236
60765
 
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";
60766
+ const SOLID_CLIENT_AUTHN_KEY_PREFIX = "solidClientAuthn:";
60767
+ const PREFERRED_SIGNING_ALG = ["ES256", "RS256"];
60768
+ const EVENTS = {
60769
+ ERROR: "error",
60770
+ LOGIN: "login",
60771
+ LOGOUT: "logout",
60772
+ NEW_REFRESH_TOKEN: "newRefreshToken",
60773
+ SESSION_EXPIRED: "sessionExpired",
60774
+ SESSION_EXTENDED: "sessionExtended",
60775
+ SESSION_RESTORED: "sessionRestore",
60776
+ TIMEOUT_SET: "timeoutSet",
60777
+ };
60778
+ const REFRESH_BEFORE_EXPIRATION_SECONDS = 5;
60779
+ const SCOPE_OPENID = "openid";
60780
+ const SCOPE_OFFLINE = "offline_access";
60781
+ const SCOPE_WEBID = "webid";
60253
60782
  const DEFAULT_SCOPES = [SCOPE_OPENID, SCOPE_OFFLINE, SCOPE_WEBID].join(" ");
60254
60783
 
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
- },
60784
+ const buildProxyHandler = (toExclude, errorMessage) => ({
60785
+ get(target, prop, receiver) {
60786
+ if (!Object.getOwnPropertyNames(events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter).includes(prop) &&
60787
+ Object.getOwnPropertyNames(toExclude).includes(prop)) {
60788
+ throw new Error(`${errorMessage}: [${prop}] is not supported`);
60789
+ }
60790
+ return Reflect.get(target, prop, receiver);
60791
+ },
60263
60792
  });
60264
60793
 
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
- }
60794
+ class AggregateHandler {
60795
+ constructor(handleables) {
60796
+ this.handleables = handleables;
60797
+ }
60798
+ async getProperHandler(params) {
60799
+ const canHandleList = await Promise.all(this.handleables.map((handleable) => handleable.canHandle(...params)));
60800
+ for (let i = 0; i < canHandleList.length; i += 1) {
60801
+ if (canHandleList[i]) {
60802
+ return this.handleables[i];
60803
+ }
60804
+ }
60805
+ return null;
60806
+ }
60807
+ async canHandle(...params) {
60808
+ return (await this.getProperHandler(params)) !== null;
60809
+ }
60810
+ async handle(...params) {
60811
+ const handler = await this.getProperHandler(params);
60812
+ if (handler) {
60813
+ return handler.handle(...params);
60814
+ }
60815
+ throw new Error(`[${this.constructor.name}] cannot find a suitable handler for: ${params
60816
+ .map((param) => {
60817
+ try {
60818
+ return JSON.stringify(param);
60819
+ }
60820
+ catch (err) {
60821
+ return param.toString();
60822
+ }
60823
+ })
60824
+ .join(", ")}`);
60825
+ }
60297
60826
  }
60298
60827
 
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
- }
60828
+ async function fetchJwks(jwksIri, issuerIri) {
60829
+ const jwksResponse = await (0,_inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.fetch)(jwksIri);
60830
+ if (jwksResponse.status !== 200) {
60831
+ throw new Error(`Could not fetch JWKS for [${issuerIri}] at [${jwksIri}]: ${jwksResponse.status} ${jwksResponse.statusText}`);
60832
+ }
60833
+ let jwk;
60834
+ try {
60835
+ jwk = (await jwksResponse.json()).keys[0];
60836
+ }
60837
+ catch (e) {
60838
+ throw new Error(`Malformed JWKS for [${issuerIri}] at [${jwksIri}]: ${e.message}`);
60839
+ }
60840
+ return jwk;
60841
+ }
60842
+ async function getWebidFromTokenPayload(idToken, jwksIri, issuerIri, clientId) {
60843
+ const jwk = await fetchJwks(jwksIri, issuerIri);
60844
+ let payload;
60845
+ try {
60846
+ const { payload: verifiedPayload } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.jwtVerify)(idToken, await (0,jose__WEBPACK_IMPORTED_MODULE_1__.importJWK)(jwk), {
60847
+ issuer: issuerIri,
60848
+ audience: clientId,
60849
+ });
60850
+ payload = verifiedPayload;
60851
+ }
60852
+ catch (e) {
60853
+ throw new Error(`Token verification failed: ${e.stack}`);
60854
+ }
60855
+ if (typeof payload.webid === "string") {
60856
+ return payload.webid;
60857
+ }
60858
+ if (typeof payload.sub !== "string") {
60859
+ throw new Error(`The token ${JSON.stringify(payload)} is invalid: it has no 'webid' claim and no 'sub' claim.`);
60860
+ }
60861
+ try {
60862
+ new URL(payload.sub);
60863
+ return payload.sub;
60864
+ }
60865
+ catch (e) {
60866
+ throw new Error(`The token has no 'webid' claim, and its 'sub' claim of [${payload.sub}] is invalid as a URL - error [${e}].`);
60867
+ }
60339
60868
  }
60340
60869
 
60341
- function isValidRedirectUrl(redirectUrl) {
60342
- try {
60343
- const urlObject = new URL(redirectUrl);
60344
- return urlObject.hash === "";
60345
- }
60346
- catch (e) {
60347
- return false;
60348
- }
60870
+ function isValidRedirectUrl(redirectUrl) {
60871
+ try {
60872
+ const urlObject = new URL(redirectUrl);
60873
+ return urlObject.hash === "";
60874
+ }
60875
+ catch (e) {
60876
+ return false;
60877
+ }
60349
60878
  }
60350
60879
 
60351
- function isSupportedTokenType(token) {
60352
- return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60880
+ function isSupportedTokenType(token) {
60881
+ return typeof token === "string" && ["DPoP", "Bearer"].includes(token);
60353
60882
  }
60354
60883
 
60355
60884
  const USER_SESSION_PREFIX = "solidClientAuthenticationUser";
60356
60885
 
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
- };
60886
+ function isValidUrl(url) {
60887
+ try {
60888
+ new URL(url);
60889
+ return true;
60890
+ }
60891
+ catch (_a) {
60892
+ return false;
60893
+ }
60894
+ }
60895
+ function determineSigningAlg(supported, preferred) {
60896
+ var _a;
60897
+ return ((_a = preferred.find((signingAlg) => {
60898
+ return supported.includes(signingAlg);
60899
+ })) !== null && _a !== void 0 ? _a : null);
60900
+ }
60901
+ function determineClientType(options, issuerConfig) {
60902
+ if (options.clientId !== undefined && !isValidUrl(options.clientId)) {
60903
+ return "static";
60904
+ }
60905
+ if (issuerConfig.scopesSupported.includes("webid") &&
60906
+ options.clientId !== undefined &&
60907
+ isValidUrl(options.clientId)) {
60908
+ return "solid-oidc";
60909
+ }
60910
+ return "dynamic";
60911
+ }
60912
+ async function handleRegistration(options, issuerConfig, storageUtility, clientRegistrar) {
60913
+ const clientType = determineClientType(options, issuerConfig);
60914
+ if (clientType === "dynamic") {
60915
+ return clientRegistrar.getClient({
60916
+ sessionId: options.sessionId,
60917
+ clientName: options.clientName,
60918
+ redirectUrl: options.redirectUrl,
60919
+ }, issuerConfig);
60920
+ }
60921
+ await storageUtility.setForUser(options.sessionId, {
60922
+ clientId: options.clientId,
60923
+ });
60924
+ if (options.clientSecret) {
60925
+ await storageUtility.setForUser(options.sessionId, {
60926
+ clientSecret: options.clientSecret,
60927
+ });
60928
+ }
60929
+ if (options.clientName) {
60930
+ await storageUtility.setForUser(options.sessionId, {
60931
+ clientName: options.clientName,
60932
+ });
60933
+ }
60934
+ return {
60935
+ clientId: options.clientId,
60936
+ clientSecret: options.clientSecret,
60937
+ clientName: options.clientName,
60938
+ clientType,
60939
+ };
60411
60940
  }
60412
60941
 
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
- }
60942
+ async function getSessionIdFromOauthState(storageUtility, oauthState) {
60943
+ return storageUtility.getForUser(oauthState, "sessionId");
60944
+ }
60945
+ async function loadOidcContextFromStorage(sessionId, storageUtility, configFetcher) {
60946
+ try {
60947
+ const [issuerIri, codeVerifier, storedRedirectIri, dpop] = await Promise.all([
60948
+ storageUtility.getForUser(sessionId, "issuer", {
60949
+ errorIfNull: true,
60950
+ }),
60951
+ storageUtility.getForUser(sessionId, "codeVerifier"),
60952
+ storageUtility.getForUser(sessionId, "redirectUrl"),
60953
+ storageUtility.getForUser(sessionId, "dpop", { errorIfNull: true }),
60954
+ ]);
60955
+ await storageUtility.deleteForUser(sessionId, "codeVerifier");
60956
+ const issuerConfig = await configFetcher.fetchConfig(issuerIri);
60957
+ return {
60958
+ codeVerifier,
60959
+ redirectUrl: storedRedirectIri,
60960
+ issuerConfig,
60961
+ dpop: dpop === "true",
60962
+ };
60963
+ }
60964
+ catch (e) {
60965
+ throw new Error(`Failed to retrieve OIDC context from storage associated with session [${sessionId}]: ${e}`);
60966
+ }
60967
+ }
60968
+ async function saveSessionInfoToStorage(storageUtility, sessionId, webId, isLoggedIn, refreshToken, secure, dpopKey) {
60969
+ if (refreshToken !== undefined) {
60970
+ await storageUtility.setForUser(sessionId, { refreshToken }, { secure });
60971
+ }
60972
+ if (webId !== undefined) {
60973
+ await storageUtility.setForUser(sessionId, { webId }, { secure });
60974
+ }
60975
+ if (isLoggedIn !== undefined) {
60976
+ await storageUtility.setForUser(sessionId, { isLoggedIn }, { secure });
60977
+ }
60978
+ if (dpopKey !== undefined) {
60979
+ await storageUtility.setForUser(sessionId, {
60980
+ publicKey: JSON.stringify(dpopKey.publicKey),
60981
+ privateKey: JSON.stringify(await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(dpopKey.privateKey)),
60982
+ }, { secure });
60983
+ }
60984
+ }
60985
+ class StorageUtility {
60986
+ constructor(secureStorage, insecureStorage) {
60987
+ this.secureStorage = secureStorage;
60988
+ this.insecureStorage = insecureStorage;
60989
+ }
60990
+ getKey(userId) {
60991
+ return `solidClientAuthenticationUser:${userId}`;
60992
+ }
60993
+ async getUserData(userId, secure) {
60994
+ const stored = await (secure
60995
+ ? this.secureStorage
60996
+ : this.insecureStorage).get(this.getKey(userId));
60997
+ if (stored === undefined) {
60998
+ return {};
60999
+ }
61000
+ try {
61001
+ return JSON.parse(stored);
61002
+ }
61003
+ catch (err) {
61004
+ throw new Error(`Data for user [${userId}] in [${secure ? "secure" : "unsecure"}] storage is corrupted - expected valid JSON, but got: ${stored}`);
61005
+ }
61006
+ }
61007
+ async setUserData(userId, data, secure) {
61008
+ await (secure ? this.secureStorage : this.insecureStorage).set(this.getKey(userId), JSON.stringify(data));
61009
+ }
61010
+ async get(key, options) {
61011
+ const value = await ((options === null || options === void 0 ? void 0 : options.secure)
61012
+ ? this.secureStorage
61013
+ : this.insecureStorage).get(key);
61014
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
61015
+ throw new Error(`[${key}] is not stored`);
61016
+ }
61017
+ return value;
61018
+ }
61019
+ async set(key, value, options) {
61020
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).set(key, value);
61021
+ }
61022
+ async delete(key, options) {
61023
+ return ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(key);
61024
+ }
61025
+ async getForUser(userId, key, options) {
61026
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61027
+ let value;
61028
+ if (!userData || !userData[key]) {
61029
+ value = undefined;
61030
+ }
61031
+ value = userData[key];
61032
+ if (value === undefined && (options === null || options === void 0 ? void 0 : options.errorIfNull)) {
61033
+ throw new Error(`Field [${key}] for user [${userId}] is not stored`);
61034
+ }
61035
+ return value || undefined;
61036
+ }
61037
+ async setForUser(userId, values, options) {
61038
+ let userData;
61039
+ try {
61040
+ userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61041
+ }
61042
+ catch (_a) {
61043
+ userData = {};
61044
+ }
61045
+ await this.setUserData(userId, { ...userData, ...values }, options === null || options === void 0 ? void 0 : options.secure);
61046
+ }
61047
+ async deleteForUser(userId, key, options) {
61048
+ const userData = await this.getUserData(userId, options === null || options === void 0 ? void 0 : options.secure);
61049
+ delete userData[key];
61050
+ await this.setUserData(userId, userData, options === null || options === void 0 ? void 0 : options.secure);
61051
+ }
61052
+ async deleteAllUserData(userId, options) {
61053
+ await ((options === null || options === void 0 ? void 0 : options.secure) ? this.secureStorage : this.insecureStorage).delete(this.getKey(userId));
61054
+ }
60526
61055
  }
60527
61056
 
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
- }
61057
+ class InMemoryStorage {
61058
+ constructor() {
61059
+ this.map = {};
61060
+ }
61061
+ async get(key) {
61062
+ return this.map[key] || undefined;
61063
+ }
61064
+ async set(key, value) {
61065
+ this.map[key] = value;
61066
+ }
61067
+ async delete(key) {
61068
+ delete this.map[key];
61069
+ }
60541
61070
  }
60542
61071
 
60543
- class ConfigurationError extends Error {
60544
- constructor(message) {
60545
- super(message);
60546
- }
61072
+ class ConfigurationError extends Error {
61073
+ constructor(message) {
61074
+ super(message);
61075
+ }
60547
61076
  }
60548
61077
 
60549
- class NotImplementedError extends Error {
60550
- constructor(methodName) {
60551
- super(`[${methodName}] is not implemented`);
60552
- }
61078
+ class NotImplementedError extends Error {
61079
+ constructor(methodName) {
61080
+ super(`[${methodName}] is not implemented`);
61081
+ }
60553
61082
  }
60554
61083
 
60555
- class InvalidResponseError extends Error {
60556
- constructor(missingFields) {
60557
- super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
60558
- this.missingFields = missingFields;
60559
- }
61084
+ class InvalidResponseError extends Error {
61085
+ constructor(missingFields) {
61086
+ super(`Invalid response from OIDC provider: missing fields ${missingFields}`);
61087
+ this.missingFields = missingFields;
61088
+ }
60560
61089
  }
60561
61090
 
60562
- class OidcProviderError extends Error {
60563
- constructor(message, error, errorDescription) {
60564
- super(message);
60565
- this.error = error;
60566
- this.errorDescription = errorDescription;
60567
- }
61091
+ class OidcProviderError extends Error {
61092
+ constructor(message, error, errorDescription) {
61093
+ super(message);
61094
+ this.error = error;
61095
+ this.errorDescription = errorDescription;
61096
+ }
60568
61097
  }
60569
61098
 
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;
61099
+ function normalizeHTU(audience) {
61100
+ const audienceUrl = new URL(audience);
61101
+ return new URL(audienceUrl.pathname, audienceUrl.origin).toString();
61102
+ }
61103
+ async function createDpopHeader(audience, method, dpopKey) {
61104
+ return new jose__WEBPACK_IMPORTED_MODULE_1__.SignJWT({
61105
+ htu: normalizeHTU(audience),
61106
+ htm: method.toUpperCase(),
61107
+ jti: (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])(),
61108
+ })
61109
+ .setProtectedHeader({
61110
+ alg: PREFERRED_SIGNING_ALG[0],
61111
+ jwk: dpopKey.publicKey,
61112
+ typ: "dpop+jwt",
61113
+ })
61114
+ .setIssuedAt()
61115
+ .sign(dpopKey.privateKey, {});
61116
+ }
61117
+ async function generateDpopKeyPair() {
61118
+ const { privateKey, publicKey } = await (0,jose__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)(PREFERRED_SIGNING_ALG[0]);
61119
+ const dpopKeyPair = {
61120
+ privateKey,
61121
+ publicKey: await (0,jose__WEBPACK_IMPORTED_MODULE_1__.exportJWK)(publicKey),
61122
+ };
61123
+ [dpopKeyPair.publicKey.alg] = PREFERRED_SIGNING_ALG;
61124
+ return dpopKeyPair;
60596
61125
  }
60597
61126
 
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
- };
61127
+ const DEFAULT_EXPIRATION_TIME_SECONDS = 600;
61128
+ function isExpectedAuthError(statusCode) {
61129
+ return [401, 403].includes(statusCode);
61130
+ }
61131
+ async function buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions) {
61132
+ var _a;
61133
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
61134
+ headers.set("Authorization", `DPoP ${authToken}`);
61135
+ headers.set("DPoP", await createDpopHeader(targetUrl, (_a = defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.method) !== null && _a !== void 0 ? _a : "get", dpopKey));
61136
+ return {
61137
+ ...defaultOptions,
61138
+ headers,
61139
+ };
61140
+ }
61141
+ async function buildAuthenticatedHeaders(targetUrl, authToken, dpopKey, defaultOptions) {
61142
+ if (dpopKey !== undefined) {
61143
+ return buildDpopFetchOptions(targetUrl, authToken, dpopKey, defaultOptions);
61144
+ }
61145
+ const headers = new _inrupt_universal_fetch__WEBPACK_IMPORTED_MODULE_2__.Headers(defaultOptions === null || defaultOptions === void 0 ? void 0 : defaultOptions.headers);
61146
+ headers.set("Authorization", `Bearer ${authToken}`);
61147
+ return {
61148
+ ...defaultOptions,
61149
+ headers,
61150
+ };
61151
+ }
61152
+ async function makeAuthenticatedRequest(unauthFetch, accessToken, url, defaultRequestInit, dpopKey) {
61153
+ return unauthFetch(url, await buildAuthenticatedHeaders(url.toString(), accessToken, dpopKey, defaultRequestInit));
61154
+ }
61155
+ async function refreshAccessToken(refreshOptions, dpopKey, eventEmitter) {
61156
+ var _a;
61157
+ const tokenSet = await refreshOptions.tokenRefresher.refresh(refreshOptions.sessionId, refreshOptions.refreshToken, dpopKey);
61158
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.SESSION_EXTENDED, (_a = tokenSet.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRATION_TIME_SECONDS);
61159
+ if (typeof tokenSet.refreshToken === "string") {
61160
+ eventEmitter === null || eventEmitter === void 0 ? void 0 : eventEmitter.emit(EVENTS.NEW_REFRESH_TOKEN, tokenSet.refreshToken);
61161
+ }
61162
+ return {
61163
+ accessToken: tokenSet.accessToken,
61164
+ refreshToken: tokenSet.refreshToken,
61165
+ expiresIn: tokenSet.expiresIn,
61166
+ };
61167
+ }
61168
+ const computeRefreshDelay = (expiresIn) => {
61169
+ if (expiresIn !== undefined) {
61170
+ return expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS > 0
61171
+ ?
61172
+ expiresIn - REFRESH_BEFORE_EXPIRATION_SECONDS
61173
+ : expiresIn;
61174
+ }
61175
+ return DEFAULT_EXPIRATION_TIME_SECONDS;
61176
+ };
61177
+ async function buildAuthenticatedFetch(unauthFetch, accessToken, options) {
61178
+ var _a;
61179
+ let currentAccessToken = accessToken;
61180
+ let latestTimeout;
61181
+ const currentRefreshOptions = options === null || options === void 0 ? void 0 : options.refreshOptions;
61182
+ if (currentRefreshOptions !== undefined) {
61183
+ const proactivelyRefreshToken = async () => {
61184
+ var _a, _b, _c, _d;
61185
+ try {
61186
+ const { accessToken: refreshedAccessToken, refreshToken, expiresIn, } = await refreshAccessToken(currentRefreshOptions, options.dpopKey, options.eventEmitter);
61187
+ currentAccessToken = refreshedAccessToken;
61188
+ if (refreshToken !== undefined) {
61189
+ currentRefreshOptions.refreshToken = refreshToken;
61190
+ }
61191
+ clearTimeout(latestTimeout);
61192
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(expiresIn) * 1000);
61193
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
61194
+ }
61195
+ catch (e) {
61196
+ if (e instanceof OidcProviderError) {
61197
+ (_b = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _b === void 0 ? void 0 : _b.emit(EVENTS.ERROR, e.error, e.errorDescription);
61198
+ (_c = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _c === void 0 ? void 0 : _c.emit(EVENTS.SESSION_EXPIRED);
61199
+ }
61200
+ if (e instanceof InvalidResponseError &&
61201
+ e.missingFields.includes("access_token")) {
61202
+ (_d = options === null || options === void 0 ? void 0 : options.eventEmitter) === null || _d === void 0 ? void 0 : _d.emit(EVENTS.SESSION_EXPIRED);
61203
+ }
61204
+ }
61205
+ };
61206
+ latestTimeout = setTimeout(proactivelyRefreshToken, computeRefreshDelay(options.expiresIn) * 1000);
61207
+ (_a = options.eventEmitter) === null || _a === void 0 ? void 0 : _a.emit(EVENTS.TIMEOUT_SET, latestTimeout);
61208
+ }
61209
+ else if (options !== undefined && options.eventEmitter !== undefined) {
61210
+ const expirationTimeout = setTimeout(() => {
61211
+ options.eventEmitter.emit(EVENTS.SESSION_EXPIRED);
61212
+ }, computeRefreshDelay(options.expiresIn) * 1000);
61213
+ options.eventEmitter.emit(EVENTS.TIMEOUT_SET, expirationTimeout);
61214
+ }
61215
+ return async (url, requestInit) => {
61216
+ let response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, url, requestInit, options === null || options === void 0 ? void 0 : options.dpopKey);
61217
+ const failedButNotExpectedAuthError = !response.ok && !isExpectedAuthError(response.status);
61218
+ if (response.ok || failedButNotExpectedAuthError) {
61219
+ return response;
61220
+ }
61221
+ const hasBeenRedirected = response.url !== url;
61222
+ if (hasBeenRedirected && (options === null || options === void 0 ? void 0 : options.dpopKey) !== undefined) {
61223
+ response = await makeAuthenticatedRequest(unauthFetch, currentAccessToken, response.url, requestInit, options.dpopKey);
61224
+ }
61225
+ return response;
61226
+ };
60698
61227
  }
60699
61228
 
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));
61229
+ const StorageUtilityGetResponse = "getResponse";
61230
+ const StorageUtilityMock = {
61231
+ get: async (key, options) => StorageUtilityGetResponse,
61232
+ set: async (key, value) => {
61233
+ },
61234
+ delete: async (key) => {
61235
+ },
61236
+ getForUser: async (userId, key, options) => StorageUtilityGetResponse,
61237
+ setForUser: async (userId, values, options) => {
61238
+ },
61239
+ deleteForUser: async (userId, key, options) => {
61240
+ },
61241
+ deleteAllUserData: async (userId, options) => {
61242
+ },
61243
+ };
61244
+ const mockStorage = (stored) => {
61245
+ const store = stored;
61246
+ return {
61247
+ get: async (key) => {
61248
+ if (store[key] === undefined) {
61249
+ return undefined;
61250
+ }
61251
+ if (typeof store[key] === "string") {
61252
+ return store[key];
61253
+ }
61254
+ return JSON.stringify(store[key]);
61255
+ },
61256
+ set: async (key, value) => {
61257
+ store[key] = value;
61258
+ },
61259
+ delete: async (key) => {
61260
+ delete store[key];
61261
+ },
61262
+ };
61263
+ };
61264
+ const mockStorageUtility = (stored, isSecure = false) => {
61265
+ if (isSecure) {
61266
+ return new StorageUtility(mockStorage(stored), mockStorage({}));
61267
+ }
61268
+ return new StorageUtility(mockStorage({}), mockStorage(stored));
60740
61269
  };
60741
61270
 
60742
61271
 
60743
61272
 
60744
61273
 
61274
+ /***/ }),
61275
+
61276
+ /***/ "./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs":
61277
+ /*!*********************************************************************!*\
61278
+ !*** ./node_modules/@inrupt/universal-fetch/dist/index-browser.mjs ***!
61279
+ \*********************************************************************/
61280
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
61281
+
61282
+ "use strict";
61283
+ __webpack_require__.r(__webpack_exports__);
61284
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
61285
+ /* harmony export */ "Headers": () => (/* binding */ Headers),
61286
+ /* harmony export */ "Request": () => (/* binding */ Request),
61287
+ /* harmony export */ "Response": () => (/* binding */ Response),
61288
+ /* harmony export */ "default": () => (/* binding */ indexBrowser),
61289
+ /* harmony export */ "fetch": () => (/* binding */ fetch)
61290
+ /* harmony export */ });
61291
+ var indexBrowser = globalThis.fetch;
61292
+ const { fetch, Response, Request, Headers } = globalThis;
61293
+
61294
+
61295
+
61296
+
60745
61297
  /***/ }),
60746
61298
 
60747
61299
  /***/ "./node_modules/jose/dist/browser/index.js":
@@ -61809,14 +62361,17 @@ __webpack_require__.r(__webpack_exports__);
61809
62361
  /* harmony export */ "createRemoteJWKSet": () => (/* binding */ createRemoteJWKSet)
61810
62362
  /* harmony export */ });
61811
62363
  /* 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
-
62364
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
62365
+ /* harmony import */ var _local_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./local.js */ "./node_modules/jose/dist/browser/jwks/local.js");
61816
62366
 
61817
62367
 
61818
62368
 
61819
- class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
62369
+ function isCloudflareWorkers() {
62370
+ return (typeof WebSocketPair !== 'undefined' ||
62371
+ (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
62372
+ (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
62373
+ }
62374
+ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_2__.LocalJWKSet {
61820
62375
  constructor(url, options) {
61821
62376
  super({ keys: [] });
61822
62377
  this._jwks = undefined;
@@ -61849,7 +62404,7 @@ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
61849
62404
  return await super.getKey(protectedHeader, token);
61850
62405
  }
61851
62406
  catch (err) {
61852
- if (err instanceof _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JWKSNoMatchingKey) {
62407
+ if (err instanceof _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JWKSNoMatchingKey) {
61853
62408
  if (this.coolingDown() === false) {
61854
62409
  await this.reload();
61855
62410
  return super.getKey(protectedHeader, token);
@@ -61859,13 +62414,13 @@ class RemoteJWKSet extends _local_js__WEBPACK_IMPORTED_MODULE_3__.LocalJWKSet {
61859
62414
  }
61860
62415
  }
61861
62416
  async reload() {
61862
- if (this._pendingFetch && (0,_runtime_env_js__WEBPACK_IMPORTED_MODULE_1__.isCloudflareWorkers)()) {
62417
+ if (this._pendingFetch && isCloudflareWorkers()) {
61863
62418
  this._pendingFetch = undefined;
61864
62419
  }
61865
62420
  this._pendingFetch || (this._pendingFetch = (0,_runtime_fetch_jwks_js__WEBPACK_IMPORTED_MODULE_0__["default"])(this._url, this._timeoutDuration, this._options)
61866
62421
  .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');
62422
+ if (!(0,_local_js__WEBPACK_IMPORTED_MODULE_2__.isJWKSLike)(json)) {
62423
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JWKSInvalid('JSON Web Key Set malformed');
61869
62424
  }
61870
62425
  this._jwks = { keys: json.keys };
61871
62426
  this._jwksTimestamp = Date.now();
@@ -63053,8 +63608,6 @@ __webpack_require__.r(__webpack_exports__);
63053
63608
  /* harmony export */ "checkEncCryptoKey": () => (/* binding */ checkEncCryptoKey),
63054
63609
  /* harmony export */ "checkSigCryptoKey": () => (/* binding */ checkSigCryptoKey)
63055
63610
  /* 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
63611
  function unusable(name, prop = 'algorithm.name') {
63059
63612
  return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
63060
63613
  }
@@ -63129,11 +63682,6 @@ function checkSigCryptoKey(key, alg, ...usages) {
63129
63682
  }
63130
63683
  case 'EdDSA': {
63131
63684
  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
63685
  throw unusable('Ed25519 or Ed448');
63138
63686
  }
63139
63687
  break;
@@ -63964,14 +64512,12 @@ __webpack_require__.r(__webpack_exports__);
63964
64512
  /* harmony export */ "toPKCS8": () => (/* binding */ toPKCS8),
63965
64513
  /* harmony export */ "toSPKI": () => (/* binding */ toSPKI)
63966
64514
  /* 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
-
64515
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
64516
+ /* 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");
64517
+ /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
64518
+ /* 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");
64519
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
64520
+ /* 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
64521
 
63976
64522
 
63977
64523
 
@@ -63979,8 +64525,8 @@ __webpack_require__.r(__webpack_exports__);
63979
64525
 
63980
64526
 
63981
64527
  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));
64528
+ if (!(0,_webcrypto_js__WEBPACK_IMPORTED_MODULE_0__.isCryptoKey)(key)) {
64529
+ 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
64530
  }
63985
64531
  if (!key.extractable) {
63986
64532
  throw new TypeError('CryptoKey is not extractable');
@@ -63988,7 +64534,7 @@ const genericExport = async (keyType, keyFormat, key) => {
63988
64534
  if (key.type !== keyType) {
63989
64535
  throw new TypeError(`key is not a ${keyType} key`);
63990
64536
  }
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`);
64537
+ 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
64538
  };
63993
64539
  const toSPKI = (key) => {
63994
64540
  return genericExport('public', 'spki', key);
@@ -64026,11 +64572,11 @@ const getNamedCurve = (keyData) => {
64026
64572
  case findOid(keyData, [0x2b, 0x65, 0x71]):
64027
64573
  return 'Ed448';
64028
64574
  default:
64029
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_5__.JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');
64575
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_4__.JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');
64030
64576
  }
64031
64577
  };
64032
64578
  const genericImport = async (replace, keyFormat, pem, alg, options) => {
64033
- var _a, _b;
64579
+ var _a;
64034
64580
  let algorithm;
64035
64581
  let keyUsages;
64036
64582
  const keyData = new Uint8Array(atob(pem.replace(replace, ''))
@@ -64086,20 +64632,9 @@ const genericImport = async (replace, keyFormat, pem, alg, options) => {
64086
64632
  keyUsages = isPublic ? ['verify'] : ['sign'];
64087
64633
  break;
64088
64634
  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;
64635
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_4__.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
64102
64636
  }
64637
+ 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
64638
  };
64104
64639
  const fromPKCS8 = (pem, alg, options) => {
64105
64640
  return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options);
@@ -64168,12 +64703,12 @@ function parseElement(bytes) {
64168
64703
  }
64169
64704
  function spkiFromX509(buf) {
64170
64705
  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);
64706
+ return (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.encodeBase64)(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);
64172
64707
  }
64173
64708
  function getSPKI(x509) {
64174
64709
  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');
64710
+ const raw = (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.decodeBase64)(pem);
64711
+ return (0,_lib_format_pem_js__WEBPACK_IMPORTED_MODULE_3__["default"])(spkiFromX509(raw), 'PUBLIC KEY');
64177
64712
  }
64178
64713
  const fromX509 = (pem, alg, options) => {
64179
64714
  let spki;
@@ -64601,26 +65136,6 @@ const encrypt = async (enc, plaintext, cek, iv, aad) => {
64601
65136
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (encrypt);
64602
65137
 
64603
65138
 
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
65139
  /***/ }),
64625
65140
 
64626
65141
  /***/ "./node_modules/jose/dist/browser/runtime/fetch_jwks.js":
@@ -64685,11 +65200,9 @@ __webpack_require__.r(__webpack_exports__);
64685
65200
  /* harmony export */ "generateKeyPair": () => (/* binding */ generateKeyPair),
64686
65201
  /* harmony export */ "generateSecret": () => (/* binding */ generateSecret)
64687
65202
  /* 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
-
65203
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
65204
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65205
+ /* harmony import */ var _random_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./random.js */ "./node_modules/jose/dist/browser/runtime/random.js");
64693
65206
 
64694
65207
 
64695
65208
 
@@ -64710,7 +65223,7 @@ async function generateSecret(alg, options) {
64710
65223
  case 'A192CBC-HS384':
64711
65224
  case 'A256CBC-HS512':
64712
65225
  length = parseInt(alg.slice(-3), 10);
64713
- return (0,_random_js__WEBPACK_IMPORTED_MODULE_3__["default"])(new Uint8Array(length >> 3));
65226
+ return (0,_random_js__WEBPACK_IMPORTED_MODULE_2__["default"])(new Uint8Array(length >> 3));
64714
65227
  case 'A128KW':
64715
65228
  case 'A192KW':
64716
65229
  case 'A256KW':
@@ -64729,20 +65242,20 @@ async function generateSecret(alg, options) {
64729
65242
  keyUsages = ['encrypt', 'decrypt'];
64730
65243
  break;
64731
65244
  default:
64732
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65245
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64733
65246
  }
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);
65247
+ 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
65248
  }
64736
65249
  function getModulusLengthOption(options) {
64737
65250
  var _a;
64738
65251
  const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048;
64739
65252
  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');
65253
+ 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
65254
  }
64742
65255
  return modulusLength;
64743
65256
  }
64744
65257
  async function generateKeyPair(alg, options) {
64745
- var _a, _b, _c, _d;
65258
+ var _a, _b, _c;
64746
65259
  let algorithm;
64747
65260
  let keyUsages;
64748
65261
  switch (alg) {
@@ -64801,7 +65314,7 @@ async function generateKeyPair(alg, options) {
64801
65314
  algorithm = { name: crv };
64802
65315
  break;
64803
65316
  default:
64804
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported crv option provided');
65317
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported crv option provided');
64805
65318
  }
64806
65319
  break;
64807
65320
  case 'ECDH-ES':
@@ -64822,25 +65335,14 @@ async function generateKeyPair(alg, options) {
64822
65335
  algorithm = { name: crv };
64823
65336
  break;
64824
65337
  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');
65338
+ 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
65339
  }
64827
65340
  break;
64828
65341
  }
64829
65342
  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;
65343
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64843
65344
  }
65345
+ 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
65346
  }
64845
65347
 
64846
65348
 
@@ -64915,11 +65417,9 @@ __webpack_require__.r(__webpack_exports__);
64915
65417
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
64916
65418
  /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
64917
65419
  /* 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
-
65420
+ /* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/jose/dist/browser/runtime/webcrypto.js");
65421
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65422
+ /* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/jose/dist/browser/runtime/base64url.js");
64923
65423
 
64924
65424
 
64925
65425
 
@@ -64938,7 +65438,7 @@ function subtleMapping(jwk) {
64938
65438
  case 'A128CBC-HS256':
64939
65439
  case 'A192CBC-HS384':
64940
65440
  case 'A256CBC-HS512':
64941
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`);
65441
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`);
64942
65442
  case 'A128GCM':
64943
65443
  case 'A192GCM':
64944
65444
  case 'A256GCM':
@@ -64961,7 +65461,7 @@ function subtleMapping(jwk) {
64961
65461
  keyUsages = ['deriveBits'];
64962
65462
  break;
64963
65463
  default:
64964
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65464
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64965
65465
  }
64966
65466
  break;
64967
65467
  }
@@ -64990,7 +65490,7 @@ function subtleMapping(jwk) {
64990
65490
  keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];
64991
65491
  break;
64992
65492
  default:
64993
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65493
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
64994
65494
  }
64995
65495
  break;
64996
65496
  }
@@ -65016,7 +65516,7 @@ function subtleMapping(jwk) {
65016
65516
  keyUsages = jwk.d ? ['deriveBits'] : [];
65017
65517
  break;
65018
65518
  default:
65019
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65519
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65020
65520
  }
65021
65521
  break;
65022
65522
  }
@@ -65034,12 +65534,12 @@ function subtleMapping(jwk) {
65034
65534
  keyUsages = jwk.d ? ['deriveBits'] : [];
65035
65535
  break;
65036
65536
  default:
65037
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65537
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
65038
65538
  }
65039
65539
  break;
65040
65540
  }
65041
65541
  default:
65042
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_2__.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
65542
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
65043
65543
  }
65044
65544
  return { algorithm, keyUsages };
65045
65545
  }
@@ -65055,23 +65555,12 @@ const parse = async (jwk) => {
65055
65555
  (_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages,
65056
65556
  ];
65057
65557
  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);
65558
+ return _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.importKey('raw', (0,_base64url_js__WEBPACK_IMPORTED_MODULE_2__.decode)(jwk.k), ...rest);
65059
65559
  }
65060
65560
  const keyData = { ...jwk };
65061
65561
  delete keyData.alg;
65062
65562
  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
- }
65563
+ return _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"].subtle.importKey('jwk', keyData, ...rest);
65075
65564
  };
65076
65565
  /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (parse);
65077
65566
 
@@ -65313,9 +65802,7 @@ __webpack_require__.r(__webpack_exports__);
65313
65802
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
65314
65803
  /* harmony export */ "default": () => (/* binding */ subtleDsa)
65315
65804
  /* 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
-
65805
+ /* harmony import */ var _util_errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/errors.js */ "./node_modules/jose/dist/browser/util/errors.js");
65319
65806
 
65320
65807
  function subtleDsa(alg, algorithm) {
65321
65808
  const hash = `SHA-${alg.slice(-3)}`;
@@ -65337,12 +65824,9 @@ function subtleDsa(alg, algorithm) {
65337
65824
  case 'ES512':
65338
65825
  return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };
65339
65826
  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
65827
  return { name: algorithm.name };
65344
65828
  default:
65345
- throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_1__.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
65829
+ throw new _util_errors_js__WEBPACK_IMPORTED_MODULE_0__.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
65346
65830
  }
65347
65831
  }
65348
65832