@sphereon/ssi-sdk-ext.did-utils 0.28.1-feature.esm.cjs.8 → 0.28.1-feature.esm.cjs.9

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/index.cjs CHANGED
@@ -1,85 +1,18 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var __defProp = Object.defineProperty;
8
2
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/index.ts
32
- var index_exports = {};
33
- __export(index_exports, {
34
- AgentDIDResolver: () => AgentDIDResolver,
35
- DID_PREFIX: () => DID_PREFIX,
36
- IdentifierAliasEnum: () => IdentifierAliasEnum,
37
- SupportedDidMethodEnum: () => SupportedDidMethodEnum,
38
- asDidWeb: () => asDidWeb,
39
- createIdentifier: () => createIdentifier,
40
- dereferenceDidKeysWithJwkSupport: () => dereferenceDidKeysWithJwkSupport,
41
- determineKid: () => determineKid,
42
- didDocumentToJwks: () => didDocumentToJwks,
43
- extractPublicKeyHex: () => extractPublicKeyHex,
44
- extractPublicKeyHexWithJwkSupport: () => extractPublicKeyHexWithJwkSupport,
45
- getAgentDIDMethods: () => getAgentDIDMethods,
46
- getAgentResolver: () => getAgentResolver,
47
- getAuthenticationKey: () => getAuthenticationKey,
48
- getControllerKey: () => getControllerKey,
49
- getDID: () => getDID,
50
- getDidSigner: () => getDidSigner,
51
- getEthereumAddressFromKey: () => getEthereumAddressFromKey,
52
- getFirstKeyWithRelation: () => getFirstKeyWithRelation,
53
- getFirstKeyWithRelationFromDIDDoc: () => getFirstKeyWithRelationFromDIDDoc,
54
- getKey: () => getKey,
55
- getKeys: () => getKeys,
56
- getOrCreatePrimaryIdentifier: () => getOrCreatePrimaryIdentifier,
57
- getPrimaryIdentifier: () => getPrimaryIdentifier,
58
- getSupportedDIDMethods: () => getSupportedDIDMethods,
59
- isEvenHexString: () => isEvenHexString,
60
- jwkTtoPublicKeyHex: () => jwkTtoPublicKeyHex,
61
- mapIdentifierKeysToDocWithJwkSupport: () => mapIdentifierKeysToDocWithJwkSupport,
62
- signDidJWT: () => signDidJWT,
63
- toDID: () => toDID,
64
- toDIDs: () => toDIDs,
65
- toDidDocument: () => toDidDocument,
66
- toDidResolutionResult: () => toDidResolutionResult,
67
- verificationMethodToJwk: () => verificationMethodToJwk
68
- });
69
- module.exports = __toCommonJS(index_exports);
70
3
 
71
4
  // src/did-functions.ts
72
- var import_transactions = require("@ethersproject/transactions");
73
- var import_did_uni_client = require("@sphereon/did-uni-client");
74
- var import_ssi_sdk_ext = require("@sphereon/ssi-sdk-ext.key-utils");
75
- var import_ssi_sdk_ext2 = require("@sphereon/ssi-sdk-ext.x509-utils");
76
- var import_ssi_sdk = require("@sphereon/ssi-sdk.core");
77
- var import_ed25519 = require("@stablelib/ed25519");
78
- var import_utils = require("@veramo/utils");
79
- var import_did_jwt = require("did-jwt");
80
- var import_elliptic = __toESM(require("elliptic"), 1);
81
- var import_from_string = require("uint8arrays/from-string");
82
- var import_to_string = require("uint8arrays/to-string");
5
+ var _transactions = require('@ethersproject/transactions');
6
+ var _diduniclient = require('@sphereon/did-uni-client');
7
+ var _ssisdkextkeyutils = require('@sphereon/ssi-sdk-ext.key-utils');
8
+ var _ssisdkextx509utils = require('@sphereon/ssi-sdk-ext.x509-utils');
9
+ var _ssisdkcore = require('@sphereon/ssi-sdk.core');
10
+ var _ed25519 = require('@stablelib/ed25519');
11
+ var _utils = require('@veramo/utils');
12
+ var _didjwt = require('did-jwt');
13
+ var _elliptic = require('elliptic'); var _elliptic2 = _interopRequireDefault(_elliptic);
14
+ var _fromstring = require('uint8arrays/from-string');
15
+ var _tostring = require('uint8arrays/to-string');
83
16
 
84
17
  // src/types.ts
85
18
  var SupportedDidMethodEnum = /* @__PURE__ */ function(SupportedDidMethodEnum2) {
@@ -112,19 +45,19 @@ var getAuthenticationKey = /* @__PURE__ */ __name(async ({ identifier, offlineWh
112
45
  var getFirstKeyWithRelation = /* @__PURE__ */ __name(async ({ identifier, offlineWhenNoDIDRegistered, noVerificationMethodFallback, keyType, controllerKey, vmRelationship }, context) => {
113
46
  let key = void 0;
114
47
  try {
115
- key = await getFirstKeyWithRelationFromDIDDoc({
48
+ key = await _asyncNullishCoalesce(await getFirstKeyWithRelationFromDIDDoc({
116
49
  identifier,
117
50
  vmRelationship,
118
51
  errorOnNotFound: false,
119
52
  keyType,
120
53
  controllerKey
121
- }, context) ?? (noVerificationMethodFallback || vmRelationship === "verificationMethod" ? void 0 : await getFirstKeyWithRelationFromDIDDoc({
54
+ }, context), async () => ( (noVerificationMethodFallback || vmRelationship === "verificationMethod" ? void 0 : await getFirstKeyWithRelationFromDIDDoc({
122
55
  identifier,
123
56
  vmRelationship: "verificationMethod",
124
57
  errorOnNotFound: false,
125
58
  keyType,
126
59
  controllerKey
127
- }, context));
60
+ }, context))));
128
61
  } catch (e) {
129
62
  if (e instanceof Error) {
130
63
  if (!e.message.includes("404") || !offlineWhenNoDIDRegistered) {
@@ -136,23 +69,23 @@ var getFirstKeyWithRelation = /* @__PURE__ */ __name(async ({ identifier, offlin
136
69
  }
137
70
  if (!key && offlineWhenNoDIDRegistered) {
138
71
  const offlineDID = toDidDocument(identifier);
139
- key = await getFirstKeyWithRelationFromDIDDoc({
72
+ key = await _asyncNullishCoalesce(await getFirstKeyWithRelationFromDIDDoc({
140
73
  identifier,
141
74
  vmRelationship,
142
75
  errorOnNotFound: false,
143
76
  didDocument: offlineDID,
144
77
  keyType,
145
78
  controllerKey
146
- }, context) ?? (noVerificationMethodFallback || vmRelationship === "verificationMethod" ? void 0 : await getFirstKeyWithRelationFromDIDDoc({
79
+ }, context), async () => ( (noVerificationMethodFallback || vmRelationship === "verificationMethod" ? void 0 : await getFirstKeyWithRelationFromDIDDoc({
147
80
  identifier,
148
81
  vmRelationship: "verificationMethod",
149
82
  errorOnNotFound: false,
150
83
  didDocument: offlineDID,
151
84
  keyType,
152
85
  controllerKey
153
- }, context));
86
+ }, context))));
154
87
  if (!key) {
155
- key = identifier.keys.map((key2) => key2).filter((key2) => keyType === void 0 || key2.type === keyType || controllerKey && key2.kid === identifier.controllerKeyId).find((key2) => key2.meta.verificationMethod?.type.includes("authentication") || key2.meta.purposes?.includes("authentication"));
88
+ key = identifier.keys.map((key2) => key2).filter((key2) => keyType === void 0 || key2.type === keyType || controllerKey && key2.kid === identifier.controllerKeyId).find((key2) => _optionalChain([key2, 'access', _ => _.meta, 'access', _2 => _2.verificationMethod, 'optionalAccess', _3 => _3.type, 'access', _4 => _4.includes, 'call', _5 => _5("authentication")]) || _optionalChain([key2, 'access', _6 => _6.meta, 'access', _7 => _7.purposes, 'optionalAccess', _8 => _8.includes, 'call', _9 => _9("authentication")]));
156
89
  }
157
90
  }
158
91
  if (!key) {
@@ -162,8 +95,8 @@ var getFirstKeyWithRelation = /* @__PURE__ */ __name(async ({ identifier, offlin
162
95
  }, "getFirstKeyWithRelation");
163
96
  var getOrCreatePrimaryIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
164
97
  const primaryIdentifier = await getPrimaryIdentifier(context, {
165
- ...opts?.createOpts?.options,
166
- ...opts?.method && {
98
+ ..._optionalChain([opts, 'optionalAccess', _10 => _10.createOpts, 'optionalAccess', _11 => _11.options]),
99
+ ..._optionalChain([opts, 'optionalAccess', _12 => _12.method]) && {
167
100
  method: opts.method
168
101
  }
169
102
  });
@@ -173,8 +106,8 @@ var getOrCreatePrimaryIdentifier = /* @__PURE__ */ __name(async (context, opts)
173
106
  result: primaryIdentifier
174
107
  };
175
108
  }
176
- if (opts?.method === SupportedDidMethodEnum.DID_KEY) {
177
- const createOpts = opts?.createOpts ?? {};
109
+ if (_optionalChain([opts, 'optionalAccess', _13 => _13.method]) === SupportedDidMethodEnum.DID_KEY) {
110
+ const createOpts = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _14 => _14.createOpts]), () => ( {}));
178
111
  createOpts.options = {
179
112
  codecName: "EBSI",
180
113
  type: "Secp256r1",
@@ -189,19 +122,19 @@ var getOrCreatePrimaryIdentifier = /* @__PURE__ */ __name(async (context, opts)
189
122
  };
190
123
  }, "getOrCreatePrimaryIdentifier");
191
124
  var getPrimaryIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
192
- const identifiers = (await context.agent.didManagerFind(opts?.method ? {
193
- provider: `${DID_PREFIX}${opts?.method}`
194
- } : {})).filter((identifier) => opts?.type === void 0 || identifier.keys.some((key) => key.type === opts?.type));
125
+ const identifiers = (await context.agent.didManagerFind(_optionalChain([opts, 'optionalAccess', _15 => _15.method]) ? {
126
+ provider: `${DID_PREFIX}${_optionalChain([opts, 'optionalAccess', _16 => _16.method])}`
127
+ } : {})).filter((identifier) => _optionalChain([opts, 'optionalAccess', _17 => _17.type]) === void 0 || identifier.keys.some((key) => key.type === _optionalChain([opts, 'optionalAccess', _18 => _18.type])));
195
128
  return identifiers && identifiers.length > 0 ? identifiers[0] : void 0;
196
129
  }, "getPrimaryIdentifier");
197
130
  var createIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
198
131
  return await context.agent.didManagerCreate({
199
- kms: await (0, import_ssi_sdk_ext.getKms)(context, opts?.createOpts?.kms),
200
- ...opts?.method && {
201
- provider: `${DID_PREFIX}${opts?.method}`
132
+ kms: await _ssisdkextkeyutils.getKms.call(void 0, context, _optionalChain([opts, 'optionalAccess', _19 => _19.createOpts, 'optionalAccess', _20 => _20.kms])),
133
+ ..._optionalChain([opts, 'optionalAccess', _21 => _21.method]) && {
134
+ provider: `${DID_PREFIX}${_optionalChain([opts, 'optionalAccess', _22 => _22.method])}`
202
135
  },
203
- alias: opts?.createOpts?.alias ?? `${IdentifierAliasEnum.PRIMARY}-${opts?.method}-${opts?.createOpts?.options?.type}-${(/* @__PURE__ */ new Date()).getTime()}`,
204
- options: opts?.createOpts?.options
136
+ alias: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _23 => _23.createOpts, 'optionalAccess', _24 => _24.alias]), () => ( `${IdentifierAliasEnum.PRIMARY}-${_optionalChain([opts, 'optionalAccess', _25 => _25.method])}-${_optionalChain([opts, 'optionalAccess', _26 => _26.createOpts, 'optionalAccess', _27 => _27.options, 'optionalAccess', _28 => _28.type])}-${(/* @__PURE__ */ new Date()).getTime()}`)),
137
+ options: _optionalChain([opts, 'optionalAccess', _29 => _29.createOpts, 'optionalAccess', _30 => _30.options])
205
138
  });
206
139
  }, "createIdentifier");
207
140
  var getFirstKeyWithRelationFromDIDDoc = /* @__PURE__ */ __name(async ({ identifier, vmRelationship = "verificationMethod", keyType, errorOnNotFound = false, didDocument, controllerKey }, context) => {
@@ -225,7 +158,7 @@ var getEthereumAddressFromKey = /* @__PURE__ */ __name(({ key }) => {
225
158
  if (key.type !== "Secp256k1") {
226
159
  throw Error(`Can only get ethereum address from a Secp256k1 key. Type is ${key.type} for keyRef: ${key.kid}`);
227
160
  }
228
- const ethereumAddress = key.meta?.ethereumAddress ?? key.meta?.account?.toLowerCase() ?? (0, import_transactions.computeAddress)(`0x${key.publicKeyHex}`).toLowerCase();
161
+ const ethereumAddress = _nullishCoalesce(_nullishCoalesce(_optionalChain([key, 'access', _31 => _31.meta, 'optionalAccess', _32 => _32.ethereumAddress]), () => ( _optionalChain([key, 'access', _33 => _33.meta, 'optionalAccess', _34 => _34.account, 'optionalAccess', _35 => _35.toLowerCase, 'call', _36 => _36()]))), () => ( _transactions.computeAddress.call(void 0, `0x${key.publicKeyHex}`).toLowerCase()));
229
162
  if (!ethereumAddress) {
230
163
  throw Error(`Could not get or generate ethereum address from key with keyRef ${key.kid}`);
231
164
  }
@@ -239,7 +172,7 @@ var getControllerKey = /* @__PURE__ */ __name(({ identifier }) => {
239
172
  return key;
240
173
  }, "getControllerKey");
241
174
  var getKeys = /* @__PURE__ */ __name(({ jwkThumbprint, kms, identifier, kmsKeyRef, keyType, controllerKey }) => {
242
- return identifier.keys.filter((key) => !keyType || key.type === keyType).filter((key) => !kms || key.kms === kms).filter((key) => !kmsKeyRef || key.kid === kmsKeyRef).filter((key) => !jwkThumbprint || key.meta?.jwkThumbprint === jwkThumbprint).filter((key) => !controllerKey || identifier.controllerKeyId === key.kid);
175
+ return identifier.keys.filter((key) => !keyType || key.type === keyType).filter((key) => !kms || key.kms === kms).filter((key) => !kmsKeyRef || key.kid === kmsKeyRef).filter((key) => !jwkThumbprint || _optionalChain([key, 'access', _37 => _37.meta, 'optionalAccess', _38 => _38.jwkThumbprint]) === jwkThumbprint).filter((key) => !controllerKey || identifier.controllerKeyId === key.kid);
243
176
  }, "getKeys");
244
177
  async function dereferenceDidKeysWithJwkSupport(didDocument, section = "keyAgreement", context) {
245
178
  const convert = section === "keyAgreement";
@@ -260,7 +193,7 @@ async function dereferenceDidKeysWithJwkSupport(didDocument, section = "keyAgree
260
193
  } else {
261
194
  return key;
262
195
  }
263
- }))).filter(import_utils.isDefined).map((key) => {
196
+ }))).filter(_utils.isDefined).map((key) => {
264
197
  const hexKey = extractPublicKeyHexWithJwkSupport(key, convert);
265
198
  const { publicKeyHex, publicKeyBase58, publicKeyBase64, publicKeyJwk, ...keyProps } = key;
266
199
  const newKey = {
@@ -276,31 +209,31 @@ async function dereferenceDidKeysWithJwkSupport(didDocument, section = "keyAgree
276
209
  __name(dereferenceDidKeysWithJwkSupport, "dereferenceDidKeysWithJwkSupport");
277
210
  function jwkTtoPublicKeyHex(jwk) {
278
211
  const vm = {
279
- publicKeyJwk: (0, import_ssi_sdk_ext.sanitizedJwk)(jwk)
212
+ publicKeyJwk: _ssisdkextkeyutils.sanitizedJwk.call(void 0, jwk)
280
213
  };
281
214
  return extractPublicKeyHexWithJwkSupport(vm);
282
215
  }
283
216
  __name(jwkTtoPublicKeyHex, "jwkTtoPublicKeyHex");
284
217
  function extractPublicKeyHexWithJwkSupport(pk, convert = false) {
285
218
  if (pk.publicKeyJwk) {
286
- const jwk = (0, import_ssi_sdk_ext.sanitizedJwk)(pk.publicKeyJwk);
219
+ const jwk = _ssisdkextkeyutils.sanitizedJwk.call(void 0, pk.publicKeyJwk);
287
220
  if (jwk.kty === "EC") {
288
221
  const curve = jwk.crv ? toEcLibCurve(jwk.crv) : "p256";
289
- const xHex = (0, import_ssi_sdk_ext2.base64ToHex)(jwk.x, "base64url");
290
- const yHex = (0, import_ssi_sdk_ext2.base64ToHex)(jwk.y, "base64url");
222
+ const xHex = _ssisdkextx509utils.base64ToHex.call(void 0, jwk.x, "base64url");
223
+ const yHex = _ssisdkextx509utils.base64ToHex.call(void 0, jwk.y, "base64url");
291
224
  const prefix = "04";
292
225
  const hex = `${prefix}${xHex}${yHex}`;
293
226
  try {
294
- const ec = new import_elliptic.default.ec(curve);
227
+ const ec = new _elliptic2.default.ec(curve);
295
228
  const publicKeyHex = ec.keyFromPublic(hex, "hex").getPublic(true, "hex");
296
229
  return publicKeyHex;
297
230
  } catch (error) {
298
231
  console.error(`Error converting EC with elliptic lib curve ${curve} from JWK to hex. x: ${jwk.x}, y: ${jwk.y}, error: ${error}`, error);
299
232
  }
300
233
  } else if (jwk.crv === "Ed25519") {
301
- return (0, import_to_string.toString)((0, import_from_string.fromString)(jwk.x, "base64url"), "base16");
234
+ return _tostring.toString.call(void 0, _fromstring.fromString.call(void 0, jwk.x, "base64url"), "base16");
302
235
  } else if (jwk.kty === "RSA") {
303
- return (0, import_ssi_sdk_ext2.hexKeyFromPEMBasedJwk)(jwk, "public");
236
+ return _ssisdkextx509utils.hexKeyFromPEMBasedJwk.call(void 0, jwk, "public");
304
237
  }
305
238
  }
306
239
  return extractPublicKeyHex(pk, convert);
@@ -322,23 +255,23 @@ function isEvenHexString(hex) {
322
255
  __name(isEvenHexString, "isEvenHexString");
323
256
  function extractPublicKeyHex(pk, convert = false) {
324
257
  let keyBytes = extractPublicKeyBytes(pk);
325
- const jwk = pk.publicKeyJwk ? (0, import_ssi_sdk_ext.sanitizedJwk)(pk.publicKeyJwk) : void 0;
258
+ const jwk = pk.publicKeyJwk ? _ssisdkextkeyutils.sanitizedJwk.call(void 0, pk.publicKeyJwk) : void 0;
326
259
  if (convert) {
327
260
  if ([
328
261
  "Ed25519",
329
262
  "Ed25519VerificationKey2018",
330
263
  "Ed25519VerificationKey2020"
331
- ].includes(pk.type) || pk.type === "JsonWebKey2020" && jwk?.crv === "Ed25519") {
332
- keyBytes = (0, import_ed25519.convertPublicKeyToX25519)(keyBytes);
264
+ ].includes(pk.type) || pk.type === "JsonWebKey2020" && _optionalChain([jwk, 'optionalAccess', _39 => _39.crv]) === "Ed25519") {
265
+ keyBytes = _ed25519.convertPublicKeyToX25519.call(void 0, keyBytes);
333
266
  } else if (![
334
267
  "X25519",
335
268
  "X25519KeyAgreementKey2019",
336
269
  "X25519KeyAgreementKey2020"
337
- ].includes(pk.type) && !(pk.type === "JsonWebKey2020" && jwk?.crv === "X25519")) {
270
+ ].includes(pk.type) && !(pk.type === "JsonWebKey2020" && _optionalChain([jwk, 'optionalAccess', _40 => _40.crv]) === "X25519")) {
338
271
  return "";
339
272
  }
340
273
  }
341
- return (0, import_ssi_sdk.bytesToHex)(keyBytes);
274
+ return _ssisdkcore.bytesToHex.call(void 0, keyBytes);
342
275
  }
343
276
  __name(extractPublicKeyHex, "extractPublicKeyHex");
344
277
  function toEcLibCurve(input) {
@@ -347,17 +280,17 @@ function toEcLibCurve(input) {
347
280
  __name(toEcLibCurve, "toEcLibCurve");
348
281
  function extractPublicKeyBytes(pk) {
349
282
  if (pk.publicKeyBase58) {
350
- return (0, import_ssi_sdk.base58ToBytes)(pk.publicKeyBase58);
283
+ return _ssisdkcore.base58ToBytes.call(void 0, pk.publicKeyBase58);
351
284
  } else if (pk.publicKeyMultibase) {
352
- return (0, import_ssi_sdk.multibaseKeyToBytes)(pk.publicKeyMultibase);
285
+ return _ssisdkcore.multibaseKeyToBytes.call(void 0, pk.publicKeyMultibase);
353
286
  } else if (pk.publicKeyBase64) {
354
- return (0, import_ssi_sdk.base64ToBytes)(pk.publicKeyBase64);
287
+ return _ssisdkcore.base64ToBytes.call(void 0, pk.publicKeyBase64);
355
288
  } else if (pk.publicKeyHex) {
356
- return (0, import_ssi_sdk.hexToBytes)(pk.publicKeyHex);
357
- } else if (pk.publicKeyJwk?.crv && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
358
- return (0, import_ssi_sdk.hexToBytes)(extractPublicKeyHexWithJwkSupport(pk));
289
+ return _ssisdkcore.hexToBytes.call(void 0, pk.publicKeyHex);
290
+ } else if (_optionalChain([pk, 'access', _41 => _41.publicKeyJwk, 'optionalAccess', _42 => _42.crv]) && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
291
+ return _ssisdkcore.hexToBytes.call(void 0, extractPublicKeyHexWithJwkSupport(pk));
359
292
  } else if (pk.publicKeyJwk && (pk.publicKeyJwk.crv === "Ed25519" || pk.publicKeyJwk.crv === "X25519") && pk.publicKeyJwk.x) {
360
- return (0, import_ssi_sdk.base64ToBytes)(pk.publicKeyJwk.x);
293
+ return _ssisdkcore.base64ToBytes.call(void 0, pk.publicKeyJwk.x);
361
294
  }
362
295
  return new Uint8Array();
363
296
  }
@@ -365,8 +298,8 @@ __name(extractPublicKeyBytes, "extractPublicKeyBytes");
365
298
  function verificationMethodToJwk(vm) {
366
299
  let jwk = vm.publicKeyJwk;
367
300
  if (!jwk) {
368
- let publicKeyHex = vm.publicKeyHex ?? (0, import_to_string.toString)(extractPublicKeyBytes(vm), "hex");
369
- jwk = (0, import_ssi_sdk_ext.toJwk)(publicKeyHex, (0, import_ssi_sdk_ext.keyTypeFromCryptographicSuite)({
301
+ let publicKeyHex = _nullishCoalesce(vm.publicKeyHex, () => ( _tostring.toString.call(void 0, extractPublicKeyBytes(vm), "hex")));
302
+ jwk = _ssisdkextkeyutils.toJwk.call(void 0, publicKeyHex, _ssisdkextkeyutils.keyTypeFromCryptographicSuite.call(void 0, {
370
303
  crv: vm.type
371
304
  }));
372
305
  }
@@ -374,11 +307,11 @@ function verificationMethodToJwk(vm) {
374
307
  throw Error(`Could not convert verification method to jwk`);
375
308
  }
376
309
  jwk.kid = vm.id;
377
- return (0, import_ssi_sdk_ext.sanitizedJwk)(jwk);
310
+ return _ssisdkextkeyutils.sanitizedJwk.call(void 0, jwk);
378
311
  }
379
312
  __name(verificationMethodToJwk, "verificationMethodToJwk");
380
313
  function didDocumentSectionToJwks(didDocumentSection, searchForVerificationMethods, verificationMethods) {
381
- const jwks = new Set((searchForVerificationMethods ?? []).map((vmOrId) => typeof vmOrId === "object" ? vmOrId : verificationMethods?.find((vm) => vm.id === vmOrId)).filter(import_utils.isDefined).map((vm) => verificationMethodToJwk(vm)));
314
+ const jwks = new Set((_nullishCoalesce(searchForVerificationMethods, () => ( []))).map((vmOrId) => typeof vmOrId === "object" ? vmOrId : _optionalChain([verificationMethods, 'optionalAccess', _43 => _43.find, 'call', _44 => _44((vm) => vm.id === vmOrId)])).filter(_utils.isDefined).map((vm) => verificationMethodToJwk(vm)));
382
315
  return {
383
316
  didDocumentSection,
384
317
  jwks: Array.from(jwks)
@@ -400,15 +333,15 @@ function didDocumentToJwks(didDocument) {
400
333
  }
401
334
  __name(didDocumentToJwks, "didDocumentToJwks");
402
335
  async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship = "verificationMethod", didDocument }, context) {
403
- const didDoc = didDocument ?? await getAgentResolver(context).resolve(identifier.did).then((result) => result.didDocument);
336
+ const didDoc = await _asyncNullishCoalesce(didDocument, async () => ( await getAgentResolver(context).resolve(identifier.did).then((result) => result.didDocument)));
404
337
  if (!didDoc) {
405
338
  throw Error(`Could not resolve DID ${identifier.did}`);
406
339
  }
407
- const keys = didDoc ? [] : await (0, import_utils.mapIdentifierKeysToDoc)(identifier, vmRelationship, context);
340
+ const keys = didDoc ? [] : await _utils.mapIdentifierKeysToDoc.call(void 0, identifier, vmRelationship, context);
408
341
  const documentKeys = await dereferenceDidKeysWithJwkSupport(didDoc, vmRelationship, context);
409
- const localKeys = vmRelationship === "keyAgreement" ? (0, import_utils.convertIdentifierEncryptionKeys)(identifier) : (0, import_utils.compressIdentifierSecp256k1Keys)(identifier);
342
+ const localKeys = vmRelationship === "keyAgreement" ? _utils.convertIdentifierEncryptionKeys.call(void 0, identifier) : _utils.compressIdentifierSecp256k1Keys.call(void 0, identifier);
410
343
  const extendedKeys = documentKeys.map((verificationMethod) => {
411
- const localKey = localKeys.find((localKey2) => localKey2.publicKeyHex === verificationMethod.publicKeyHex || verificationMethod.publicKeyHex?.startsWith(localKey2.publicKeyHex) || compareBlockchainAccountId(localKey2, verificationMethod));
344
+ const localKey = localKeys.find((localKey2) => localKey2.publicKeyHex === verificationMethod.publicKeyHex || _optionalChain([verificationMethod, 'access', _45 => _45.publicKeyHex, 'optionalAccess', _46 => _46.startsWith, 'call', _47 => _47(localKey2.publicKeyHex)]) || compareBlockchainAccountId(localKey2, verificationMethod));
412
345
  if (localKey) {
413
346
  const { meta, ...localProps } = localKey;
414
347
  return {
@@ -421,7 +354,7 @@ async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship
421
354
  } else {
422
355
  return null;
423
356
  }
424
- }).filter(import_utils.isDefined);
357
+ }).filter(_utils.isDefined);
425
358
  return keys.concat(extendedKeys);
426
359
  }
427
360
  __name(mapIdentifierKeysToDocWithJwkSupport, "mapIdentifierKeysToDocWithJwkSupport");
@@ -429,11 +362,11 @@ function compareBlockchainAccountId(localKey, verificationMethod) {
429
362
  if (verificationMethod.type !== "EcdsaSecp256k1RecoveryMethod2020" && verificationMethod.type !== "EcdsaSecp256k1VerificationKey2019" || localKey.type !== "Secp256k1") {
430
363
  return false;
431
364
  }
432
- let vmEthAddr = (0, import_utils.getEthereumAddress)(verificationMethod);
433
- if (localKey.meta?.account) {
434
- return vmEthAddr === localKey.meta?.account.toLowerCase();
365
+ let vmEthAddr = _utils.getEthereumAddress.call(void 0, verificationMethod);
366
+ if (_optionalChain([localKey, 'access', _48 => _48.meta, 'optionalAccess', _49 => _49.account])) {
367
+ return vmEthAddr === _optionalChain([localKey, 'access', _50 => _50.meta, 'optionalAccess', _51 => _51.account, 'access', _52 => _52.toLowerCase, 'call', _53 => _53()]);
435
368
  }
436
- const computedAddr = (0, import_transactions.computeAddress)("0x" + localKey.publicKeyHex).toLowerCase();
369
+ const computedAddr = _transactions.computeAddress.call(void 0, "0x" + localKey.publicKeyHex).toLowerCase();
437
370
  return computedAddr === vmEthAddr;
438
371
  }
439
372
  __name(compareBlockchainAccountId, "compareBlockchainAccountId");
@@ -471,9 +404,9 @@ async function getKey({ identifier, vmRelationship = "authentication", kmsKeyRef
471
404
  if (!identifier) {
472
405
  return Promise.reject(new Error(`No identifier provided to getKey method!`));
473
406
  }
474
- const kmsKeyRefParts = kmsKeyRef?.split(`#`);
475
- const kid = kmsKeyRefParts ? kmsKeyRefParts?.length === 2 ? kmsKeyRefParts[1] : kmsKeyRefParts[0] : void 0;
476
- let identifierKey = kmsKeyRef ? identifier.keys.find((key) => key.kid === kid || key?.meta?.jwkThumbprint === kid) : void 0;
407
+ const kmsKeyRefParts = _optionalChain([kmsKeyRef, 'optionalAccess', _54 => _54.split, 'call', _55 => _55(`#`)]);
408
+ const kid = kmsKeyRefParts ? _optionalChain([kmsKeyRefParts, 'optionalAccess', _56 => _56.length]) === 2 ? kmsKeyRefParts[1] : kmsKeyRefParts[0] : void 0;
409
+ let identifierKey = kmsKeyRef ? identifier.keys.find((key) => key.kid === kid || _optionalChain([key, 'optionalAccess', _57 => _57.meta, 'optionalAccess', _58 => _58.jwkThumbprint]) === kid) : void 0;
477
410
  if (!identifierKey) {
478
411
  const keys = await mapIdentifierKeysToDocWithJwkSupport({
479
412
  identifier,
@@ -483,10 +416,10 @@ async function getKey({ identifier, vmRelationship = "authentication", kmsKeyRef
483
416
  throw new Error(`No keys found for verificationMethodSection: ${vmRelationship} and did ${identifier.did}`);
484
417
  }
485
418
  if (kmsKeyRef) {
486
- identifierKey = keys.find((key) => key.meta.verificationMethod?.id === kmsKeyRef || kid && key.meta.verificationMethod?.id?.includes(kid));
419
+ identifierKey = keys.find((key) => _optionalChain([key, 'access', _59 => _59.meta, 'access', _60 => _60.verificationMethod, 'optionalAccess', _61 => _61.id]) === kmsKeyRef || kid && _optionalChain([key, 'access', _62 => _62.meta, 'access', _63 => _63.verificationMethod, 'optionalAccess', _64 => _64.id, 'optionalAccess', _65 => _65.includes, 'call', _66 => _66(kid)]));
487
420
  }
488
421
  if (!identifierKey) {
489
- identifierKey = keys.find((key) => key.meta.verificationMethod?.type === vmRelationship || key.meta.purposes?.includes(vmRelationship));
422
+ identifierKey = keys.find((key) => _optionalChain([key, 'access', _67 => _67.meta, 'access', _68 => _68.verificationMethod, 'optionalAccess', _69 => _69.type]) === vmRelationship || _optionalChain([key, 'access', _70 => _70.meta, 'access', _71 => _71.purposes, 'optionalAccess', _72 => _72.includes, 'call', _73 => _73(vmRelationship)]));
490
423
  }
491
424
  if (!identifierKey) {
492
425
  identifierKey = keys[0];
@@ -508,8 +441,8 @@ async function legacyGetIdentifier({ identifier }, context) {
508
441
  }
509
442
  __name(legacyGetIdentifier, "legacyGetIdentifier");
510
443
  async function determineKid({ key, idOpts }, context) {
511
- if (key.meta?.verificationMethod?.id) {
512
- return key.meta?.verificationMethod?.id;
444
+ if (_optionalChain([key, 'access', _74 => _74.meta, 'optionalAccess', _75 => _75.verificationMethod, 'optionalAccess', _76 => _76.id])) {
445
+ return _optionalChain([key, 'access', _77 => _77.meta, 'optionalAccess', _78 => _78.verificationMethod, 'optionalAccess', _79 => _79.id]);
513
446
  }
514
447
  const identifier = await legacyGetIdentifier(idOpts, context);
515
448
  const mappedKeys = await mapIdentifierKeysToDocWithJwkSupport({
@@ -518,13 +451,13 @@ async function determineKid({ key, idOpts }, context) {
518
451
  }, context);
519
452
  const vmKey = mappedKeys.find((extendedKey) => extendedKey.kid === key.kid);
520
453
  if (vmKey) {
521
- return vmKey.meta?.verificationMethod?.id ?? vmKey.meta?.jwkThumbprint ?? idOpts.kmsKeyRef ?? vmKey.kid;
454
+ return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([vmKey, 'access', _80 => _80.meta, 'optionalAccess', _81 => _81.verificationMethod, 'optionalAccess', _82 => _82.id]), () => ( _optionalChain([vmKey, 'access', _83 => _83.meta, 'optionalAccess', _84 => _84.jwkThumbprint]))), () => ( idOpts.kmsKeyRef)), () => ( vmKey.kid));
522
455
  }
523
- return key.meta?.jwkThumbprint ?? idOpts.kmsKeyRef ?? key.kid;
456
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([key, 'access', _85 => _85.meta, 'optionalAccess', _86 => _86.jwkThumbprint]), () => ( idOpts.kmsKeyRef)), () => ( key.kid));
524
457
  }
525
458
  __name(determineKid, "determineKid");
526
459
  async function getSupportedDIDMethods(didOpts, context) {
527
- return didOpts.supportedDIDMethods ?? await getAgentDIDMethods(context);
460
+ return await _asyncNullishCoalesce(didOpts.supportedDIDMethods, async () => ( await getAgentDIDMethods(context)));
528
461
  }
529
462
  __name(getSupportedDIDMethods, "getSupportedDIDMethods");
530
463
  function getAgentResolver(context, opts) {
@@ -535,15 +468,15 @@ var AgentDIDResolver = class {
535
468
  static {
536
469
  __name(this, "AgentDIDResolver");
537
470
  }
538
- context;
539
- resolverResolution;
540
- uniresolverResolution;
541
- localResolution;
471
+
472
+
473
+
474
+
542
475
  constructor(context, opts) {
543
476
  this.context = context;
544
- this.resolverResolution = opts?.resolverResolution !== false;
545
- this.uniresolverResolution = opts?.uniresolverResolution !== false;
546
- this.localResolution = opts?.localResolution !== false;
477
+ this.resolverResolution = _optionalChain([opts, 'optionalAccess', _87 => _87.resolverResolution]) !== false;
478
+ this.uniresolverResolution = _optionalChain([opts, 'optionalAccess', _88 => _88.uniresolverResolution]) !== false;
479
+ this.localResolution = _optionalChain([opts, 'optionalAccess', _89 => _89.localResolution]) !== false;
547
480
  }
548
481
  async resolve(didUrl, options) {
549
482
  let resolutionResult;
@@ -601,7 +534,7 @@ var AgentDIDResolver = class {
601
534
  }
602
535
  if (!resolutionResult && this.uniresolverResolution) {
603
536
  console.log(`Using universal resolver resolution for did ${didUrl} `);
604
- resolutionResult = await new import_did_uni_client.UniResolver().resolve(didUrl, options);
537
+ resolutionResult = await new (0, _diduniclient.UniResolver)().resolve(didUrl, options);
605
538
  if (!origResolutionResult) {
606
539
  origResolutionResult = resolutionResult;
607
540
  }
@@ -615,13 +548,13 @@ var AgentDIDResolver = class {
615
548
  if (!resolutionResult && !origResolutionResult) {
616
549
  throw `Could not resolve ${didUrl}. Resolutions tried: online: ${this.resolverResolution}, local: ${this.localResolution}, uni resolver: ${this.uniresolverResolution}`;
617
550
  }
618
- return resolutionResult ?? origResolutionResult;
551
+ return _nullishCoalesce(resolutionResult, () => ( origResolutionResult));
619
552
  }
620
553
  };
621
554
  function toDidDocument(identifier, opts) {
622
555
  let didDocument = void 0;
623
556
  if (identifier) {
624
- const did = identifier.did ?? opts?.did;
557
+ const did = _nullishCoalesce(identifier.did, () => ( _optionalChain([opts, 'optionalAccess', _90 => _90.did])));
625
558
  didDocument = {
626
559
  "@context": "https://www.w3.org/ns/did/v1",
627
560
  id: did,
@@ -629,48 +562,48 @@ function toDidDocument(identifier, opts) {
629
562
  const vm = {
630
563
  controller: did,
631
564
  id: key.kid.startsWith(did) && key.kid.includes("#") ? key.kid : `${did}#${key.kid}`,
632
- publicKeyJwk: (0, import_ssi_sdk_ext.toJwk)(key.publicKeyHex, key.type, {
633
- use: import_ssi_sdk_ext.ENC_KEY_ALGS.includes(key.type) ? import_ssi_sdk_ext.JwkKeyUse.Encryption : import_ssi_sdk_ext.JwkKeyUse.Signature,
565
+ publicKeyJwk: _ssisdkextkeyutils.toJwk.call(void 0, key.publicKeyHex, key.type, {
566
+ use: _ssisdkextkeyutils.ENC_KEY_ALGS.includes(key.type) ? _ssisdkextkeyutils.JwkKeyUse.Encryption : _ssisdkextkeyutils.JwkKeyUse.Signature,
634
567
  key
635
568
  }),
636
569
  type: "JsonWebKey2020"
637
570
  };
638
571
  return vm;
639
572
  }),
640
- ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
641
- assertionMethod: identifier.keys.filter((key) => key?.meta?.purpose === void 0 || key?.meta?.purpose === "assertionMethod" || key?.meta?.purposes?.includes("assertionMethod")).map((key) => {
573
+ ...(_optionalChain([opts, 'optionalAccess', _91 => _91.use]) === void 0 || _optionalChain([opts, 'optionalAccess', _92 => _92.use, 'optionalAccess', _93 => _93.includes, 'call', _94 => _94(_ssisdkextkeyutils.JwkKeyUse.Signature)])) && identifier.keys && {
574
+ assertionMethod: identifier.keys.filter((key) => _optionalChain([key, 'optionalAccess', _95 => _95.meta, 'optionalAccess', _96 => _96.purpose]) === void 0 || _optionalChain([key, 'optionalAccess', _97 => _97.meta, 'optionalAccess', _98 => _98.purpose]) === "assertionMethod" || _optionalChain([key, 'optionalAccess', _99 => _99.meta, 'optionalAccess', _100 => _100.purposes, 'optionalAccess', _101 => _101.includes, 'call', _102 => _102("assertionMethod")])).map((key) => {
642
575
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
643
576
  return key.kid;
644
577
  }
645
578
  return `${did}#${key.kid}`;
646
579
  })
647
580
  },
648
- ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
649
- authentication: identifier.keys.filter((key) => key?.meta?.purpose === void 0 || key?.meta?.purpose === "authentication" || key?.meta?.purposes?.includes("authentication")).map((key) => {
581
+ ...(_optionalChain([opts, 'optionalAccess', _103 => _103.use]) === void 0 || _optionalChain([opts, 'optionalAccess', _104 => _104.use, 'optionalAccess', _105 => _105.includes, 'call', _106 => _106(_ssisdkextkeyutils.JwkKeyUse.Signature)])) && identifier.keys && {
582
+ authentication: identifier.keys.filter((key) => _optionalChain([key, 'optionalAccess', _107 => _107.meta, 'optionalAccess', _108 => _108.purpose]) === void 0 || _optionalChain([key, 'optionalAccess', _109 => _109.meta, 'optionalAccess', _110 => _110.purpose]) === "authentication" || _optionalChain([key, 'optionalAccess', _111 => _111.meta, 'optionalAccess', _112 => _112.purposes, 'optionalAccess', _113 => _113.includes, 'call', _114 => _114("authentication")])).map((key) => {
650
583
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
651
584
  return key.kid;
652
585
  }
653
586
  return `${did}#${key.kid}`;
654
587
  })
655
588
  },
656
- ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
657
- keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "keyAgreement" || key?.meta?.purposes?.includes("keyAgreement")).map((key) => {
589
+ ...(_optionalChain([opts, 'optionalAccess', _115 => _115.use]) === void 0 || _optionalChain([opts, 'optionalAccess', _116 => _116.use, 'optionalAccess', _117 => _117.includes, 'call', _118 => _118(_ssisdkextkeyutils.JwkKeyUse.Encryption)])) && identifier.keys && {
590
+ keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || _optionalChain([key, 'optionalAccess', _119 => _119.meta, 'optionalAccess', _120 => _120.purpose]) === "keyAgreement" || _optionalChain([key, 'optionalAccess', _121 => _121.meta, 'optionalAccess', _122 => _122.purposes, 'optionalAccess', _123 => _123.includes, 'call', _124 => _124("keyAgreement")])).map((key) => {
658
591
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
659
592
  return key.kid;
660
593
  }
661
594
  return `${did}#${key.kid}`;
662
595
  })
663
596
  },
664
- ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
665
- capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "capabilityInvocation" || key?.meta?.purposes?.includes("capabilityInvocation")).map((key) => {
597
+ ...(_optionalChain([opts, 'optionalAccess', _125 => _125.use]) === void 0 || _optionalChain([opts, 'optionalAccess', _126 => _126.use, 'optionalAccess', _127 => _127.includes, 'call', _128 => _128(_ssisdkextkeyutils.JwkKeyUse.Encryption)])) && identifier.keys && {
598
+ capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || _optionalChain([key, 'optionalAccess', _129 => _129.meta, 'optionalAccess', _130 => _130.purpose]) === "capabilityInvocation" || _optionalChain([key, 'optionalAccess', _131 => _131.meta, 'optionalAccess', _132 => _132.purposes, 'optionalAccess', _133 => _133.includes, 'call', _134 => _134("capabilityInvocation")])).map((key) => {
666
599
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
667
600
  return key.kid;
668
601
  }
669
602
  return `${did}#${key.kid}`;
670
603
  })
671
604
  },
672
- ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
673
- capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "capabilityDelegation" || key?.meta?.purposes?.includes("capabilityDelegation")).map((key) => {
605
+ ...(_optionalChain([opts, 'optionalAccess', _135 => _135.use]) === void 0 || _optionalChain([opts, 'optionalAccess', _136 => _136.use, 'optionalAccess', _137 => _137.includes, 'call', _138 => _138(_ssisdkextkeyutils.JwkKeyUse.Encryption)])) && identifier.keys && {
606
+ capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || _optionalChain([key, 'optionalAccess', _139 => _139.meta, 'optionalAccess', _140 => _140.purpose]) === "capabilityDelegation" || _optionalChain([key, 'optionalAccess', _141 => _141.meta, 'optionalAccess', _142 => _142.purposes, 'optionalAccess', _143 => _143.includes, 'call', _144 => _144("capabilityDelegation")])).map((key) => {
674
607
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
675
608
  return key.kid;
676
609
  }
@@ -686,7 +619,7 @@ function toDidDocument(identifier, opts) {
686
619
  }
687
620
  __name(toDidDocument, "toDidDocument");
688
621
  function toDidResolutionResult(identifier, opts) {
689
- const didDocument = toDidDocument(identifier, opts) ?? null;
622
+ const didDocument = _nullishCoalesce(toDidDocument(identifier, opts), () => ( null));
690
623
  const resolutionResult = {
691
624
  "@context": "https://w3id.org/did-resolution/v1",
692
625
  didDocument,
@@ -694,13 +627,13 @@ function toDidResolutionResult(identifier, opts) {
694
627
  ...!didDocument && {
695
628
  error: "notFound"
696
629
  },
697
- ...Array.isArray(opts?.supportedMethods) && identifier && !opts?.supportedMethods.includes(identifier.provider.replace("did:", "")) && {
630
+ ...Array.isArray(_optionalChain([opts, 'optionalAccess', _145 => _145.supportedMethods])) && identifier && !_optionalChain([opts, 'optionalAccess', _146 => _146.supportedMethods, 'access', _147 => _147.includes, 'call', _148 => _148(identifier.provider.replace("did:", ""))]) && {
698
631
  error: "unsupportedDidMethod"
699
632
  }
700
633
  },
701
634
  didDocumentMetadata: {
702
- ...identifier?.alias && {
703
- equivalentId: identifier?.alias
635
+ ..._optionalChain([identifier, 'optionalAccess', _149 => _149.alias]) && {
636
+ equivalentId: _optionalChain([identifier, 'optionalAccess', _150 => _150.alias])
704
637
  }
705
638
  }
706
639
  };
@@ -727,7 +660,7 @@ var signDidJWT = /* @__PURE__ */ __name(async (args) => {
727
660
  context
728
661
  })
729
662
  };
730
- return (0, import_did_jwt.createJWT)(payload, jwtOptions, header);
663
+ return _didjwt.createJWT.call(void 0, payload, jwtOptions, header);
731
664
  }, "signDidJWT");
732
665
  var getDidSigner = /* @__PURE__ */ __name(async (args) => {
733
666
  const { idOpts, context } = args;
@@ -737,7 +670,7 @@ var getDidSigner = /* @__PURE__ */ __name(async (args) => {
737
670
  vmRelationship: idOpts.verificationMethodSection,
738
671
  kmsKeyRef: idOpts.kmsKeyRef
739
672
  }, context);
740
- const algorithm = await (0, import_ssi_sdk_ext.signatureAlgorithmFromKey)({
673
+ const algorithm = await _ssisdkextkeyutils.signatureAlgorithmFromKey.call(void 0, {
741
674
  key
742
675
  });
743
676
  return async (data) => {
@@ -749,4 +682,40 @@ var getDidSigner = /* @__PURE__ */ __name(async (args) => {
749
682
  });
750
683
  };
751
684
  }, "getDidSigner");
685
+
686
+
687
+
688
+
689
+
690
+
691
+
692
+
693
+
694
+
695
+
696
+
697
+
698
+
699
+
700
+
701
+
702
+
703
+
704
+
705
+
706
+
707
+
708
+
709
+
710
+
711
+
712
+
713
+
714
+
715
+
716
+
717
+
718
+
719
+
720
+ exports.AgentDIDResolver = AgentDIDResolver; exports.DID_PREFIX = DID_PREFIX; exports.IdentifierAliasEnum = IdentifierAliasEnum; exports.SupportedDidMethodEnum = SupportedDidMethodEnum; exports.asDidWeb = asDidWeb; exports.createIdentifier = createIdentifier; exports.dereferenceDidKeysWithJwkSupport = dereferenceDidKeysWithJwkSupport; exports.determineKid = determineKid; exports.didDocumentToJwks = didDocumentToJwks; exports.extractPublicKeyHex = extractPublicKeyHex; exports.extractPublicKeyHexWithJwkSupport = extractPublicKeyHexWithJwkSupport; exports.getAgentDIDMethods = getAgentDIDMethods; exports.getAgentResolver = getAgentResolver; exports.getAuthenticationKey = getAuthenticationKey; exports.getControllerKey = getControllerKey; exports.getDID = getDID; exports.getDidSigner = getDidSigner; exports.getEthereumAddressFromKey = getEthereumAddressFromKey; exports.getFirstKeyWithRelation = getFirstKeyWithRelation; exports.getFirstKeyWithRelationFromDIDDoc = getFirstKeyWithRelationFromDIDDoc; exports.getKey = getKey; exports.getKeys = getKeys; exports.getOrCreatePrimaryIdentifier = getOrCreatePrimaryIdentifier; exports.getPrimaryIdentifier = getPrimaryIdentifier; exports.getSupportedDIDMethods = getSupportedDIDMethods; exports.isEvenHexString = isEvenHexString; exports.jwkTtoPublicKeyHex = jwkTtoPublicKeyHex; exports.mapIdentifierKeysToDocWithJwkSupport = mapIdentifierKeysToDocWithJwkSupport; exports.signDidJWT = signDidJWT; exports.toDID = toDID; exports.toDIDs = toDIDs; exports.toDidDocument = toDidDocument; exports.toDidResolutionResult = toDidResolutionResult; exports.verificationMethodToJwk = verificationMethodToJwk;
752
721
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/did-functions.ts","../src/types.ts"],"sourcesContent":["export * from './did-functions'\nexport * from './types'\n","import { computeAddress } from '@ethersproject/transactions'\nimport { UniResolver } from '@sphereon/did-uni-client'\nimport {\n ENC_KEY_ALGS,\n getKms,\n JwkKeyUse,\n keyTypeFromCryptographicSuite,\n sanitizedJwk,\n signatureAlgorithmFromKey,\n TKeyType,\n toJwk,\n} from '@sphereon/ssi-sdk-ext.key-utils'\nimport { base64ToHex, hexKeyFromPEMBasedJwk } from '@sphereon/ssi-sdk-ext.x509-utils'\nimport { base58ToBytes, base64ToBytes, bytesToHex, hexToBytes, multibaseKeyToBytes } from '@sphereon/ssi-sdk.core'\nimport { JWK } from '@sphereon/ssi-types'\nimport { convertPublicKeyToX25519 } from '@stablelib/ed25519'\nimport { DIDDocument, DIDDocumentSection, DIDResolutionResult, IAgentContext, IDIDManager, IIdentifier, IKey, IResolver } from '@veramo/core'\nimport {\n _ExtendedIKey,\n _ExtendedVerificationMethod,\n _NormalizedVerificationMethod,\n compressIdentifierSecp256k1Keys,\n convertIdentifierEncryptionKeys,\n getEthereumAddress,\n isDefined,\n mapIdentifierKeysToDoc,\n} from '@veramo/utils'\nimport { createJWT, Signer } from 'did-jwt'\nimport { DIDResolutionOptions, JsonWebKey, Resolvable, VerificationMethod } from 'did-resolver'\n// @ts-ignore\nimport elliptic from 'elliptic'\n// @ts-ignore\nimport { fromString } from 'uint8arrays/from-string'\n// @ts-ignore\nimport { toString } from 'uint8arrays/to-string'\nimport {\n CreateIdentifierOpts,\n CreateOrGetIdentifierOpts,\n DID_PREFIX,\n GetOrCreateResult,\n GetSignerArgs,\n IdentifierAliasEnum,\n IdentifierProviderOpts,\n IDIDOptions,\n SignJwtArgs,\n SupportedDidMethodEnum,\n} from './types'\n\nexport const getAuthenticationKey = async (\n {\n identifier,\n offlineWhenNoDIDRegistered,\n noVerificationMethodFallback,\n keyType,\n controllerKey,\n }: {\n identifier: IIdentifier\n keyType?: TKeyType\n offlineWhenNoDIDRegistered?: boolean\n noVerificationMethodFallback?: boolean\n controllerKey?: boolean\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<_ExtendedIKey> => {\n return await getFirstKeyWithRelation(\n {\n identifier,\n offlineWhenNoDIDRegistered,\n noVerificationMethodFallback,\n keyType,\n controllerKey,\n vmRelationship: 'authentication',\n },\n context\n )\n}\nexport const getFirstKeyWithRelation = async (\n {\n identifier,\n offlineWhenNoDIDRegistered,\n noVerificationMethodFallback,\n keyType,\n controllerKey,\n vmRelationship,\n }: {\n identifier: IIdentifier\n keyType?: TKeyType\n offlineWhenNoDIDRegistered?: boolean\n noVerificationMethodFallback?: boolean\n controllerKey?: boolean\n vmRelationship: DIDDocumentSection\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<_ExtendedIKey> => {\n let key: _ExtendedIKey | undefined = undefined\n try {\n key =\n (await getFirstKeyWithRelationFromDIDDoc(\n {\n identifier,\n vmRelationship,\n errorOnNotFound: false,\n keyType,\n controllerKey,\n },\n context\n )) ??\n (noVerificationMethodFallback || vmRelationship === 'verificationMethod' // let's not fallback to the same value again\n ? undefined\n : await getFirstKeyWithRelationFromDIDDoc(\n {\n identifier,\n vmRelationship: 'verificationMethod',\n errorOnNotFound: false,\n keyType,\n controllerKey,\n },\n context\n ))\n } catch (e) {\n if (e instanceof Error) {\n if (!e.message.includes('404') || !offlineWhenNoDIDRegistered) {\n throw e\n }\n } else {\n throw e\n }\n }\n if (!key && offlineWhenNoDIDRegistered) {\n const offlineDID = toDidDocument(identifier)\n key =\n (await getFirstKeyWithRelationFromDIDDoc(\n {\n identifier,\n vmRelationship,\n errorOnNotFound: false,\n didDocument: offlineDID,\n keyType,\n controllerKey,\n },\n context\n )) ??\n (noVerificationMethodFallback || vmRelationship === 'verificationMethod' // let's not fallback to the same value again\n ? undefined\n : await getFirstKeyWithRelationFromDIDDoc(\n {\n identifier,\n vmRelationship: 'verificationMethod',\n errorOnNotFound: false,\n didDocument: offlineDID,\n keyType,\n controllerKey,\n },\n context\n ))\n if (!key) {\n key = identifier.keys\n .map((key) => key as _ExtendedIKey)\n .filter((key) => keyType === undefined || key.type === keyType || (controllerKey && key.kid === identifier.controllerKeyId))\n .find((key) => key.meta.verificationMethod?.type.includes('authentication') || key.meta.purposes?.includes('authentication'))\n }\n }\n if (!key) {\n throw Error(`Could not find authentication key for DID ${identifier.did}`)\n }\n return key\n}\n\nexport const getOrCreatePrimaryIdentifier = async (\n context: IAgentContext<IDIDManager>,\n opts?: CreateOrGetIdentifierOpts\n): Promise<GetOrCreateResult<IIdentifier>> => {\n const primaryIdentifier = await getPrimaryIdentifier(context, { ...opts?.createOpts?.options, ...(opts?.method && { method: opts.method }) })\n if (primaryIdentifier !== undefined) {\n return {\n created: false,\n result: primaryIdentifier,\n }\n }\n\n if (opts?.method === SupportedDidMethodEnum.DID_KEY) {\n const createOpts = opts?.createOpts ?? {}\n createOpts.options = { codecName: 'EBSI', type: 'Secp256r1', ...createOpts }\n opts.createOpts = createOpts\n }\n const createdIdentifier = await createIdentifier(context, opts)\n return {\n created: true,\n result: createdIdentifier,\n }\n}\n\nexport const getPrimaryIdentifier = async (context: IAgentContext<IDIDManager>, opts?: IdentifierProviderOpts): Promise<IIdentifier | undefined> => {\n const identifiers = (await context.agent.didManagerFind(opts?.method ? { provider: `${DID_PREFIX}${opts?.method}` } : {})).filter(\n (identifier: IIdentifier) => opts?.type === undefined || identifier.keys.some((key: IKey) => key.type === opts?.type)\n )\n\n return identifiers && identifiers.length > 0 ? identifiers[0] : undefined\n}\n\nexport const createIdentifier = async (context: IAgentContext<IDIDManager>, opts?: CreateIdentifierOpts): Promise<IIdentifier> => {\n return await context.agent.didManagerCreate({\n kms: await getKms(context, opts?.createOpts?.kms),\n ...(opts?.method && { provider: `${DID_PREFIX}${opts?.method}` }),\n alias: opts?.createOpts?.alias ?? `${IdentifierAliasEnum.PRIMARY}-${opts?.method}-${opts?.createOpts?.options?.type}-${new Date().getTime()}`,\n options: opts?.createOpts?.options,\n })\n}\n\nexport const getFirstKeyWithRelationFromDIDDoc = async (\n {\n identifier,\n vmRelationship = 'verificationMethod',\n keyType,\n errorOnNotFound = false,\n didDocument,\n controllerKey,\n }: {\n identifier: IIdentifier\n controllerKey?: boolean\n vmRelationship?: DIDDocumentSection\n keyType?: TKeyType\n errorOnNotFound?: boolean\n didDocument?: DIDDocument\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<_ExtendedIKey | undefined> => {\n const matchedKeys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship, didDocument }, context)\n if (Array.isArray(matchedKeys) && matchedKeys.length > 0) {\n const result = matchedKeys.find(\n (key) => keyType === undefined || key.type === keyType || (controllerKey && key.kid === identifier.controllerKeyId)\n )\n if (result) {\n return result\n }\n }\n if (errorOnNotFound) {\n throw new Error(\n `Could not find key with relationship ${vmRelationship} in DID document for ${identifier.did}${keyType ? ' and key type: ' + keyType : ''}`\n )\n }\n return undefined\n}\n\nexport const getEthereumAddressFromKey = ({ key }: { key: IKey }) => {\n if (key.type !== 'Secp256k1') {\n throw Error(`Can only get ethereum address from a Secp256k1 key. Type is ${key.type} for keyRef: ${key.kid}`)\n }\n const ethereumAddress = key.meta?.ethereumAddress ?? key.meta?.account?.toLowerCase() ?? computeAddress(`0x${key.publicKeyHex}`).toLowerCase()\n if (!ethereumAddress) {\n throw Error(`Could not get or generate ethereum address from key with keyRef ${key.kid}`)\n }\n return ethereumAddress\n}\n\nexport const getControllerKey = ({ identifier }: { identifier: IIdentifier }) => {\n const key = identifier.keys.find((key) => key.kid === identifier.controllerKeyId)\n if (!key) {\n throw Error(`Could not get controller key for identifier ${identifier}`)\n }\n return key\n}\n\nexport const getKeys = ({\n jwkThumbprint,\n kms,\n identifier,\n kmsKeyRef,\n keyType,\n controllerKey,\n}: {\n identifier: IIdentifier\n kmsKeyRef?: string\n keyType?: TKeyType\n kms?: string\n jwkThumbprint?: string\n controllerKey?: boolean\n}) => {\n return identifier.keys\n .filter((key) => !keyType || key.type === keyType)\n .filter((key) => !kms || key.kms === kms)\n .filter((key) => !kmsKeyRef || key.kid === kmsKeyRef)\n .filter((key) => !jwkThumbprint || key.meta?.jwkThumbprint === jwkThumbprint)\n .filter((key) => !controllerKey || identifier.controllerKeyId === key.kid)\n}\n\n//TODO: Move to ssi-sdk/core and create PR upstream\n/**\n * Dereferences keys from DID document and normalizes them for easy comparison.\n *\n * When dereferencing keyAgreement keys, only Ed25519 and X25519 curves are supported.\n * Other key types are omitted from the result and Ed25519 keys are converted to X25519\n *\n * @returns a Promise that resolves to the list of dereferenced keys.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport async function dereferenceDidKeysWithJwkSupport(\n didDocument: DIDDocument,\n section: DIDDocumentSection = 'keyAgreement',\n context: IAgentContext<IResolver>\n): Promise<_NormalizedVerificationMethod[]> {\n const convert = section === 'keyAgreement'\n if (section === 'service') {\n return []\n }\n return (\n await Promise.all(\n (didDocument[section] || []).map(async (key: string | VerificationMethod) => {\n if (typeof key === 'string') {\n try {\n return (await context.agent.getDIDComponentById({\n didDocument,\n didUrl: key,\n section,\n })) as _ExtendedVerificationMethod\n } catch (e) {\n return null\n }\n } else {\n return key as _ExtendedVerificationMethod\n }\n })\n )\n )\n .filter(isDefined)\n .map((key) => {\n const hexKey = extractPublicKeyHexWithJwkSupport(key, convert)\n const { publicKeyHex, publicKeyBase58, publicKeyBase64, publicKeyJwk, ...keyProps } = key\n const newKey = { ...keyProps, publicKeyHex: hexKey }\n if (convert && 'Ed25519VerificationKey2018' === newKey.type) {\n newKey.type = 'X25519KeyAgreementKey2019'\n }\n return newKey\n })\n}\n\nexport function jwkTtoPublicKeyHex(jwk: JWK): string {\n // todo: Hacky way to convert this to a VM. Should extract the logic from the below methods\n // @ts-ignore\n const vm: _ExtendedVerificationMethod = {\n publicKeyJwk: sanitizedJwk(jwk),\n }\n return extractPublicKeyHexWithJwkSupport(vm)\n}\n\n/**\n * Converts the publicKey of a VerificationMethod to hex encoding (publicKeyHex)\n *\n * @param pk - the VerificationMethod to be converted\n * @param convert - when this flag is set to true, Ed25519 keys are converted to their X25519 pairs\n * @returns the hex encoding of the public key\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport function extractPublicKeyHexWithJwkSupport(pk: _ExtendedVerificationMethod, convert = false): string {\n if (pk.publicKeyJwk) {\n const jwk = sanitizedJwk(pk.publicKeyJwk)\n if (jwk.kty === 'EC') {\n const curve = jwk.crv ? toEcLibCurve(jwk.crv) : 'p256'\n const xHex = base64ToHex(jwk.x!, 'base64url')\n const yHex = base64ToHex(jwk.y!, 'base64url')\n const prefix = '04' // isEven(yHex) ? '02' : '03'\n // Uncompressed Hex format: 04<x><y>\n // Compressed Hex format: 02<x> (for even y) or 03<x> (for uneven y)\n const hex = `${prefix}${xHex}${yHex}`\n try {\n const ec = new elliptic.ec(curve)\n // We return directly as we don't want to convert the result back into Uint8Array and then convert again to hex as the elliptic lib already returns hex strings\n const publicKeyHex = ec.keyFromPublic(hex, 'hex').getPublic(true, 'hex')\n // This returns a short form (x) with 02 or 03 prefix\n return publicKeyHex\n } catch (error: any) {\n console.error(`Error converting EC with elliptic lib curve ${curve} from JWK to hex. x: ${jwk.x}, y: ${jwk.y}, error: ${error}`, error)\n }\n } else if (jwk.crv === 'Ed25519') {\n return toString(fromString(jwk.x!, 'base64url'), 'base16')\n } else if (jwk.kty === 'RSA') {\n return hexKeyFromPEMBasedJwk(jwk, 'public')\n }\n }\n // delegate the other types to the original Veramo function\n return extractPublicKeyHex(pk, convert)\n}\n\nexport function isEvenHexString(hex: string) {\n const lastChar = hex[hex.length - 1].toLowerCase()\n return ['0', '2', '4', '6', '8', 'a', 'c', 'e'].includes(lastChar)\n}\n\ninterface LegacyVerificationMethod extends VerificationMethod {\n publicKeyBase64: string\n}\n\n/**\n * Converts the publicKey of a VerificationMethod to hex encoding (publicKeyHex)\n *\n * @param pk - the VerificationMethod to be converted\n * @param convert - when this flag is set to true, Ed25519 keys are converted to their X25519 pairs\n * @returns the hex encoding of the public key\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport function extractPublicKeyHex(pk: _ExtendedVerificationMethod, convert: boolean = false): string {\n let keyBytes = extractPublicKeyBytes(pk)\n const jwk = pk.publicKeyJwk ? sanitizedJwk(pk.publicKeyJwk) : undefined\n if (convert) {\n if (\n ['Ed25519', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020'].includes(pk.type) ||\n (pk.type === 'JsonWebKey2020' && jwk?.crv === 'Ed25519')\n ) {\n keyBytes = convertPublicKeyToX25519(keyBytes)\n } else if (\n !['X25519', 'X25519KeyAgreementKey2019', 'X25519KeyAgreementKey2020'].includes(pk.type) &&\n !(pk.type === 'JsonWebKey2020' && jwk?.crv === 'X25519')\n ) {\n return ''\n }\n }\n return bytesToHex(keyBytes)\n}\n\nfunction toEcLibCurve(input: string) {\n return input.toLowerCase().replace('-', '').replace('_', '')\n}\n\nfunction extractPublicKeyBytes(pk: VerificationMethod): Uint8Array {\n if (pk.publicKeyBase58) {\n return base58ToBytes(pk.publicKeyBase58)\n } else if (pk.publicKeyMultibase) {\n return multibaseKeyToBytes(pk.publicKeyMultibase)\n } else if ((<LegacyVerificationMethod>pk).publicKeyBase64) {\n return base64ToBytes((<LegacyVerificationMethod>pk).publicKeyBase64)\n } else if (pk.publicKeyHex) {\n return hexToBytes(pk.publicKeyHex)\n } else if (pk.publicKeyJwk?.crv && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return hexToBytes(extractPublicKeyHexWithJwkSupport(pk))\n } else if (pk.publicKeyJwk && (pk.publicKeyJwk.crv === 'Ed25519' || pk.publicKeyJwk.crv === 'X25519') && pk.publicKeyJwk.x) {\n return base64ToBytes(pk.publicKeyJwk.x)\n }\n return new Uint8Array()\n}\n\nexport function verificationMethodToJwk(vm: VerificationMethod): JWK {\n let jwk: JWK | undefined = vm.publicKeyJwk as JWK\n if (!jwk) {\n let publicKeyHex = vm.publicKeyHex ?? toString(extractPublicKeyBytes(vm), 'hex')\n jwk = toJwk(publicKeyHex, keyTypeFromCryptographicSuite({ crv: vm.type }))\n }\n if (!jwk) {\n throw Error(`Could not convert verification method to jwk`)\n }\n jwk.kid = vm.id\n return sanitizedJwk(jwk)\n}\n\nfunction didDocumentSectionToJwks(\n didDocumentSection: DIDDocumentSection,\n searchForVerificationMethods?: (VerificationMethod | string)[],\n verificationMethods?: VerificationMethod[]\n) {\n const jwks = new Set(\n (searchForVerificationMethods ?? [])\n .map((vmOrId) => (typeof vmOrId === 'object' ? vmOrId : verificationMethods?.find((vm) => vm.id === vmOrId)))\n .filter(isDefined)\n .map((vm) => verificationMethodToJwk(vm))\n )\n return { didDocumentSection, jwks: Array.from(jwks) }\n}\n\nexport type DidDocumentJwks = Record<Exclude<DIDDocumentSection, 'publicKey' | 'service'>, Array<JWK>>\n\nexport function didDocumentToJwks(didDocument: DIDDocument): DidDocumentJwks {\n return {\n verificationMethod: [\n ...didDocumentSectionToJwks('publicKey', didDocument.publicKey, didDocument.verificationMethod).jwks, // legacy support\n ...didDocumentSectionToJwks('verificationMethod', didDocument.verificationMethod, didDocument.verificationMethod).jwks,\n ],\n assertionMethod: didDocumentSectionToJwks('assertionMethod', didDocument.assertionMethod, didDocument.verificationMethod).jwks,\n authentication: didDocumentSectionToJwks('authentication', didDocument.authentication, didDocument.verificationMethod).jwks,\n keyAgreement: didDocumentSectionToJwks('keyAgreement', didDocument.keyAgreement, didDocument.verificationMethod).jwks,\n capabilityInvocation: didDocumentSectionToJwks('capabilityInvocation', didDocument.capabilityInvocation, didDocument.verificationMethod).jwks,\n capabilityDelegation: didDocumentSectionToJwks('capabilityDelegation', didDocument.capabilityDelegation, didDocument.verificationMethod).jwks,\n }\n}\n\n/**\n * Maps the keys of a locally managed {@link @veramo/core#IIdentifier | IIdentifier} to the corresponding\n * {@link did-resolver#VerificationMethod | VerificationMethod} entries from the DID document.\n *\n * @param identifier - the identifier to be mapped\n * @param section - the section of the DID document to be mapped (see\n * {@link https://www.w3.org/TR/did-core/#verification-relationships | verification relationships}), but can also be\n * `verificationMethod` to map all the keys.\n * @param didDocument\n * @param context - the veramo agent context, which must contain a {@link @veramo/core#IResolver | IResolver}\n * implementation that can resolve the DID document of the identifier.\n *\n * @returns an array of mapped keys. The corresponding verification method is added to the `meta.verificationMethod`\n * property of the key.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport async function mapIdentifierKeysToDocWithJwkSupport(\n {\n identifier,\n vmRelationship = 'verificationMethod',\n didDocument,\n }: {\n identifier: IIdentifier\n vmRelationship?: DIDDocumentSection\n didDocument?: DIDDocument\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<_ExtendedIKey[]> {\n const didDoc =\n didDocument ??\n (await getAgentResolver(context)\n .resolve(identifier.did)\n .then((result) => result.didDocument))\n if (!didDoc) {\n throw Error(`Could not resolve DID ${identifier.did}`)\n }\n\n // const rsaDidWeb = identifier.keys && identifier.keys.length > 0 && identifier.keys.find((key) => key.type === 'RSA') && didDocument\n\n // We skip mapping in case the identifier is RSA and a did document is supplied.\n const keys = didDoc ? [] : await mapIdentifierKeysToDoc(identifier, vmRelationship, context)\n\n // dereference all key agreement keys from DID document and normalize\n const documentKeys: VerificationMethod[] = await dereferenceDidKeysWithJwkSupport(didDoc, vmRelationship, context)\n\n const localKeys = vmRelationship === 'keyAgreement' ? convertIdentifierEncryptionKeys(identifier) : compressIdentifierSecp256k1Keys(identifier)\n\n // finally map the didDocument keys to the identifier keys by comparing `publicKeyHex`\n const extendedKeys: _ExtendedIKey[] = documentKeys\n .map((verificationMethod) => {\n /*if (verificationMethod.type !== 'JsonWebKey2020') {\n return null\n }*/\n const localKey = localKeys.find(\n (localKey) =>\n localKey.publicKeyHex === verificationMethod.publicKeyHex ||\n verificationMethod.publicKeyHex?.startsWith(localKey.publicKeyHex) ||\n compareBlockchainAccountId(localKey, verificationMethod)\n )\n if (localKey) {\n const { meta, ...localProps } = localKey\n return { ...localProps, meta: { ...meta, verificationMethod } }\n } else {\n return null\n }\n })\n .filter(isDefined)\n\n return keys.concat(extendedKeys)\n}\n\n/**\n * Compares the `blockchainAccountId` of a `EcdsaSecp256k1RecoveryMethod2020` verification method with the address\n * computed from a locally managed key.\n *\n * @returns true if the local key address corresponds to the `blockchainAccountId`\n *\n * @param localKey - The locally managed key\n * @param verificationMethod - a {@link did-resolver#VerificationMethod | VerificationMethod} with a\n * `blockchainAccountId`\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nfunction compareBlockchainAccountId(localKey: IKey, verificationMethod: VerificationMethod): boolean {\n if (\n (verificationMethod.type !== 'EcdsaSecp256k1RecoveryMethod2020' && verificationMethod.type !== 'EcdsaSecp256k1VerificationKey2019') ||\n localKey.type !== 'Secp256k1'\n ) {\n return false\n }\n let vmEthAddr = getEthereumAddress(verificationMethod)\n if (localKey.meta?.account) {\n return vmEthAddr === localKey.meta?.account.toLowerCase()\n }\n const computedAddr = computeAddress('0x' + localKey.publicKeyHex).toLowerCase()\n return computedAddr === vmEthAddr\n}\n\nexport async function getAgentDIDMethods(context: IAgentContext<IDIDManager>) {\n return (await context.agent.didManagerGetProviders()).map((provider) => provider.toLowerCase().replace('did:', ''))\n}\n\nexport function getDID(idOpts: { identifier: IIdentifier | string }): string {\n if (typeof idOpts.identifier === 'string') {\n return idOpts.identifier\n } else if (typeof idOpts.identifier === 'object') {\n return idOpts.identifier.did\n }\n throw Error(`Cannot get DID from identifier value`)\n}\n\nexport function toDID(identifier: string | IIdentifier | Partial<IIdentifier>): string {\n if (typeof identifier === 'string') {\n return identifier\n }\n if (identifier.did) {\n return identifier.did\n }\n throw Error(`No DID value present in identifier`)\n}\n\nexport function toDIDs(identifiers?: (string | IIdentifier | Partial<IIdentifier>)[]): string[] {\n if (!identifiers) {\n return []\n }\n return identifiers.map(toDID)\n}\n\nexport async function getKey(\n {\n identifier,\n vmRelationship = 'authentication',\n kmsKeyRef,\n }: {\n identifier: IIdentifier\n vmRelationship?: DIDDocumentSection\n kmsKeyRef?: string\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<IKey> {\n if (!identifier) {\n return Promise.reject(new Error(`No identifier provided to getKey method!`))\n }\n // normalize to kid, in case keyId was passed in as did#vm or #vm\n const kmsKeyRefParts = kmsKeyRef?.split(`#`)\n const kid = kmsKeyRefParts ? (kmsKeyRefParts?.length === 2 ? kmsKeyRefParts[1] : kmsKeyRefParts[0]) : undefined\n // todo: We really should do a keyRef and external kid here\n let identifierKey = kmsKeyRef ? identifier.keys.find((key: IKey) => key.kid === kid || key?.meta?.jwkThumbprint === kid) : undefined\n if (!identifierKey) {\n const keys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship: vmRelationship }, context)\n if (!keys || keys.length === 0) {\n throw new Error(`No keys found for verificationMethodSection: ${vmRelationship} and did ${identifier.did}`)\n }\n if (kmsKeyRef) {\n identifierKey = keys.find(\n (key: _ExtendedIKey) => key.meta.verificationMethod?.id === kmsKeyRef || (kid && key.meta.verificationMethod?.id?.includes(kid))\n )\n }\n if (!identifierKey) {\n identifierKey = keys.find(\n (key: _ExtendedIKey) => key.meta.verificationMethod?.type === vmRelationship || key.meta.purposes?.includes(vmRelationship)\n )\n }\n if (!identifierKey) {\n identifierKey = keys[0]\n }\n }\n if (!identifierKey) {\n throw new Error(\n `No matching verificationMethodSection key found for keyId: ${kmsKeyRef} and vmSection: ${vmRelationship} for id ${identifier.did}`\n )\n }\n\n return identifierKey\n}\n\n/**\n *\n * @param identifier\n * @param context\n *\n * @deprecated Replaced by the identfier resolution plugin\n */\nasync function legacyGetIdentifier(\n {\n identifier,\n }: {\n identifier: string | IIdentifier\n },\n context: IAgentContext<IDIDManager>\n): Promise<IIdentifier> {\n if (typeof identifier === 'string') {\n return await context.agent.didManagerGet({ did: identifier })\n }\n return identifier\n}\n\n/**\n * Get the real kid as used in JWTs. This is the kid in the VM or in the JWT, not the kid in the Veramo/Sphereon keystore. That was just a poorly chosen name\n * @param key\n * @param idOpts\n * @param context\n */\nexport async function determineKid(\n {\n key,\n idOpts,\n }: {\n key: IKey\n idOpts: { identifier: IIdentifier | string; kmsKeyRef?: string }\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<string> {\n if (key.meta?.verificationMethod?.id) {\n return key.meta?.verificationMethod?.id\n }\n const identifier = await legacyGetIdentifier(idOpts, context)\n const mappedKeys = await mapIdentifierKeysToDocWithJwkSupport(\n {\n identifier,\n vmRelationship: 'verificationMethod',\n },\n context\n )\n const vmKey = mappedKeys.find((extendedKey) => extendedKey.kid === key.kid)\n if (vmKey) {\n return vmKey.meta?.verificationMethod?.id ?? vmKey.meta?.jwkThumbprint ?? idOpts.kmsKeyRef ?? vmKey.kid\n }\n\n return key.meta?.jwkThumbprint ?? idOpts.kmsKeyRef ?? key.kid\n}\n\nexport async function getSupportedDIDMethods(didOpts: IDIDOptions, context: IAgentContext<IDIDManager>) {\n return didOpts.supportedDIDMethods ?? (await getAgentDIDMethods(context))\n}\n\nexport function getAgentResolver(\n context: IAgentContext<IResolver & IDIDManager>,\n opts?: {\n localResolution?: boolean // Resolve identifiers hosted by the agent\n uniresolverResolution?: boolean // Resolve identifiers using universal resolver\n resolverResolution?: boolean // Use registered drivers\n }\n): Resolvable {\n return new AgentDIDResolver(context, opts)\n}\n\nexport class AgentDIDResolver implements Resolvable {\n private readonly context: IAgentContext<IResolver & IDIDManager>\n private readonly resolverResolution: boolean\n private readonly uniresolverResolution: boolean\n private readonly localResolution: boolean\n\n constructor(\n context: IAgentContext<IResolver & IDIDManager>,\n opts?: { uniresolverResolution?: boolean; localResolution?: boolean; resolverResolution?: boolean }\n ) {\n this.context = context\n this.resolverResolution = opts?.resolverResolution !== false\n this.uniresolverResolution = opts?.uniresolverResolution !== false\n this.localResolution = opts?.localResolution !== false\n }\n\n async resolve(didUrl: string, options?: DIDResolutionOptions): Promise<DIDResolutionResult> {\n let resolutionResult: DIDResolutionResult | undefined\n let origResolutionResult: DIDResolutionResult | undefined\n let err: any\n if (!this.resolverResolution && !this.localResolution && !this.uniresolverResolution) {\n throw Error(`No agent hosted DID resolution, regular agent resolution nor universal resolver resolution is enabled. Cannot resolve DIDs.`)\n }\n if (this.resolverResolution) {\n try {\n resolutionResult = await this.context.agent.resolveDid({ didUrl, options })\n } catch (error: unknown) {\n err = error\n }\n }\n if (resolutionResult) {\n origResolutionResult = resolutionResult\n if (resolutionResult.didDocument === null) {\n resolutionResult = undefined\n }\n } else {\n console.log(`Agent resolver resolution is disabled. This typically isn't desirable!`)\n }\n if (!resolutionResult && this.localResolution) {\n console.log(`Using local DID resolution, looking at DIDs hosted by the agent.`)\n try {\n const did = didUrl.split('#')[0]\n const iIdentifier = await this.context.agent.didManagerGet({ did })\n resolutionResult = toDidResolutionResult(iIdentifier, { did })\n if (resolutionResult.didDocument) {\n err = undefined\n } else {\n console.log(`Local resolution resulted in a DID Document for ${did}`)\n }\n } catch (error: unknown) {\n if (!err) {\n err = error\n }\n }\n }\n if (resolutionResult) {\n if (!origResolutionResult) {\n origResolutionResult = resolutionResult\n }\n if (!resolutionResult.didDocument) {\n resolutionResult = undefined\n }\n }\n if (!resolutionResult && this.uniresolverResolution) {\n console.log(`Using universal resolver resolution for did ${didUrl} `)\n resolutionResult = await new UniResolver().resolve(didUrl, options)\n if (!origResolutionResult) {\n origResolutionResult = resolutionResult\n }\n if (resolutionResult.didDocument) {\n err = undefined\n }\n }\n\n if (err) {\n // throw original error\n throw err\n }\n if (!resolutionResult && !origResolutionResult) {\n throw `Could not resolve ${didUrl}. Resolutions tried: online: ${this.resolverResolution}, local: ${this.localResolution}, uni resolver: ${this.uniresolverResolution}`\n }\n return resolutionResult ?? origResolutionResult!\n }\n}\n\n/**\n * Please note that this is not an exact representation of the actual DID Document.\n *\n * We try to do our best, to map keys onto relevant verification methods and relationships, but we simply lack the context\n * of the actual DID method here. Do not relly on this method for DID resolution. It is only handy for offline use cases\n * when no DID Document is cached. For DID:WEB it does provide an accurate representation!\n *\n * @param identifier\n * @param opts\n */\nexport function toDidDocument(\n identifier?: IIdentifier,\n opts?: {\n did?: string\n use?: JwkKeyUse[]\n }\n): DIDDocument | undefined {\n let didDocument: DIDDocument | undefined = undefined\n // TODO: Introduce jwk thumbprints here\n if (identifier) {\n const did = identifier.did ?? opts?.did\n didDocument = {\n '@context': 'https://www.w3.org/ns/did/v1',\n id: did,\n verificationMethod: identifier.keys.map((key) => {\n const vm: VerificationMethod = {\n controller: did,\n id: key.kid.startsWith(did) && key.kid.includes('#') ? key.kid : `${did}#${key.kid}`,\n publicKeyJwk: toJwk(key.publicKeyHex, key.type, {\n use: ENC_KEY_ALGS.includes(key.type) ? JwkKeyUse.Encryption : JwkKeyUse.Signature,\n key,\n }) as JsonWebKey,\n type: 'JsonWebKey2020',\n }\n return vm\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&\n identifier.keys && {\n assertionMethod: identifier.keys\n .filter(\n (key) =>\n key?.meta?.purpose === undefined || key?.meta?.purpose === 'assertionMethod' || key?.meta?.purposes?.includes('assertionMethod')\n )\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&\n identifier.keys && {\n authentication: identifier.keys\n .filter(\n (key) => key?.meta?.purpose === undefined || key?.meta?.purpose === 'authentication' || key?.meta?.purposes?.includes('authentication')\n )\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&\n identifier.keys && {\n keyAgreement: identifier.keys\n .filter((key) => key.type === 'X25519' || key?.meta?.purpose === 'keyAgreement' || key?.meta?.purposes?.includes('keyAgreement'))\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&\n identifier.keys && {\n capabilityInvocation: identifier.keys\n .filter(\n (key) => key.type === 'X25519' || key?.meta?.purpose === 'capabilityInvocation' || key?.meta?.purposes?.includes('capabilityInvocation')\n )\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&\n identifier.keys && {\n capabilityDelegation: identifier.keys\n .filter(\n (key) => key.type === 'X25519' || key?.meta?.purpose === 'capabilityDelegation' || key?.meta?.purposes?.includes('capabilityDelegation')\n )\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...(identifier.services && identifier.services.length > 0 && { service: identifier.services }),\n }\n }\n return didDocument\n}\n\nexport function toDidResolutionResult(\n identifier?: IIdentifier,\n opts?: {\n did?: string\n supportedMethods?: string[]\n }\n): DIDResolutionResult {\n const didDocument = toDidDocument(identifier, opts) ?? null // null is used in case of errors and required by the did resolution spec\n\n const resolutionResult: DIDResolutionResult = {\n '@context': 'https://w3id.org/did-resolution/v1',\n didDocument,\n didResolutionMetadata: {\n ...(!didDocument && { error: 'notFound' }),\n ...(Array.isArray(opts?.supportedMethods) &&\n identifier &&\n !opts?.supportedMethods.includes(identifier.provider.replace('did:', '')) && { error: 'unsupportedDidMethod' }),\n },\n didDocumentMetadata: {\n ...(identifier?.alias && { equivalentId: identifier?.alias }),\n },\n }\n return resolutionResult\n}\n\nexport async function asDidWeb(hostnameOrDID: string): Promise<string> {\n let did = hostnameOrDID\n if (!did) {\n throw Error('Domain or DID expected, but received nothing.')\n }\n if (did.startsWith('did:web:')) {\n return did\n }\n return `did:web:${did.replace(/https?:\\/\\/([^/?#]+).*/i, '$1').toLowerCase()}`\n}\n\n/**\n * @deprecated Replaced by the new signer service\n */\nexport const signDidJWT = async (args: SignJwtArgs): Promise<string> => {\n const { idOpts, header, payload, context, options } = args\n const jwtOptions = {\n ...options,\n signer: await getDidSigner({ idOpts, context }),\n }\n\n return createJWT(payload, jwtOptions, header)\n}\n\n/**\n * @deprecated Replaced by the new signer service\n */\nexport const getDidSigner = async (\n args: GetSignerArgs & {\n idOpts: {\n /**\n * @deprecated\n */\n identifier: IIdentifier | string\n /**\n * @deprecated\n */\n verificationMethodSection?: DIDDocumentSection\n /**\n * @deprecated\n */\n kmsKeyRef?: string\n }\n }\n): Promise<Signer> => {\n const { idOpts, context } = args\n\n const identifier = await legacyGetIdentifier(idOpts, context)\n const key = await getKey(\n {\n identifier,\n vmRelationship: idOpts.verificationMethodSection,\n kmsKeyRef: idOpts.kmsKeyRef,\n },\n context\n )\n const algorithm = await signatureAlgorithmFromKey({ key })\n\n return async (data: string | Uint8Array): Promise<string> => {\n const input = data instanceof Object.getPrototypeOf(Uint8Array) ? new TextDecoder().decode(data as Uint8Array) : (data as string)\n return await context.agent.keyManagerSign({\n keyRef: key.kid,\n algorithm,\n data: input,\n })\n }\n}\n","import { TKeyType } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { IAgentContext, IDIDManager, IIdentifier, IKeyManager, IResolver } from '@veramo/core'\nimport { JWTHeader, JWTPayload, JWTVerifyOptions } from 'did-jwt'\nimport { Resolvable } from 'did-resolver'\n\nexport enum SupportedDidMethodEnum {\n DID_ETHR = 'ethr',\n DID_KEY = 'key',\n DID_LTO = 'lto',\n DID_ION = 'ion',\n DID_EBSI = 'ebsi',\n DID_JWK = 'jwk',\n DID_OYD = 'oyd',\n}\n\nexport enum IdentifierAliasEnum {\n PRIMARY = 'primary',\n}\n\nexport interface ResolveOpts {\n jwtVerifyOpts?: JWTVerifyOptions\n resolver?: Resolvable\n resolveUrl?: string\n noUniversalResolverFallback?: boolean\n subjectSyntaxTypesSupported?: string[]\n}\n\n/**\n * @deprecated Replaced by the identifier resolution service\n */\nexport interface IDIDOptions {\n resolveOpts?: ResolveOpts\n idOpts: LegacyIIdentifierOpts\n supportedDIDMethods?: string[]\n}\n\nexport type IdentifierProviderOpts = {\n type?: TKeyType\n use?: string\n method?: SupportedDidMethodEnum\n [x: string]: any\n}\n\nexport type CreateIdentifierOpts = {\n method: SupportedDidMethodEnum\n createOpts?: CreateIdentifierCreateOpts\n}\n\nexport type CreateIdentifierCreateOpts = {\n kms?: string\n alias?: string\n options?: IdentifierProviderOpts\n}\n\nexport type CreateOrGetIdentifierOpts = {\n method: SupportedDidMethodEnum\n createOpts?: CreateIdentifierCreateOpts\n}\n\nexport const DID_PREFIX = 'did:'\n\nexport interface GetOrCreateResult<T> {\n created: boolean\n result: T\n}\n\n/**\n * @deprecated Replaced by new signer\n */\nexport type SignJwtArgs = {\n idOpts: LegacyIIdentifierOpts\n header: Partial<JWTHeader>\n payload: Partial<JWTPayload>\n options: { issuer: string; expiresIn?: number; canonicalize?: boolean }\n context: IRequiredSignAgentContext\n}\n\n/**\n * @deprecated Replaced by new signer\n */\nexport type GetSignerArgs = {\n idOpts: LegacyIIdentifierOpts\n context: IRequiredSignAgentContext\n}\n\n/**\n * @deprecated Replaced by the identifier resolution service\n */\ntype LegacyIIdentifierOpts = {\n identifier: IIdentifier | string\n}\nexport type IRequiredSignAgentContext = IAgentContext<IKeyManager & IDIDManager & IResolver>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA,0BAA+B;AAC/B,4BAA4B;AAC5B,yBASO;AACP,IAAAA,sBAAmD;AACnD,qBAA0F;AAE1F,qBAAyC;AAEzC,mBASO;AACP,qBAAkC;AAGlC,sBAAqB;AAErB,yBAA2B;AAE3B,uBAAyB;;;AC7BlB,IAAKC,yBAAAA,yBAAAA,yBAAAA;;;;;;;;SAAAA;;AAUL,IAAKC,sBAAAA,yBAAAA,sBAAAA;;SAAAA;;AA4CL,IAAMC,aAAa;;;ADXnB,IAAMC,uBAAuB,8BAClC,EACEC,YACAC,4BACAC,8BACAC,SACAC,cAAa,GAQfC,YAAAA;AAEA,SAAO,MAAMC,wBACX;IACEN;IACAC;IACAC;IACAC;IACAC;IACAG,gBAAgB;EAClB,GACAF,OAAAA;AAEJ,GA3BoC;AA4B7B,IAAMC,0BAA0B,8BACrC,EACEN,YACAC,4BACAC,8BACAC,SACA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REFIX","getAuthenticationKey","identifier","offlineWhenNoDIDRegistered","noVerificationMethodFallback","keyType","controllerKey","context","getFirstKeyWithRelation","vmRelationship","key","undefined","getFirstKeyWithRelationFromDIDDoc","errorOnNotFound","e","Error","message","includes","offlineDID","toDidDocument","didDocument","keys","map","filter","type","kid","controllerKeyId","find","meta","verificationMethod","purposes","did","getOrCreatePrimaryIdentifier","opts","primaryIdentifier","getPrimaryIdentifier","createOpts","options","method","created","result","SupportedDidMethodEnum","DID_KEY","codecName","createdIdentifier","createIdentifier","identifiers","agent","didManagerFind","provider","DID_PREFIX","some","length","didManagerCreate","kms","getKms","alias","IdentifierAliasEnum","PRIMARY","Date","getTime","matchedKeys","mapIdentifierKeysToDocWithJwkSupport","Array","isArray","getEthereumAddressFromKey","ethereumAddress","account","toLowerCase","computeAddress","publicKeyHex","getControllerKey","getKeys","jwkThumbprint","kmsKeyRef","dereferenceDidKeysWithJwkSupport","section","convert","Promise","all","getDIDComponentById","didUrl","isDefined","hexKey","extractPublicKeyHexWithJwkSupport","publicKeyBase58","publicKeyBase64","publicKeyJwk","keyProps","newKey","jwkTtoPublicKeyHex","jwk","vm","sanitizedJwk","pk","kty","curve","crv","toEcLibCurve","xHex","base64ToHex","x","yHex","y","prefix","hex","ec","elliptic","keyFromPublic","getPublic","error","console","toString","fromString","hexKeyFromPEMBasedJwk","extractPublicKeyHex","isEvenHexString","lastChar","keyBytes","extractPublicKeyBytes","convertPublicKeyToX25519","bytesToHex","input","replace","base58ToBytes","publicKeyMultibase","multibaseKeyToBytes","base64ToBytes","hexToBytes","Uint8Array","verificationMethodToJwk","toJwk","keyTypeFromCryptographicSuite","id","didDocumentSectionToJwks","didDocumentSection","searchForVerificationMethods","verificationMethods","jwks","Set","vmOrId","from","didDocumentToJwks","publicKey","assertionMethod","authentication","keyAgreement","capabilityInvocation","capabilityDelegation","didDoc","getAgentResolver","resolve","then","mapIdentifierKeysToDoc","documentKeys","localKeys","convertIdentifierEncryptionKeys","compressIdentifierSecp256k1Keys","extendedKeys","localKey","startsWith","compareBlockchainAccountId","localProps","concat","vmEthAddr","getEthereumAddress","computedAddr","getAgentDIDMethods","didManagerGetProviders","getDID","idOpts","toDID","toDIDs","getKey","reject","kmsKeyRefParts","split","identifierKey","legacyGetIdentifier","didManagerGet","determineKid","mappedKeys","vmKey","extendedKey","getSupportedDIDMethods","didOpts","supportedDIDMethods","AgentDIDResolver","resolverResolution","uniresolverResolution","localResolution","constructor","resolutionResult","origResolutionResult","err","resolveDid","log","iIdentifier","toDidResolutionResult","UniResolver","controller","use","ENC_KEY_ALGS","JwkKeyUse","Encryption","Signature","purpose","services","service","didResolutionMetadata","supportedMethods","didDocumentMetadata","equivalentId","asDidWeb","hostnameOrDID","signDidJWT","args","header","payload","jwtOptions","signer","getDidSigner","createJWT","verificationMethodSection","algorithm","signatureAlgorithmFromKey","data","Object","getPrototypeOf","TextDecoder","decode","keyManagerSign","keyRef"]}
1
+ {"version":3,"sources":["/home/runner/work/SSI-SDK-crypto-extensions/SSI-SDK-crypto-extensions/packages/did-utils/dist/index.cjs","../src/did-functions.ts","../src/types.ts"],"names":["SupportedDidMethodEnum","IdentifierAliasEnum","DID_PREFIX","getAuthenticationKey","identifier","offlineWhenNoDIDRegistered","noVerificationMethodFallback","keyType","controllerKey","context","getFirstKeyWithRelation","vmRelationship","key","undefined","getFirstKeyWithRelationFromDIDDoc","errorOnNotFound","e","Error","message","includes","offlineDID","toDidDocument","didDocument","keys","map","filter","type","kid","controllerKeyId","find","meta","verificationMethod","purposes","did","opts","options","method","primaryIdentifier","createOpts","createdIdentifier","some","kms","result","toLowerCase","ethereumAddress","kmsKeyRef","section","convert","keyProps","hexKey","newKey","dereferenceDidKeysWithJwkSupport","jwk","vm","jwkTtoPublicKeyHex","yHex","curve","publicKeyHex","extractPublicKeyHexWithJwkSupport","lastChar","isEvenHexString","pk","keyBytes","extractPublicKeyHex","toEcLibCurve","y","publicKeyJwk","Uint8Array","extractPublicKeyBytes","id","verificationMethodToJwk","searchForVerificationMethods","didDocumentSection","jwks","didDocumentSectionToJwks","authentication","keyAgreement","didDocumentToJwks","convertIdentifierEncryptionKeys","localKey","localProps","isDefined","extendedKeys","mapIdentifierKeysToDocWithJwkSupport","vmEthAddr","compareBlockchainAccountId","provider","getAgentDIDMethods","getDID","toDID","toDIDs","kmsKeyRefParts","identifierKey","getKey","legacyGetIdentifier","jwkThumbprint","determineKid","getSupportedDIDMethods","getAgentResolver","AgentDIDResolver","resolverResolution","uniresolverResolution","localResolution","resolutionResult","origResolutionResult","err","didUrl","error","JwkKeyUse","purpose","services","supportedMethods","alias","toDidResolutionResult","hostnameOrDID","asDidWeb","args","idOpts","header","verificationMethodSection","data","TextDecoder","algorithm","input"],"mappings":"AAAA,04BAAI,UAAU,EAAE,MAAM,CAAC,cAAc;AACrC,IAAI,OAAO,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,CAAC,CAAC;AACxF;AACA;ACHA,2DAA+B;AAC/B,wDAA4B;AAC5B,oEASO;AACP,sEAAmD;AACnD,oDAA0F;AAE1F,6CAAyC;AAEzC,sCASO;AACP,iCAAkC;AAGlC,wFAAqB;AAErB,qDAA2B;AAE3B,iDAAyB;ADnBzB;AACA;AEXO,IAAKA,uBAAAA,kBAAAA,QAAAA,CAAAA,uBAAAA,EAAAA;AFaZ,EAAE,uBAAuB,CAAC,UAAU,EAAE,EAAE,MAAM;AAC9C,EAAE,uBAAuB,CAAC,SAAS,EAAE,EAAE,KAAK;AAC5C,EAAE,uBAAuB,CAAC,SAAS,EAAE,EAAE,KAAK;AAC5C,EAAE,uBAAuB,CAAC,SAAS,EAAE,EAAE,KAAK;AAC5C,EAAE,uBAAuB,CAAC,UAAU,EAAE,EAAE,MAAM;AAC9C,EAAE,uBAAuB,CAAC,SAAS,EAAE,EAAE,KAAK;AAC5C,EAAE,uBAAuB,CAAC,SAAS,EA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AAA;AACM,MAAA;AAA4BC,QAAAA;AAAM,MAAA;AAC7D,IAAA;AACF,EAAA;AACOT,EAAAA;AACT;AAvBgBU;AAyBoC;AACxCC,EAAAA;AACA,EAAA;AACI,IAAA;AACd,EAAA;AACgC,EAAA;AACvBjF,IAAAA;AACT,EAAA;AAC+DU,EAAAA;AACjE;AATsBwE;AAcWC;AACuBA,EAAAA;AACnC,EAAA;AACdjF,IAAAA;AACwB,IAAA;AAAEkF,MAAAA;AAAQ5G,MAAAA;AAAQ,IAAA;AAC/C,EAAA;AAEsC6G,EAAAA;AAPd;AAcxBF;AAiB4BA,EAAAA;AAEyB3G,EAAAA;AAEnD,EAAA;AACEL,IAAAA;AACuBmH,IAAAA;AACL1E,IAAAA;AAEpBpC,EAAAA;AAEgD,EAAA;AAAEG,IAAAA;AAAI,EAAA;AAE1C4G,EAAAA;AAC0DC,IAAAA;AAC5B,IAAA;AAC5B9F,MAAAA;AACZ+F,MAAAA;AACMC,MAAAA;AACR,IAAA;AACF,EAAA;AAtC0B;ADrSgD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/SSI-SDK-crypto-extensions/SSI-SDK-crypto-extensions/packages/did-utils/dist/index.cjs","sourcesContent":[null,"import { computeAddress } from '@ethersproject/transactions'\nimport { UniResolver } from '@sphereon/did-uni-client'\nimport {\n ENC_KEY_ALGS,\n getKms,\n JwkKeyUse,\n keyTypeFromCryptographicSuite,\n sanitizedJwk,\n signatureAlgorithmFromKey,\n TKeyType,\n toJwk,\n} from '@sphereon/ssi-sdk-ext.key-utils'\nimport { base64ToHex, hexKeyFromPEMBasedJwk } from '@sphereon/ssi-sdk-ext.x509-utils'\nimport { base58ToBytes, base64ToBytes, bytesToHex, hexToBytes, multibaseKeyToBytes } from '@sphereon/ssi-sdk.core'\nimport { JWK } from '@sphereon/ssi-types'\nimport { convertPublicKeyToX25519 } from '@stablelib/ed25519'\nimport { DIDDocument, DIDDocumentSection, DIDResolutionResult, IAgentContext, IDIDManager, IIdentifier, IKey, IResolver } from '@veramo/core'\nimport {\n _ExtendedIKey,\n _ExtendedVerificationMethod,\n _NormalizedVerificationMethod,\n compressIdentifierSecp256k1Keys,\n convertIdentifierEncryptionKeys,\n getEthereumAddress,\n isDefined,\n mapIdentifierKeysToDoc,\n} from '@veramo/utils'\nimport { createJWT, Signer } from 'did-jwt'\nimport { DIDResolutionOptions, JsonWebKey, Resolvable, VerificationMethod } from 'did-resolver'\n// @ts-ignore\nimport elliptic from 'elliptic'\n// @ts-ignore\nimport { fromString } from 'uint8arrays/from-string'\n// @ts-ignore\nimport { toString } from 'uint8arrays/to-string'\nimport {\n CreateIdentifierOpts,\n CreateOrGetIdentifierOpts,\n DID_PREFIX,\n GetOrCreateResult,\n GetSignerArgs,\n IdentifierAliasEnum,\n IdentifierProviderOpts,\n IDIDOptions,\n SignJwtArgs,\n SupportedDidMethodEnum,\n} from './types'\n\nexport const getAuthenticationKey = async (\n {\n identifier,\n offlineWhenNoDIDRegistered,\n noVerificationMethodFallback,\n keyType,\n controllerKey,\n }: {\n identifier: IIdentifier\n keyType?: TKeyType\n offlineWhenNoDIDRegistered?: boolean\n noVerificationMethodFallback?: boolean\n controllerKey?: boolean\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<_ExtendedIKey> => {\n return await getFirstKeyWithRelation(\n {\n identifier,\n offlineWhenNoDIDRegistered,\n noVerificationMethodFallback,\n keyType,\n controllerKey,\n vmRelationship: 'authentication',\n },\n context\n )\n}\nexport const getFirstKeyWithRelation = async (\n {\n identifier,\n offlineWhenNoDIDRegistered,\n noVerificationMethodFallback,\n keyType,\n controllerKey,\n vmRelationship,\n }: {\n identifier: IIdentifier\n keyType?: TKeyType\n offlineWhenNoDIDRegistered?: boolean\n noVerificationMethodFallback?: boolean\n controllerKey?: boolean\n vmRelationship: DIDDocumentSection\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<_ExtendedIKey> => {\n let key: _ExtendedIKey | undefined = undefined\n try {\n key =\n (await getFirstKeyWithRelationFromDIDDoc(\n {\n identifier,\n vmRelationship,\n errorOnNotFound: false,\n keyType,\n controllerKey,\n },\n context\n )) ??\n (noVerificationMethodFallback || vmRelationship === 'verificationMethod' // let's not fallback to the same value again\n ? undefined\n : await getFirstKeyWithRelationFromDIDDoc(\n {\n identifier,\n vmRelationship: 'verificationMethod',\n errorOnNotFound: false,\n keyType,\n controllerKey,\n },\n context\n ))\n } catch (e) {\n if (e instanceof Error) {\n if (!e.message.includes('404') || !offlineWhenNoDIDRegistered) {\n throw e\n }\n } else {\n throw e\n }\n }\n if (!key && offlineWhenNoDIDRegistered) {\n const offlineDID = toDidDocument(identifier)\n key =\n (await getFirstKeyWithRelationFromDIDDoc(\n {\n identifier,\n vmRelationship,\n errorOnNotFound: false,\n didDocument: offlineDID,\n keyType,\n controllerKey,\n },\n context\n )) ??\n (noVerificationMethodFallback || vmRelationship === 'verificationMethod' // let's not fallback to the same value again\n ? undefined\n : await getFirstKeyWithRelationFromDIDDoc(\n {\n identifier,\n vmRelationship: 'verificationMethod',\n errorOnNotFound: false,\n didDocument: offlineDID,\n keyType,\n controllerKey,\n },\n context\n ))\n if (!key) {\n key = identifier.keys\n .map((key) => key as _ExtendedIKey)\n .filter((key) => keyType === undefined || key.type === keyType || (controllerKey && key.kid === identifier.controllerKeyId))\n .find((key) => key.meta.verificationMethod?.type.includes('authentication') || key.meta.purposes?.includes('authentication'))\n }\n }\n if (!key) {\n throw Error(`Could not find authentication key for DID ${identifier.did}`)\n }\n return key\n}\n\nexport const getOrCreatePrimaryIdentifier = async (\n context: IAgentContext<IDIDManager>,\n opts?: CreateOrGetIdentifierOpts\n): Promise<GetOrCreateResult<IIdentifier>> => {\n const primaryIdentifier = await getPrimaryIdentifier(context, { ...opts?.createOpts?.options, ...(opts?.method && { method: opts.method }) })\n if (primaryIdentifier !== undefined) {\n return {\n created: false,\n result: primaryIdentifier,\n }\n }\n\n if (opts?.method === SupportedDidMethodEnum.DID_KEY) {\n const createOpts = opts?.createOpts ?? {}\n createOpts.options = { codecName: 'EBSI', type: 'Secp256r1', ...createOpts }\n opts.createOpts = createOpts\n }\n const createdIdentifier = await createIdentifier(context, opts)\n return {\n created: true,\n result: createdIdentifier,\n }\n}\n\nexport const getPrimaryIdentifier = async (context: IAgentContext<IDIDManager>, opts?: IdentifierProviderOpts): Promise<IIdentifier | undefined> => {\n const identifiers = (await context.agent.didManagerFind(opts?.method ? { provider: `${DID_PREFIX}${opts?.method}` } : {})).filter(\n (identifier: IIdentifier) => opts?.type === undefined || identifier.keys.some((key: IKey) => key.type === opts?.type)\n )\n\n return identifiers && identifiers.length > 0 ? identifiers[0] : undefined\n}\n\nexport const createIdentifier = async (context: IAgentContext<IDIDManager>, opts?: CreateIdentifierOpts): Promise<IIdentifier> => {\n return await context.agent.didManagerCreate({\n kms: await getKms(context, opts?.createOpts?.kms),\n ...(opts?.method && { provider: `${DID_PREFIX}${opts?.method}` }),\n alias: opts?.createOpts?.alias ?? `${IdentifierAliasEnum.PRIMARY}-${opts?.method}-${opts?.createOpts?.options?.type}-${new Date().getTime()}`,\n options: opts?.createOpts?.options,\n })\n}\n\nexport const getFirstKeyWithRelationFromDIDDoc = async (\n {\n identifier,\n vmRelationship = 'verificationMethod',\n keyType,\n errorOnNotFound = false,\n didDocument,\n controllerKey,\n }: {\n identifier: IIdentifier\n controllerKey?: boolean\n vmRelationship?: DIDDocumentSection\n keyType?: TKeyType\n errorOnNotFound?: boolean\n didDocument?: DIDDocument\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<_ExtendedIKey | undefined> => {\n const matchedKeys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship, didDocument }, context)\n if (Array.isArray(matchedKeys) && matchedKeys.length > 0) {\n const result = matchedKeys.find(\n (key) => keyType === undefined || key.type === keyType || (controllerKey && key.kid === identifier.controllerKeyId)\n )\n if (result) {\n return result\n }\n }\n if (errorOnNotFound) {\n throw new Error(\n `Could not find key with relationship ${vmRelationship} in DID document for ${identifier.did}${keyType ? ' and key type: ' + keyType : ''}`\n )\n }\n return undefined\n}\n\nexport const getEthereumAddressFromKey = ({ key }: { key: IKey }) => {\n if (key.type !== 'Secp256k1') {\n throw Error(`Can only get ethereum address from a Secp256k1 key. Type is ${key.type} for keyRef: ${key.kid}`)\n }\n const ethereumAddress = key.meta?.ethereumAddress ?? key.meta?.account?.toLowerCase() ?? computeAddress(`0x${key.publicKeyHex}`).toLowerCase()\n if (!ethereumAddress) {\n throw Error(`Could not get or generate ethereum address from key with keyRef ${key.kid}`)\n }\n return ethereumAddress\n}\n\nexport const getControllerKey = ({ identifier }: { identifier: IIdentifier }) => {\n const key = identifier.keys.find((key) => key.kid === identifier.controllerKeyId)\n if (!key) {\n throw Error(`Could not get controller key for identifier ${identifier}`)\n }\n return key\n}\n\nexport const getKeys = ({\n jwkThumbprint,\n kms,\n identifier,\n kmsKeyRef,\n keyType,\n controllerKey,\n}: {\n identifier: IIdentifier\n kmsKeyRef?: string\n keyType?: TKeyType\n kms?: string\n jwkThumbprint?: string\n controllerKey?: boolean\n}) => {\n return identifier.keys\n .filter((key) => !keyType || key.type === keyType)\n .filter((key) => !kms || key.kms === kms)\n .filter((key) => !kmsKeyRef || key.kid === kmsKeyRef)\n .filter((key) => !jwkThumbprint || key.meta?.jwkThumbprint === jwkThumbprint)\n .filter((key) => !controllerKey || identifier.controllerKeyId === key.kid)\n}\n\n//TODO: Move to ssi-sdk/core and create PR upstream\n/**\n * Dereferences keys from DID document and normalizes them for easy comparison.\n *\n * When dereferencing keyAgreement keys, only Ed25519 and X25519 curves are supported.\n * Other key types are omitted from the result and Ed25519 keys are converted to X25519\n *\n * @returns a Promise that resolves to the list of dereferenced keys.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport async function dereferenceDidKeysWithJwkSupport(\n didDocument: DIDDocument,\n section: DIDDocumentSection = 'keyAgreement',\n context: IAgentContext<IResolver>\n): Promise<_NormalizedVerificationMethod[]> {\n const convert = section === 'keyAgreement'\n if (section === 'service') {\n return []\n }\n return (\n await Promise.all(\n (didDocument[section] || []).map(async (key: string | VerificationMethod) => {\n if (typeof key === 'string') {\n try {\n return (await context.agent.getDIDComponentById({\n didDocument,\n didUrl: key,\n section,\n })) as _ExtendedVerificationMethod\n } catch (e) {\n return null\n }\n } else {\n return key as _ExtendedVerificationMethod\n }\n })\n )\n )\n .filter(isDefined)\n .map((key) => {\n const hexKey = extractPublicKeyHexWithJwkSupport(key, convert)\n const { publicKeyHex, publicKeyBase58, publicKeyBase64, publicKeyJwk, ...keyProps } = key\n const newKey = { ...keyProps, publicKeyHex: hexKey }\n if (convert && 'Ed25519VerificationKey2018' === newKey.type) {\n newKey.type = 'X25519KeyAgreementKey2019'\n }\n return newKey\n })\n}\n\nexport function jwkTtoPublicKeyHex(jwk: JWK): string {\n // todo: Hacky way to convert this to a VM. Should extract the logic from the below methods\n // @ts-ignore\n const vm: _ExtendedVerificationMethod = {\n publicKeyJwk: sanitizedJwk(jwk),\n }\n return extractPublicKeyHexWithJwkSupport(vm)\n}\n\n/**\n * Converts the publicKey of a VerificationMethod to hex encoding (publicKeyHex)\n *\n * @param pk - the VerificationMethod to be converted\n * @param convert - when this flag is set to true, Ed25519 keys are converted to their X25519 pairs\n * @returns the hex encoding of the public key\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport function extractPublicKeyHexWithJwkSupport(pk: _ExtendedVerificationMethod, convert = false): string {\n if (pk.publicKeyJwk) {\n const jwk = sanitizedJwk(pk.publicKeyJwk)\n if (jwk.kty === 'EC') {\n const curve = jwk.crv ? toEcLibCurve(jwk.crv) : 'p256'\n const xHex = base64ToHex(jwk.x!, 'base64url')\n const yHex = base64ToHex(jwk.y!, 'base64url')\n const prefix = '04' // isEven(yHex) ? '02' : '03'\n // Uncompressed Hex format: 04<x><y>\n // Compressed Hex format: 02<x> (for even y) or 03<x> (for uneven y)\n const hex = `${prefix}${xHex}${yHex}`\n try {\n const ec = new elliptic.ec(curve)\n // We return directly as we don't want to convert the result back into Uint8Array and then convert again to hex as the elliptic lib already returns hex strings\n const publicKeyHex = ec.keyFromPublic(hex, 'hex').getPublic(true, 'hex')\n // This returns a short form (x) with 02 or 03 prefix\n return publicKeyHex\n } catch (error: any) {\n console.error(`Error converting EC with elliptic lib curve ${curve} from JWK to hex. x: ${jwk.x}, y: ${jwk.y}, error: ${error}`, error)\n }\n } else if (jwk.crv === 'Ed25519') {\n return toString(fromString(jwk.x!, 'base64url'), 'base16')\n } else if (jwk.kty === 'RSA') {\n return hexKeyFromPEMBasedJwk(jwk, 'public')\n }\n }\n // delegate the other types to the original Veramo function\n return extractPublicKeyHex(pk, convert)\n}\n\nexport function isEvenHexString(hex: string) {\n const lastChar = hex[hex.length - 1].toLowerCase()\n return ['0', '2', '4', '6', '8', 'a', 'c', 'e'].includes(lastChar)\n}\n\ninterface LegacyVerificationMethod extends VerificationMethod {\n publicKeyBase64: string\n}\n\n/**\n * Converts the publicKey of a VerificationMethod to hex encoding (publicKeyHex)\n *\n * @param pk - the VerificationMethod to be converted\n * @param convert - when this flag is set to true, Ed25519 keys are converted to their X25519 pairs\n * @returns the hex encoding of the public key\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport function extractPublicKeyHex(pk: _ExtendedVerificationMethod, convert: boolean = false): string {\n let keyBytes = extractPublicKeyBytes(pk)\n const jwk = pk.publicKeyJwk ? sanitizedJwk(pk.publicKeyJwk) : undefined\n if (convert) {\n if (\n ['Ed25519', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020'].includes(pk.type) ||\n (pk.type === 'JsonWebKey2020' && jwk?.crv === 'Ed25519')\n ) {\n keyBytes = convertPublicKeyToX25519(keyBytes)\n } else if (\n !['X25519', 'X25519KeyAgreementKey2019', 'X25519KeyAgreementKey2020'].includes(pk.type) &&\n !(pk.type === 'JsonWebKey2020' && jwk?.crv === 'X25519')\n ) {\n return ''\n }\n }\n return bytesToHex(keyBytes)\n}\n\nfunction toEcLibCurve(input: string) {\n return input.toLowerCase().replace('-', '').replace('_', '')\n}\n\nfunction extractPublicKeyBytes(pk: VerificationMethod): Uint8Array {\n if (pk.publicKeyBase58) {\n return base58ToBytes(pk.publicKeyBase58)\n } else if (pk.publicKeyMultibase) {\n return multibaseKeyToBytes(pk.publicKeyMultibase)\n } else if ((<LegacyVerificationMethod>pk).publicKeyBase64) {\n return base64ToBytes((<LegacyVerificationMethod>pk).publicKeyBase64)\n } else if (pk.publicKeyHex) {\n return hexToBytes(pk.publicKeyHex)\n } else if (pk.publicKeyJwk?.crv && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return hexToBytes(extractPublicKeyHexWithJwkSupport(pk))\n } else if (pk.publicKeyJwk && (pk.publicKeyJwk.crv === 'Ed25519' || pk.publicKeyJwk.crv === 'X25519') && pk.publicKeyJwk.x) {\n return base64ToBytes(pk.publicKeyJwk.x)\n }\n return new Uint8Array()\n}\n\nexport function verificationMethodToJwk(vm: VerificationMethod): JWK {\n let jwk: JWK | undefined = vm.publicKeyJwk as JWK\n if (!jwk) {\n let publicKeyHex = vm.publicKeyHex ?? toString(extractPublicKeyBytes(vm), 'hex')\n jwk = toJwk(publicKeyHex, keyTypeFromCryptographicSuite({ crv: vm.type }))\n }\n if (!jwk) {\n throw Error(`Could not convert verification method to jwk`)\n }\n jwk.kid = vm.id\n return sanitizedJwk(jwk)\n}\n\nfunction didDocumentSectionToJwks(\n didDocumentSection: DIDDocumentSection,\n searchForVerificationMethods?: (VerificationMethod | string)[],\n verificationMethods?: VerificationMethod[]\n) {\n const jwks = new Set(\n (searchForVerificationMethods ?? [])\n .map((vmOrId) => (typeof vmOrId === 'object' ? vmOrId : verificationMethods?.find((vm) => vm.id === vmOrId)))\n .filter(isDefined)\n .map((vm) => verificationMethodToJwk(vm))\n )\n return { didDocumentSection, jwks: Array.from(jwks) }\n}\n\nexport type DidDocumentJwks = Record<Exclude<DIDDocumentSection, 'publicKey' | 'service'>, Array<JWK>>\n\nexport function didDocumentToJwks(didDocument: DIDDocument): DidDocumentJwks {\n return {\n verificationMethod: [\n ...didDocumentSectionToJwks('publicKey', didDocument.publicKey, didDocument.verificationMethod).jwks, // legacy support\n ...didDocumentSectionToJwks('verificationMethod', didDocument.verificationMethod, didDocument.verificationMethod).jwks,\n ],\n assertionMethod: didDocumentSectionToJwks('assertionMethod', didDocument.assertionMethod, didDocument.verificationMethod).jwks,\n authentication: didDocumentSectionToJwks('authentication', didDocument.authentication, didDocument.verificationMethod).jwks,\n keyAgreement: didDocumentSectionToJwks('keyAgreement', didDocument.keyAgreement, didDocument.verificationMethod).jwks,\n capabilityInvocation: didDocumentSectionToJwks('capabilityInvocation', didDocument.capabilityInvocation, didDocument.verificationMethod).jwks,\n capabilityDelegation: didDocumentSectionToJwks('capabilityDelegation', didDocument.capabilityDelegation, didDocument.verificationMethod).jwks,\n }\n}\n\n/**\n * Maps the keys of a locally managed {@link @veramo/core#IIdentifier | IIdentifier} to the corresponding\n * {@link did-resolver#VerificationMethod | VerificationMethod} entries from the DID document.\n *\n * @param identifier - the identifier to be mapped\n * @param section - the section of the DID document to be mapped (see\n * {@link https://www.w3.org/TR/did-core/#verification-relationships | verification relationships}), but can also be\n * `verificationMethod` to map all the keys.\n * @param didDocument\n * @param context - the veramo agent context, which must contain a {@link @veramo/core#IResolver | IResolver}\n * implementation that can resolve the DID document of the identifier.\n *\n * @returns an array of mapped keys. The corresponding verification method is added to the `meta.verificationMethod`\n * property of the key.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport async function mapIdentifierKeysToDocWithJwkSupport(\n {\n identifier,\n vmRelationship = 'verificationMethod',\n didDocument,\n }: {\n identifier: IIdentifier\n vmRelationship?: DIDDocumentSection\n didDocument?: DIDDocument\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<_ExtendedIKey[]> {\n const didDoc =\n didDocument ??\n (await getAgentResolver(context)\n .resolve(identifier.did)\n .then((result) => result.didDocument))\n if (!didDoc) {\n throw Error(`Could not resolve DID ${identifier.did}`)\n }\n\n // const rsaDidWeb = identifier.keys && identifier.keys.length > 0 && identifier.keys.find((key) => key.type === 'RSA') && didDocument\n\n // We skip mapping in case the identifier is RSA and a did document is supplied.\n const keys = didDoc ? [] : await mapIdentifierKeysToDoc(identifier, vmRelationship, context)\n\n // dereference all key agreement keys from DID document and normalize\n const documentKeys: VerificationMethod[] = await dereferenceDidKeysWithJwkSupport(didDoc, vmRelationship, context)\n\n const localKeys = vmRelationship === 'keyAgreement' ? convertIdentifierEncryptionKeys(identifier) : compressIdentifierSecp256k1Keys(identifier)\n\n // finally map the didDocument keys to the identifier keys by comparing `publicKeyHex`\n const extendedKeys: _ExtendedIKey[] = documentKeys\n .map((verificationMethod) => {\n /*if (verificationMethod.type !== 'JsonWebKey2020') {\n return null\n }*/\n const localKey = localKeys.find(\n (localKey) =>\n localKey.publicKeyHex === verificationMethod.publicKeyHex ||\n verificationMethod.publicKeyHex?.startsWith(localKey.publicKeyHex) ||\n compareBlockchainAccountId(localKey, verificationMethod)\n )\n if (localKey) {\n const { meta, ...localProps } = localKey\n return { ...localProps, meta: { ...meta, verificationMethod } }\n } else {\n return null\n }\n })\n .filter(isDefined)\n\n return keys.concat(extendedKeys)\n}\n\n/**\n * Compares the `blockchainAccountId` of a `EcdsaSecp256k1RecoveryMethod2020` verification method with the address\n * computed from a locally managed key.\n *\n * @returns true if the local key address corresponds to the `blockchainAccountId`\n *\n * @param localKey - The locally managed key\n * @param verificationMethod - a {@link did-resolver#VerificationMethod | VerificationMethod} with a\n * `blockchainAccountId`\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nfunction compareBlockchainAccountId(localKey: IKey, verificationMethod: VerificationMethod): boolean {\n if (\n (verificationMethod.type !== 'EcdsaSecp256k1RecoveryMethod2020' && verificationMethod.type !== 'EcdsaSecp256k1VerificationKey2019') ||\n localKey.type !== 'Secp256k1'\n ) {\n return false\n }\n let vmEthAddr = getEthereumAddress(verificationMethod)\n if (localKey.meta?.account) {\n return vmEthAddr === localKey.meta?.account.toLowerCase()\n }\n const computedAddr = computeAddress('0x' + localKey.publicKeyHex).toLowerCase()\n return computedAddr === vmEthAddr\n}\n\nexport async function getAgentDIDMethods(context: IAgentContext<IDIDManager>) {\n return (await context.agent.didManagerGetProviders()).map((provider) => provider.toLowerCase().replace('did:', ''))\n}\n\nexport function getDID(idOpts: { identifier: IIdentifier | string }): string {\n if (typeof idOpts.identifier === 'string') {\n return idOpts.identifier\n } else if (typeof idOpts.identifier === 'object') {\n return idOpts.identifier.did\n }\n throw Error(`Cannot get DID from identifier value`)\n}\n\nexport function toDID(identifier: string | IIdentifier | Partial<IIdentifier>): string {\n if (typeof identifier === 'string') {\n return identifier\n }\n if (identifier.did) {\n return identifier.did\n }\n throw Error(`No DID value present in identifier`)\n}\n\nexport function toDIDs(identifiers?: (string | IIdentifier | Partial<IIdentifier>)[]): string[] {\n if (!identifiers) {\n return []\n }\n return identifiers.map(toDID)\n}\n\nexport async function getKey(\n {\n identifier,\n vmRelationship = 'authentication',\n kmsKeyRef,\n }: {\n identifier: IIdentifier\n vmRelationship?: DIDDocumentSection\n kmsKeyRef?: string\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<IKey> {\n if (!identifier) {\n return Promise.reject(new Error(`No identifier provided to getKey method!`))\n }\n // normalize to kid, in case keyId was passed in as did#vm or #vm\n const kmsKeyRefParts = kmsKeyRef?.split(`#`)\n const kid = kmsKeyRefParts ? (kmsKeyRefParts?.length === 2 ? kmsKeyRefParts[1] : kmsKeyRefParts[0]) : undefined\n // todo: We really should do a keyRef and external kid here\n let identifierKey = kmsKeyRef ? identifier.keys.find((key: IKey) => key.kid === kid || key?.meta?.jwkThumbprint === kid) : undefined\n if (!identifierKey) {\n const keys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship: vmRelationship }, context)\n if (!keys || keys.length === 0) {\n throw new Error(`No keys found for verificationMethodSection: ${vmRelationship} and did ${identifier.did}`)\n }\n if (kmsKeyRef) {\n identifierKey = keys.find(\n (key: _ExtendedIKey) => key.meta.verificationMethod?.id === kmsKeyRef || (kid && key.meta.verificationMethod?.id?.includes(kid))\n )\n }\n if (!identifierKey) {\n identifierKey = keys.find(\n (key: _ExtendedIKey) => key.meta.verificationMethod?.type === vmRelationship || key.meta.purposes?.includes(vmRelationship)\n )\n }\n if (!identifierKey) {\n identifierKey = keys[0]\n }\n }\n if (!identifierKey) {\n throw new Error(\n `No matching verificationMethodSection key found for keyId: ${kmsKeyRef} and vmSection: ${vmRelationship} for id ${identifier.did}`\n )\n }\n\n return identifierKey\n}\n\n/**\n *\n * @param identifier\n * @param context\n *\n * @deprecated Replaced by the identfier resolution plugin\n */\nasync function legacyGetIdentifier(\n {\n identifier,\n }: {\n identifier: string | IIdentifier\n },\n context: IAgentContext<IDIDManager>\n): Promise<IIdentifier> {\n if (typeof identifier === 'string') {\n return await context.agent.didManagerGet({ did: identifier })\n }\n return identifier\n}\n\n/**\n * Get the real kid as used in JWTs. This is the kid in the VM or in the JWT, not the kid in the Veramo/Sphereon keystore. That was just a poorly chosen name\n * @param key\n * @param idOpts\n * @param context\n */\nexport async function determineKid(\n {\n key,\n idOpts,\n }: {\n key: IKey\n idOpts: { identifier: IIdentifier | string; kmsKeyRef?: string }\n },\n context: IAgentContext<IResolver & IDIDManager>\n): Promise<string> {\n if (key.meta?.verificationMethod?.id) {\n return key.meta?.verificationMethod?.id\n }\n const identifier = await legacyGetIdentifier(idOpts, context)\n const mappedKeys = await mapIdentifierKeysToDocWithJwkSupport(\n {\n identifier,\n vmRelationship: 'verificationMethod',\n },\n context\n )\n const vmKey = mappedKeys.find((extendedKey) => extendedKey.kid === key.kid)\n if (vmKey) {\n return vmKey.meta?.verificationMethod?.id ?? vmKey.meta?.jwkThumbprint ?? idOpts.kmsKeyRef ?? vmKey.kid\n }\n\n return key.meta?.jwkThumbprint ?? idOpts.kmsKeyRef ?? key.kid\n}\n\nexport async function getSupportedDIDMethods(didOpts: IDIDOptions, context: IAgentContext<IDIDManager>) {\n return didOpts.supportedDIDMethods ?? (await getAgentDIDMethods(context))\n}\n\nexport function getAgentResolver(\n context: IAgentContext<IResolver & IDIDManager>,\n opts?: {\n localResolution?: boolean // Resolve identifiers hosted by the agent\n uniresolverResolution?: boolean // Resolve identifiers using universal resolver\n resolverResolution?: boolean // Use registered drivers\n }\n): Resolvable {\n return new AgentDIDResolver(context, opts)\n}\n\nexport class AgentDIDResolver implements Resolvable {\n private readonly context: IAgentContext<IResolver & IDIDManager>\n private readonly resolverResolution: boolean\n private readonly uniresolverResolution: boolean\n private readonly localResolution: boolean\n\n constructor(\n context: IAgentContext<IResolver & IDIDManager>,\n opts?: { uniresolverResolution?: boolean; localResolution?: boolean; resolverResolution?: boolean }\n ) {\n this.context = context\n this.resolverResolution = opts?.resolverResolution !== false\n this.uniresolverResolution = opts?.uniresolverResolution !== false\n this.localResolution = opts?.localResolution !== false\n }\n\n async resolve(didUrl: string, options?: DIDResolutionOptions): Promise<DIDResolutionResult> {\n let resolutionResult: DIDResolutionResult | undefined\n let origResolutionResult: DIDResolutionResult | undefined\n let err: any\n if (!this.resolverResolution && !this.localResolution && !this.uniresolverResolution) {\n throw Error(`No agent hosted DID resolution, regular agent resolution nor universal resolver resolution is enabled. Cannot resolve DIDs.`)\n }\n if (this.resolverResolution) {\n try {\n resolutionResult = await this.context.agent.resolveDid({ didUrl, options })\n } catch (error: unknown) {\n err = error\n }\n }\n if (resolutionResult) {\n origResolutionResult = resolutionResult\n if (resolutionResult.didDocument === null) {\n resolutionResult = undefined\n }\n } else {\n console.log(`Agent resolver resolution is disabled. This typically isn't desirable!`)\n }\n if (!resolutionResult && this.localResolution) {\n console.log(`Using local DID resolution, looking at DIDs hosted by the agent.`)\n try {\n const did = didUrl.split('#')[0]\n const iIdentifier = await this.context.agent.didManagerGet({ did })\n resolutionResult = toDidResolutionResult(iIdentifier, { did })\n if (resolutionResult.didDocument) {\n err = undefined\n } else {\n console.log(`Local resolution resulted in a DID Document for ${did}`)\n }\n } catch (error: unknown) {\n if (!err) {\n err = error\n }\n }\n }\n if (resolutionResult) {\n if (!origResolutionResult) {\n origResolutionResult = resolutionResult\n }\n if (!resolutionResult.didDocument) {\n resolutionResult = undefined\n }\n }\n if (!resolutionResult && this.uniresolverResolution) {\n console.log(`Using universal resolver resolution for did ${didUrl} `)\n resolutionResult = await new UniResolver().resolve(didUrl, options)\n if (!origResolutionResult) {\n origResolutionResult = resolutionResult\n }\n if (resolutionResult.didDocument) {\n err = undefined\n }\n }\n\n if (err) {\n // throw original error\n throw err\n }\n if (!resolutionResult && !origResolutionResult) {\n throw `Could not resolve ${didUrl}. Resolutions tried: online: ${this.resolverResolution}, local: ${this.localResolution}, uni resolver: ${this.uniresolverResolution}`\n }\n return resolutionResult ?? origResolutionResult!\n }\n}\n\n/**\n * Please note that this is not an exact representation of the actual DID Document.\n *\n * We try to do our best, to map keys onto relevant verification methods and relationships, but we simply lack the context\n * of the actual DID method here. Do not relly on this method for DID resolution. It is only handy for offline use cases\n * when no DID Document is cached. For DID:WEB it does provide an accurate representation!\n *\n * @param identifier\n * @param opts\n */\nexport function toDidDocument(\n identifier?: IIdentifier,\n opts?: {\n did?: string\n use?: JwkKeyUse[]\n }\n): DIDDocument | undefined {\n let didDocument: DIDDocument | undefined = undefined\n // TODO: Introduce jwk thumbprints here\n if (identifier) {\n const did = identifier.did ?? opts?.did\n didDocument = {\n '@context': 'https://www.w3.org/ns/did/v1',\n id: did,\n verificationMethod: identifier.keys.map((key) => {\n const vm: VerificationMethod = {\n controller: did,\n id: key.kid.startsWith(did) && key.kid.includes('#') ? key.kid : `${did}#${key.kid}`,\n publicKeyJwk: toJwk(key.publicKeyHex, key.type, {\n use: ENC_KEY_ALGS.includes(key.type) ? JwkKeyUse.Encryption : JwkKeyUse.Signature,\n key,\n }) as JsonWebKey,\n type: 'JsonWebKey2020',\n }\n return vm\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&\n identifier.keys && {\n assertionMethod: identifier.keys\n .filter(\n (key) =>\n key?.meta?.purpose === undefined || key?.meta?.purpose === 'assertionMethod' || key?.meta?.purposes?.includes('assertionMethod')\n )\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&\n identifier.keys && {\n authentication: identifier.keys\n .filter(\n (key) => key?.meta?.purpose === undefined || key?.meta?.purpose === 'authentication' || key?.meta?.purposes?.includes('authentication')\n )\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&\n identifier.keys && {\n keyAgreement: identifier.keys\n .filter((key) => key.type === 'X25519' || key?.meta?.purpose === 'keyAgreement' || key?.meta?.purposes?.includes('keyAgreement'))\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&\n identifier.keys && {\n capabilityInvocation: identifier.keys\n .filter(\n (key) => key.type === 'X25519' || key?.meta?.purpose === 'capabilityInvocation' || key?.meta?.purposes?.includes('capabilityInvocation')\n )\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&\n identifier.keys && {\n capabilityDelegation: identifier.keys\n .filter(\n (key) => key.type === 'X25519' || key?.meta?.purpose === 'capabilityDelegation' || key?.meta?.purposes?.includes('capabilityDelegation')\n )\n .map((key) => {\n if (key.kid.startsWith(did) && key.kid.includes('#')) {\n return key.kid\n }\n return `${did}#${key.kid}`\n }),\n }),\n ...(identifier.services && identifier.services.length > 0 && { service: identifier.services }),\n }\n }\n return didDocument\n}\n\nexport function toDidResolutionResult(\n identifier?: IIdentifier,\n opts?: {\n did?: string\n supportedMethods?: string[]\n }\n): DIDResolutionResult {\n const didDocument = toDidDocument(identifier, opts) ?? null // null is used in case of errors and required by the did resolution spec\n\n const resolutionResult: DIDResolutionResult = {\n '@context': 'https://w3id.org/did-resolution/v1',\n didDocument,\n didResolutionMetadata: {\n ...(!didDocument && { error: 'notFound' }),\n ...(Array.isArray(opts?.supportedMethods) &&\n identifier &&\n !opts?.supportedMethods.includes(identifier.provider.replace('did:', '')) && { error: 'unsupportedDidMethod' }),\n },\n didDocumentMetadata: {\n ...(identifier?.alias && { equivalentId: identifier?.alias }),\n },\n }\n return resolutionResult\n}\n\nexport async function asDidWeb(hostnameOrDID: string): Promise<string> {\n let did = hostnameOrDID\n if (!did) {\n throw Error('Domain or DID expected, but received nothing.')\n }\n if (did.startsWith('did:web:')) {\n return did\n }\n return `did:web:${did.replace(/https?:\\/\\/([^/?#]+).*/i, '$1').toLowerCase()}`\n}\n\n/**\n * @deprecated Replaced by the new signer service\n */\nexport const signDidJWT = async (args: SignJwtArgs): Promise<string> => {\n const { idOpts, header, payload, context, options } = args\n const jwtOptions = {\n ...options,\n signer: await getDidSigner({ idOpts, context }),\n }\n\n return createJWT(payload, jwtOptions, header)\n}\n\n/**\n * @deprecated Replaced by the new signer service\n */\nexport const getDidSigner = async (\n args: GetSignerArgs & {\n idOpts: {\n /**\n * @deprecated\n */\n identifier: IIdentifier | string\n /**\n * @deprecated\n */\n verificationMethodSection?: DIDDocumentSection\n /**\n * @deprecated\n */\n kmsKeyRef?: string\n }\n }\n): Promise<Signer> => {\n const { idOpts, context } = args\n\n const identifier = await legacyGetIdentifier(idOpts, context)\n const key = await getKey(\n {\n identifier,\n vmRelationship: idOpts.verificationMethodSection,\n kmsKeyRef: idOpts.kmsKeyRef,\n },\n context\n )\n const algorithm = await signatureAlgorithmFromKey({ key })\n\n return async (data: string | Uint8Array): Promise<string> => {\n const input = data instanceof Object.getPrototypeOf(Uint8Array) ? new TextDecoder().decode(data as Uint8Array) : (data as string)\n return await context.agent.keyManagerSign({\n keyRef: key.kid,\n algorithm,\n data: input,\n })\n }\n}\n","import { TKeyType } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { IAgentContext, IDIDManager, IIdentifier, IKeyManager, IResolver } from '@veramo/core'\nimport { JWTHeader, JWTPayload, JWTVerifyOptions } from 'did-jwt'\nimport { Resolvable } from 'did-resolver'\n\nexport enum SupportedDidMethodEnum {\n DID_ETHR = 'ethr',\n DID_KEY = 'key',\n DID_LTO = 'lto',\n DID_ION = 'ion',\n DID_EBSI = 'ebsi',\n DID_JWK = 'jwk',\n DID_OYD = 'oyd',\n}\n\nexport enum IdentifierAliasEnum {\n PRIMARY = 'primary',\n}\n\nexport interface ResolveOpts {\n jwtVerifyOpts?: JWTVerifyOptions\n resolver?: Resolvable\n resolveUrl?: string\n noUniversalResolverFallback?: boolean\n subjectSyntaxTypesSupported?: string[]\n}\n\n/**\n * @deprecated Replaced by the identifier resolution service\n */\nexport interface IDIDOptions {\n resolveOpts?: ResolveOpts\n idOpts: LegacyIIdentifierOpts\n supportedDIDMethods?: string[]\n}\n\nexport type IdentifierProviderOpts = {\n type?: TKeyType\n use?: string\n method?: SupportedDidMethodEnum\n [x: string]: any\n}\n\nexport type CreateIdentifierOpts = {\n method: SupportedDidMethodEnum\n createOpts?: CreateIdentifierCreateOpts\n}\n\nexport type CreateIdentifierCreateOpts = {\n kms?: string\n alias?: string\n options?: IdentifierProviderOpts\n}\n\nexport type CreateOrGetIdentifierOpts = {\n method: SupportedDidMethodEnum\n createOpts?: CreateIdentifierCreateOpts\n}\n\nexport const DID_PREFIX = 'did:'\n\nexport interface GetOrCreateResult<T> {\n created: boolean\n result: T\n}\n\n/**\n * @deprecated Replaced by new signer\n */\nexport type SignJwtArgs = {\n idOpts: LegacyIIdentifierOpts\n header: Partial<JWTHeader>\n payload: Partial<JWTPayload>\n options: { issuer: string; expiresIn?: number; canonicalize?: boolean }\n context: IRequiredSignAgentContext\n}\n\n/**\n * @deprecated Replaced by new signer\n */\nexport type GetSignerArgs = {\n idOpts: LegacyIIdentifierOpts\n context: IRequiredSignAgentContext\n}\n\n/**\n * @deprecated Replaced by the identifier resolution service\n */\ntype LegacyIIdentifierOpts = {\n identifier: IIdentifier | string\n}\nexport type IRequiredSignAgentContext = IAgentContext<IKeyManager & IDIDManager & IResolver>\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sphereon/ssi-sdk-ext.did-utils",
3
3
  "description": "DID Utils",
4
- "version": "0.28.1-feature.esm.cjs.8+4c162d1",
4
+ "version": "0.28.1-feature.esm.cjs.9+71682ea",
5
5
  "source": "./src/index.ts",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",
@@ -24,8 +24,8 @@
24
24
  "@ethersproject/networks": "^5.7.1",
25
25
  "@ethersproject/transactions": "^5.7.0",
26
26
  "@sphereon/did-uni-client": "^0.6.3",
27
- "@sphereon/ssi-sdk-ext.key-utils": "^0.28.1-feature.esm.cjs.8+4c162d1",
28
- "@sphereon/ssi-sdk-ext.x509-utils": "^0.28.1-feature.esm.cjs.8+4c162d1",
27
+ "@sphereon/ssi-sdk-ext.key-utils": "^0.28.1-feature.esm.cjs.9+71682ea",
28
+ "@sphereon/ssi-sdk-ext.x509-utils": "^0.28.1-feature.esm.cjs.9+71682ea",
29
29
  "@sphereon/ssi-sdk.agent-config": " ^0.33",
30
30
  "@sphereon/ssi-sdk.core": " ^0.33",
31
31
  "@sphereon/ssi-types": " ^0.33",
@@ -52,5 +52,5 @@
52
52
  "author": "Sphereon <dev@sphereon.com>",
53
53
  "license": "Apache-2.0",
54
54
  "keywords": [],
55
- "gitHead": "4c162d14577f462070adeea3e7ec5a443c324ee7"
55
+ "gitHead": "71682ea0c528f5b32c421245c253b3bc9d6296a0"
56
56
  }