@sphereon/ssi-sdk-ext.did-utils 0.28.1-feature.oyd.cmsm.improv.21 → 0.28.1-next.54

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 ADDED
@@ -0,0 +1,766 @@
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;
8
+ 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
+
71
+ // 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 u8a = __toESM(require("uint8arrays"), 1);
82
+
83
+ // src/types.ts
84
+ var SupportedDidMethodEnum = /* @__PURE__ */ function(SupportedDidMethodEnum2) {
85
+ SupportedDidMethodEnum2["DID_ETHR"] = "ethr";
86
+ SupportedDidMethodEnum2["DID_KEY"] = "key";
87
+ SupportedDidMethodEnum2["DID_LTO"] = "lto";
88
+ SupportedDidMethodEnum2["DID_ION"] = "ion";
89
+ SupportedDidMethodEnum2["DID_EBSI"] = "ebsi";
90
+ SupportedDidMethodEnum2["DID_JWK"] = "jwk";
91
+ SupportedDidMethodEnum2["DID_OYD"] = "oyd";
92
+ return SupportedDidMethodEnum2;
93
+ }({});
94
+ var IdentifierAliasEnum = /* @__PURE__ */ function(IdentifierAliasEnum2) {
95
+ IdentifierAliasEnum2["PRIMARY"] = "primary";
96
+ return IdentifierAliasEnum2;
97
+ }({});
98
+ var DID_PREFIX = "did:";
99
+
100
+ // src/did-functions.ts
101
+ var { fromString, toString } = u8a;
102
+ var getAuthenticationKey = /* @__PURE__ */ __name(async ({ identifier, offlineWhenNoDIDRegistered, noVerificationMethodFallback, keyType, controllerKey }, context) => {
103
+ return await getFirstKeyWithRelation({
104
+ identifier,
105
+ offlineWhenNoDIDRegistered,
106
+ noVerificationMethodFallback,
107
+ keyType,
108
+ controllerKey,
109
+ vmRelationship: "authentication"
110
+ }, context);
111
+ }, "getAuthenticationKey");
112
+ var getFirstKeyWithRelation = /* @__PURE__ */ __name(async ({ identifier, offlineWhenNoDIDRegistered, noVerificationMethodFallback, keyType, controllerKey, vmRelationship }, context) => {
113
+ let key = void 0;
114
+ try {
115
+ key = await getFirstKeyWithRelationFromDIDDoc({
116
+ identifier,
117
+ vmRelationship,
118
+ errorOnNotFound: false,
119
+ keyType,
120
+ controllerKey
121
+ }, context) ?? (noVerificationMethodFallback || vmRelationship === "verificationMethod" ? void 0 : await getFirstKeyWithRelationFromDIDDoc({
122
+ identifier,
123
+ vmRelationship: "verificationMethod",
124
+ errorOnNotFound: false,
125
+ keyType,
126
+ controllerKey
127
+ }, context));
128
+ } catch (e) {
129
+ if (e instanceof Error) {
130
+ if (!e.message.includes("404") || !offlineWhenNoDIDRegistered) {
131
+ throw e;
132
+ }
133
+ } else {
134
+ throw e;
135
+ }
136
+ }
137
+ if (!key && offlineWhenNoDIDRegistered) {
138
+ const offlineDID = toDidDocument(identifier);
139
+ key = await getFirstKeyWithRelationFromDIDDoc({
140
+ identifier,
141
+ vmRelationship,
142
+ errorOnNotFound: false,
143
+ didDocument: offlineDID,
144
+ keyType,
145
+ controllerKey
146
+ }, context) ?? (noVerificationMethodFallback || vmRelationship === "verificationMethod" ? void 0 : await getFirstKeyWithRelationFromDIDDoc({
147
+ identifier,
148
+ vmRelationship: "verificationMethod",
149
+ errorOnNotFound: false,
150
+ didDocument: offlineDID,
151
+ keyType,
152
+ controllerKey
153
+ }, context));
154
+ 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"));
156
+ }
157
+ }
158
+ if (!key) {
159
+ throw Error(`Could not find authentication key for DID ${identifier.did}`);
160
+ }
161
+ return key;
162
+ }, "getFirstKeyWithRelation");
163
+ var getOrCreatePrimaryIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
164
+ const primaryIdentifier = await getPrimaryIdentifier(context, {
165
+ ...opts?.createOpts?.options,
166
+ ...opts?.method && {
167
+ method: opts.method
168
+ }
169
+ });
170
+ if (primaryIdentifier !== void 0) {
171
+ return {
172
+ created: false,
173
+ result: primaryIdentifier
174
+ };
175
+ }
176
+ if (opts?.method === SupportedDidMethodEnum.DID_KEY) {
177
+ const createOpts = opts?.createOpts ?? {};
178
+ createOpts.options = {
179
+ codecName: "EBSI",
180
+ type: "Secp256r1",
181
+ ...createOpts
182
+ };
183
+ opts.createOpts = createOpts;
184
+ }
185
+ const createdIdentifier = await createIdentifier(context, opts);
186
+ return {
187
+ created: true,
188
+ result: createdIdentifier
189
+ };
190
+ }, "getOrCreatePrimaryIdentifier");
191
+ 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));
195
+ return identifiers && identifiers.length > 0 ? identifiers[0] : void 0;
196
+ }, "getPrimaryIdentifier");
197
+ var createIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
198
+ 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}`
202
+ },
203
+ alias: opts?.createOpts?.alias ?? `${IdentifierAliasEnum.PRIMARY}-${opts?.method}-${opts?.createOpts?.options?.type}-${(/* @__PURE__ */ new Date()).getTime()}`,
204
+ options: opts?.createOpts?.options
205
+ });
206
+ }, "createIdentifier");
207
+ var getFirstKeyWithRelationFromDIDDoc = /* @__PURE__ */ __name(async ({ identifier, vmRelationship = "verificationMethod", keyType, errorOnNotFound = false, didDocument, controllerKey }, context) => {
208
+ const matchedKeys = await mapIdentifierKeysToDocWithJwkSupport({
209
+ identifier,
210
+ vmRelationship,
211
+ didDocument
212
+ }, context);
213
+ if (Array.isArray(matchedKeys) && matchedKeys.length > 0) {
214
+ const result = matchedKeys.find((key) => keyType === void 0 || key.type === keyType || controllerKey && key.kid === identifier.controllerKeyId);
215
+ if (result) {
216
+ return result;
217
+ }
218
+ }
219
+ if (errorOnNotFound) {
220
+ throw new Error(`Could not find key with relationship ${vmRelationship} in DID document for ${identifier.did}${keyType ? " and key type: " + keyType : ""}`);
221
+ }
222
+ return void 0;
223
+ }, "getFirstKeyWithRelationFromDIDDoc");
224
+ var getEthereumAddressFromKey = /* @__PURE__ */ __name(({ key }) => {
225
+ if (key.type !== "Secp256k1") {
226
+ throw Error(`Can only get ethereum address from a Secp256k1 key. Type is ${key.type} for keyRef: ${key.kid}`);
227
+ }
228
+ const ethereumAddress = key.meta?.ethereumAddress ?? key.meta?.account?.toLowerCase() ?? (0, import_transactions.computeAddress)(`0x${key.publicKeyHex}`).toLowerCase();
229
+ if (!ethereumAddress) {
230
+ throw Error(`Could not get or generate ethereum address from key with keyRef ${key.kid}`);
231
+ }
232
+ return ethereumAddress;
233
+ }, "getEthereumAddressFromKey");
234
+ var getControllerKey = /* @__PURE__ */ __name(({ identifier }) => {
235
+ const key = identifier.keys.find((key2) => key2.kid === identifier.controllerKeyId);
236
+ if (!key) {
237
+ throw Error(`Could not get controller key for identifier ${identifier}`);
238
+ }
239
+ return key;
240
+ }, "getControllerKey");
241
+ 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);
243
+ }, "getKeys");
244
+ async function dereferenceDidKeysWithJwkSupport(didDocument, section = "keyAgreement", context) {
245
+ const convert = section === "keyAgreement";
246
+ if (section === "service") {
247
+ return [];
248
+ }
249
+ return (await Promise.all((didDocument[section] || []).map(async (key) => {
250
+ if (typeof key === "string") {
251
+ try {
252
+ return await context.agent.getDIDComponentById({
253
+ didDocument,
254
+ didUrl: key,
255
+ section
256
+ });
257
+ } catch (e) {
258
+ return null;
259
+ }
260
+ } else {
261
+ return key;
262
+ }
263
+ }))).filter(import_utils.isDefined).map((key) => {
264
+ const hexKey = extractPublicKeyHexWithJwkSupport(key, convert);
265
+ const { publicKeyHex, publicKeyBase58, publicKeyBase64, publicKeyJwk, ...keyProps } = key;
266
+ const newKey = {
267
+ ...keyProps,
268
+ publicKeyHex: hexKey
269
+ };
270
+ if (convert && "Ed25519VerificationKey2018" === newKey.type) {
271
+ newKey.type = "X25519KeyAgreementKey2019";
272
+ }
273
+ return newKey;
274
+ });
275
+ }
276
+ __name(dereferenceDidKeysWithJwkSupport, "dereferenceDidKeysWithJwkSupport");
277
+ function jwkTtoPublicKeyHex(jwk) {
278
+ const vm = {
279
+ publicKeyJwk: (0, import_ssi_sdk_ext.sanitizedJwk)(jwk)
280
+ };
281
+ return extractPublicKeyHexWithJwkSupport(vm);
282
+ }
283
+ __name(jwkTtoPublicKeyHex, "jwkTtoPublicKeyHex");
284
+ function extractPublicKeyHexWithJwkSupport(pk, convert = false) {
285
+ if (pk.publicKeyJwk) {
286
+ const jwk = (0, import_ssi_sdk_ext.sanitizedJwk)(pk.publicKeyJwk);
287
+ if (jwk.kty === "EC") {
288
+ 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");
291
+ const prefix = "04";
292
+ const hex = `${prefix}${xHex}${yHex}`;
293
+ try {
294
+ const ec = new import_elliptic.default.ec(curve);
295
+ const publicKeyHex = ec.keyFromPublic(hex, "hex").getPublic(true, "hex");
296
+ return publicKeyHex;
297
+ } catch (error) {
298
+ console.error(`Error converting EC with elliptic lib curve ${curve} from JWK to hex. x: ${jwk.x}, y: ${jwk.y}, error: ${error}`, error);
299
+ }
300
+ } else if (jwk.crv === "Ed25519") {
301
+ return toString(fromString(jwk.x, "base64url"), "base16");
302
+ } else if (jwk.kty === "RSA") {
303
+ return (0, import_ssi_sdk_ext.rsaJwkToRawHexKey)(jwk);
304
+ }
305
+ }
306
+ return extractPublicKeyHex(pk, convert);
307
+ }
308
+ __name(extractPublicKeyHexWithJwkSupport, "extractPublicKeyHexWithJwkSupport");
309
+ function isEvenHexString(hex) {
310
+ const lastChar = hex[hex.length - 1].toLowerCase();
311
+ return [
312
+ "0",
313
+ "2",
314
+ "4",
315
+ "6",
316
+ "8",
317
+ "a",
318
+ "c",
319
+ "e"
320
+ ].includes(lastChar);
321
+ }
322
+ __name(isEvenHexString, "isEvenHexString");
323
+ function extractPublicKeyHex(pk, convert = false) {
324
+ let keyBytes = extractPublicKeyBytes(pk);
325
+ const jwk = pk.publicKeyJwk ? (0, import_ssi_sdk_ext.sanitizedJwk)(pk.publicKeyJwk) : void 0;
326
+ if (convert) {
327
+ if ([
328
+ "Ed25519",
329
+ "Ed25519VerificationKey2018",
330
+ "Ed25519VerificationKey2020"
331
+ ].includes(pk.type) || pk.type === "JsonWebKey2020" && jwk?.crv === "Ed25519") {
332
+ keyBytes = (0, import_ed25519.convertPublicKeyToX25519)(keyBytes);
333
+ } else if (![
334
+ "X25519",
335
+ "X25519KeyAgreementKey2019",
336
+ "X25519KeyAgreementKey2020"
337
+ ].includes(pk.type) && !(pk.type === "JsonWebKey2020" && jwk?.crv === "X25519")) {
338
+ return "";
339
+ }
340
+ }
341
+ return (0, import_ssi_sdk.bytesToHex)(keyBytes);
342
+ }
343
+ __name(extractPublicKeyHex, "extractPublicKeyHex");
344
+ function toEcLibCurve(input) {
345
+ return input.toLowerCase().replace("-", "").replace("_", "");
346
+ }
347
+ __name(toEcLibCurve, "toEcLibCurve");
348
+ function extractPublicKeyBytes(pk) {
349
+ if (pk.publicKeyBase58) {
350
+ return (0, import_ssi_sdk.base58ToBytes)(pk.publicKeyBase58);
351
+ } else if (pk.publicKeyMultibase) {
352
+ return (0, import_ssi_sdk.multibaseKeyToBytes)(pk.publicKeyMultibase);
353
+ } else if (pk.publicKeyBase64) {
354
+ return (0, import_ssi_sdk.base64ToBytes)(pk.publicKeyBase64);
355
+ } 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));
359
+ } 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);
361
+ }
362
+ return new Uint8Array();
363
+ }
364
+ __name(extractPublicKeyBytes, "extractPublicKeyBytes");
365
+ function verificationMethodToJwk(vm, errorOnNotFound = true) {
366
+ let jwk = vm.publicKeyJwk;
367
+ if (!jwk) {
368
+ let publicKeyHex = vm.publicKeyHex ?? toString(extractPublicKeyBytes(vm), "hex");
369
+ if (publicKeyHex && publicKeyHex.trim() !== "") {
370
+ jwk = (0, import_ssi_sdk_ext.toJwk)(publicKeyHex, (0, import_ssi_sdk_ext.keyTypeFromCryptographicSuite)({
371
+ crv: vm.type
372
+ }));
373
+ }
374
+ }
375
+ if (!jwk) {
376
+ if (errorOnNotFound) {
377
+ throw Error(`Could not convert verification method ${vm.id} to jwk`);
378
+ }
379
+ return null;
380
+ }
381
+ jwk.kid = vm.id;
382
+ return (0, import_ssi_sdk_ext.sanitizedJwk)(jwk);
383
+ }
384
+ __name(verificationMethodToJwk, "verificationMethodToJwk");
385
+ function didDocumentSectionToJwks(didDocumentSection, searchForVerificationMethods, verificationMethods) {
386
+ 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, false)).filter(import_utils.isDefined));
387
+ return {
388
+ didDocumentSection,
389
+ jwks: Array.from(jwks)
390
+ };
391
+ }
392
+ __name(didDocumentSectionToJwks, "didDocumentSectionToJwks");
393
+ function didDocumentToJwks(didDocument) {
394
+ return {
395
+ verificationMethod: [
396
+ ...didDocumentSectionToJwks("publicKey", didDocument.publicKey, didDocument.verificationMethod).jwks,
397
+ ...didDocumentSectionToJwks("verificationMethod", didDocument.verificationMethod, didDocument.verificationMethod).jwks
398
+ ],
399
+ assertionMethod: didDocumentSectionToJwks("assertionMethod", didDocument.assertionMethod, didDocument.verificationMethod).jwks,
400
+ authentication: didDocumentSectionToJwks("authentication", didDocument.authentication, didDocument.verificationMethod).jwks,
401
+ keyAgreement: didDocumentSectionToJwks("keyAgreement", didDocument.keyAgreement, didDocument.verificationMethod).jwks,
402
+ capabilityInvocation: didDocumentSectionToJwks("capabilityInvocation", didDocument.capabilityInvocation, didDocument.verificationMethod).jwks,
403
+ capabilityDelegation: didDocumentSectionToJwks("capabilityDelegation", didDocument.capabilityDelegation, didDocument.verificationMethod).jwks
404
+ };
405
+ }
406
+ __name(didDocumentToJwks, "didDocumentToJwks");
407
+ async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship = "verificationMethod", didDocument, kmsKeyRef }, context) {
408
+ const didDoc = didDocument ?? await getAgentResolver(context).resolve(identifier.did).then((result) => result.didDocument);
409
+ if (!didDoc) {
410
+ throw Error(`Could not resolve DID ${identifier.did}`);
411
+ }
412
+ const keys = didDoc ? [] : await (0, import_utils.mapIdentifierKeysToDoc)(identifier, vmRelationship, context);
413
+ const documentKeys = await dereferenceDidKeysWithJwkSupport(didDoc, vmRelationship, context);
414
+ if (kmsKeyRef) {
415
+ let found = keys.filter((key) => key.kid === kmsKeyRef);
416
+ if (found.length > 0) {
417
+ return found;
418
+ }
419
+ }
420
+ const localKeys = vmRelationship === "keyAgreement" ? (0, import_utils.convertIdentifierEncryptionKeys)(identifier) : (0, import_utils.compressIdentifierSecp256k1Keys)(identifier);
421
+ const extendedKeys = documentKeys.map((verificationMethod) => {
422
+ let vmKey = verificationMethod.publicKeyHex;
423
+ if (vmKey?.startsWith("30")) {
424
+ vmKey = (0, import_ssi_sdk_ext.toPkcs1FromHex)(vmKey);
425
+ }
426
+ const localKey = localKeys.find((localKey2) => localKey2.publicKeyHex === vmKey || localKey2.type === "RSA" && vmKey?.startsWith("30") && (0, import_ssi_sdk_ext.toPkcs1FromHex)(localKey2.publicKeyHex) === vmKey || vmKey?.startsWith(localKey2.publicKeyHex) || compareBlockchainAccountId(localKey2, verificationMethod));
427
+ if (localKey) {
428
+ const { meta, ...localProps } = localKey;
429
+ return {
430
+ ...localProps,
431
+ meta: {
432
+ ...meta,
433
+ verificationMethod
434
+ }
435
+ };
436
+ } else {
437
+ return null;
438
+ }
439
+ }).filter(import_utils.isDefined);
440
+ return Array.from(new Set(keys.concat(extendedKeys)));
441
+ }
442
+ __name(mapIdentifierKeysToDocWithJwkSupport, "mapIdentifierKeysToDocWithJwkSupport");
443
+ function compareBlockchainAccountId(localKey, verificationMethod) {
444
+ if (verificationMethod.type !== "EcdsaSecp256k1RecoveryMethod2020" && verificationMethod.type !== "EcdsaSecp256k1VerificationKey2019" || localKey.type !== "Secp256k1") {
445
+ return false;
446
+ }
447
+ let vmEthAddr = (0, import_utils.getEthereumAddress)(verificationMethod);
448
+ if (localKey.meta?.account) {
449
+ return vmEthAddr === localKey.meta?.account.toLowerCase();
450
+ }
451
+ const computedAddr = (0, import_transactions.computeAddress)("0x" + localKey.publicKeyHex).toLowerCase();
452
+ return computedAddr === vmEthAddr;
453
+ }
454
+ __name(compareBlockchainAccountId, "compareBlockchainAccountId");
455
+ async function getAgentDIDMethods(context) {
456
+ return (await context.agent.didManagerGetProviders()).map((provider) => provider.toLowerCase().replace("did:", ""));
457
+ }
458
+ __name(getAgentDIDMethods, "getAgentDIDMethods");
459
+ function getDID(idOpts) {
460
+ if (typeof idOpts.identifier === "string") {
461
+ return idOpts.identifier;
462
+ } else if (typeof idOpts.identifier === "object") {
463
+ return idOpts.identifier.did;
464
+ }
465
+ throw Error(`Cannot get DID from identifier value`);
466
+ }
467
+ __name(getDID, "getDID");
468
+ function toDID(identifier) {
469
+ if (typeof identifier === "string") {
470
+ return identifier;
471
+ }
472
+ if (identifier.did) {
473
+ return identifier.did;
474
+ }
475
+ throw Error(`No DID value present in identifier`);
476
+ }
477
+ __name(toDID, "toDID");
478
+ function toDIDs(identifiers) {
479
+ if (!identifiers) {
480
+ return [];
481
+ }
482
+ return identifiers.map(toDID);
483
+ }
484
+ __name(toDIDs, "toDIDs");
485
+ async function getKey({ identifier, vmRelationship = "authentication", kmsKeyRef }, context) {
486
+ if (!identifier) {
487
+ return Promise.reject(new Error(`No identifier provided to getKey method!`));
488
+ }
489
+ const kmsKeyRefParts = kmsKeyRef?.split(`#`);
490
+ const kid = kmsKeyRefParts ? kmsKeyRefParts?.length === 2 ? kmsKeyRefParts[1] : kmsKeyRefParts[0] : void 0;
491
+ let identifierKey = void 0;
492
+ const keys = await mapIdentifierKeysToDocWithJwkSupport({
493
+ identifier,
494
+ vmRelationship,
495
+ kmsKeyRef
496
+ }, context);
497
+ if (!keys || keys.length === 0) {
498
+ throw new Error(`No keys found for verificationMethodSection: ${vmRelationship} and did ${identifier.did}`);
499
+ }
500
+ if (kmsKeyRef) {
501
+ identifierKey = keys.find((key) => key.meta.verificationMethod?.id === kmsKeyRef || kid && key.meta.verificationMethod?.id?.includes(kid));
502
+ }
503
+ if (!identifierKey) {
504
+ identifierKey = keys.find((key) => key.meta.verificationMethod?.type === vmRelationship || key.meta.purposes?.includes(vmRelationship));
505
+ }
506
+ if (!identifierKey) {
507
+ identifierKey = keys[0];
508
+ }
509
+ if (!identifierKey) {
510
+ throw new Error(`No matching verificationMethodSection key found for keyId: ${kmsKeyRef} and vmSection: ${vmRelationship} for id ${identifier.did}`);
511
+ }
512
+ return identifierKey;
513
+ }
514
+ __name(getKey, "getKey");
515
+ async function legacyGetIdentifier({ identifier }, context) {
516
+ if (typeof identifier === "string") {
517
+ return await context.agent.didManagerGet({
518
+ did: identifier
519
+ });
520
+ }
521
+ return identifier;
522
+ }
523
+ __name(legacyGetIdentifier, "legacyGetIdentifier");
524
+ async function determineKid({ key, idOpts }, context) {
525
+ if (key.meta?.verificationMethod?.id) {
526
+ return key.meta?.verificationMethod?.id;
527
+ }
528
+ const identifier = await legacyGetIdentifier(idOpts, context);
529
+ const mappedKeys = await mapIdentifierKeysToDocWithJwkSupport({
530
+ identifier,
531
+ vmRelationship: "verificationMethod"
532
+ }, context);
533
+ const vmKey = mappedKeys.find((extendedKey) => extendedKey.kid === key.kid);
534
+ if (vmKey) {
535
+ return vmKey.meta?.verificationMethod?.id ?? vmKey.meta?.jwkThumbprint ?? idOpts.kmsKeyRef ?? vmKey.kid;
536
+ }
537
+ return key.meta?.jwkThumbprint ?? idOpts.kmsKeyRef ?? key.kid;
538
+ }
539
+ __name(determineKid, "determineKid");
540
+ async function getSupportedDIDMethods(didOpts, context) {
541
+ return didOpts.supportedDIDMethods ?? await getAgentDIDMethods(context);
542
+ }
543
+ __name(getSupportedDIDMethods, "getSupportedDIDMethods");
544
+ function getAgentResolver(context, opts) {
545
+ return new AgentDIDResolver(context, opts);
546
+ }
547
+ __name(getAgentResolver, "getAgentResolver");
548
+ var AgentDIDResolver = class {
549
+ static {
550
+ __name(this, "AgentDIDResolver");
551
+ }
552
+ context;
553
+ resolverResolution;
554
+ uniresolverResolution;
555
+ localResolution;
556
+ constructor(context, opts) {
557
+ this.context = context;
558
+ this.resolverResolution = opts?.resolverResolution !== false;
559
+ this.uniresolverResolution = opts?.uniresolverResolution !== false;
560
+ this.localResolution = opts?.localResolution !== false;
561
+ }
562
+ async resolve(didUrl, options) {
563
+ let resolutionResult;
564
+ let origResolutionResult;
565
+ let err;
566
+ if (!this.resolverResolution && !this.localResolution && !this.uniresolverResolution) {
567
+ throw Error(`No agent hosted DID resolution, regular agent resolution nor universal resolver resolution is enabled. Cannot resolve DIDs.`);
568
+ }
569
+ if (this.resolverResolution) {
570
+ try {
571
+ resolutionResult = await this.context.agent.resolveDid({
572
+ didUrl,
573
+ options
574
+ });
575
+ } catch (error) {
576
+ err = error;
577
+ }
578
+ }
579
+ if (resolutionResult) {
580
+ origResolutionResult = resolutionResult;
581
+ if (resolutionResult.didDocument === null) {
582
+ resolutionResult = void 0;
583
+ }
584
+ } else {
585
+ console.log(`Agent resolver resolution is disabled. This typically isn't desirable!`);
586
+ }
587
+ if (!resolutionResult && this.localResolution) {
588
+ console.log(`Using local DID resolution, looking at DIDs hosted by the agent.`);
589
+ try {
590
+ const did = didUrl.split("#")[0];
591
+ const iIdentifier = await this.context.agent.didManagerGet({
592
+ did
593
+ });
594
+ resolutionResult = toDidResolutionResult(iIdentifier, {
595
+ did
596
+ });
597
+ if (resolutionResult.didDocument) {
598
+ err = void 0;
599
+ } else {
600
+ console.log(`Local resolution resulted in a DID Document for ${did}`);
601
+ }
602
+ } catch (error) {
603
+ if (!err) {
604
+ err = error;
605
+ }
606
+ }
607
+ }
608
+ if (resolutionResult) {
609
+ if (!origResolutionResult) {
610
+ origResolutionResult = resolutionResult;
611
+ }
612
+ if (!resolutionResult.didDocument) {
613
+ resolutionResult = void 0;
614
+ }
615
+ }
616
+ if (!resolutionResult && this.uniresolverResolution) {
617
+ console.log(`Using universal resolver resolution for did ${didUrl} `);
618
+ resolutionResult = await new import_did_uni_client.UniResolver().resolve(didUrl, options);
619
+ if (!origResolutionResult) {
620
+ origResolutionResult = resolutionResult;
621
+ }
622
+ if (resolutionResult.didDocument) {
623
+ err = void 0;
624
+ }
625
+ }
626
+ if (err) {
627
+ throw err;
628
+ }
629
+ if (!resolutionResult && !origResolutionResult) {
630
+ throw `Could not resolve ${didUrl}. Resolutions tried: online: ${this.resolverResolution}, local: ${this.localResolution}, uni resolver: ${this.uniresolverResolution}`;
631
+ }
632
+ return resolutionResult ?? origResolutionResult;
633
+ }
634
+ };
635
+ function toDidDocument(identifier, opts) {
636
+ let didDocument = void 0;
637
+ if (identifier) {
638
+ const did = identifier.did ?? opts?.did;
639
+ didDocument = {
640
+ "@context": "https://www.w3.org/ns/did/v1",
641
+ id: did,
642
+ verificationMethod: identifier.keys.map((key) => {
643
+ const vm = {
644
+ controller: did,
645
+ id: key.kid.startsWith(did) && key.kid.includes("#") ? key.kid : `${did}#${key.kid}`,
646
+ publicKeyJwk: (0, import_ssi_sdk_ext.toJwk)(key.publicKeyHex, key.type, {
647
+ use: import_ssi_sdk_ext.ENC_KEY_ALGS.includes(key.type) ? import_ssi_sdk_ext.JwkKeyUse.Encryption : import_ssi_sdk_ext.JwkKeyUse.Signature,
648
+ key
649
+ }),
650
+ type: "JsonWebKey2020"
651
+ };
652
+ return vm;
653
+ }),
654
+ ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
655
+ assertionMethod: identifier.keys.filter((key) => key?.meta?.purpose === void 0 || key?.meta?.purpose === "assertionMethod" || key?.meta?.purposes?.includes("assertionMethod")).map((key) => {
656
+ if (key.kid.startsWith(did) && key.kid.includes("#")) {
657
+ return key.kid;
658
+ }
659
+ return `${did}#${key.kid}`;
660
+ })
661
+ },
662
+ ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
663
+ authentication: identifier.keys.filter((key) => key?.meta?.purpose === void 0 || key?.meta?.purpose === "authentication" || key?.meta?.purposes?.includes("authentication")).map((key) => {
664
+ if (key.kid.startsWith(did) && key.kid.includes("#")) {
665
+ return key.kid;
666
+ }
667
+ return `${did}#${key.kid}`;
668
+ })
669
+ },
670
+ ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
671
+ keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "keyAgreement" || key?.meta?.purposes?.includes("keyAgreement")).map((key) => {
672
+ if (key.kid.startsWith(did) && key.kid.includes("#")) {
673
+ return key.kid;
674
+ }
675
+ return `${did}#${key.kid}`;
676
+ })
677
+ },
678
+ ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
679
+ capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "capabilityInvocation" || key?.meta?.purposes?.includes("capabilityInvocation")).map((key) => {
680
+ if (key.kid.startsWith(did) && key.kid.includes("#")) {
681
+ return key.kid;
682
+ }
683
+ return `${did}#${key.kid}`;
684
+ })
685
+ },
686
+ ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
687
+ capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "capabilityDelegation" || key?.meta?.purposes?.includes("capabilityDelegation")).map((key) => {
688
+ if (key.kid.startsWith(did) && key.kid.includes("#")) {
689
+ return key.kid;
690
+ }
691
+ return `${did}#${key.kid}`;
692
+ })
693
+ },
694
+ ...identifier.services && identifier.services.length > 0 && {
695
+ service: identifier.services
696
+ }
697
+ };
698
+ }
699
+ return didDocument;
700
+ }
701
+ __name(toDidDocument, "toDidDocument");
702
+ function toDidResolutionResult(identifier, opts) {
703
+ const didDocument = toDidDocument(identifier, opts) ?? null;
704
+ const resolutionResult = {
705
+ "@context": "https://w3id.org/did-resolution/v1",
706
+ didDocument,
707
+ didResolutionMetadata: {
708
+ ...!didDocument && {
709
+ error: "notFound"
710
+ },
711
+ ...Array.isArray(opts?.supportedMethods) && identifier && !opts?.supportedMethods.includes(identifier.provider.replace("did:", "")) && {
712
+ error: "unsupportedDidMethod"
713
+ }
714
+ },
715
+ didDocumentMetadata: {
716
+ ...identifier?.alias && {
717
+ equivalentId: identifier?.alias
718
+ }
719
+ }
720
+ };
721
+ return resolutionResult;
722
+ }
723
+ __name(toDidResolutionResult, "toDidResolutionResult");
724
+ async function asDidWeb(hostnameOrDID) {
725
+ let did = hostnameOrDID;
726
+ if (!did) {
727
+ throw Error("Domain or DID expected, but received nothing.");
728
+ }
729
+ if (did.startsWith("did:web:")) {
730
+ return did;
731
+ }
732
+ return `did:web:${did.replace(/https?:\/\/([^/?#]+).*/i, "$1").toLowerCase()}`;
733
+ }
734
+ __name(asDidWeb, "asDidWeb");
735
+ var signDidJWT = /* @__PURE__ */ __name(async (args) => {
736
+ const { idOpts, header, payload, context, options } = args;
737
+ const jwtOptions = {
738
+ ...options,
739
+ signer: await getDidSigner({
740
+ idOpts,
741
+ context
742
+ })
743
+ };
744
+ return (0, import_did_jwt.createJWT)(payload, jwtOptions, header);
745
+ }, "signDidJWT");
746
+ var getDidSigner = /* @__PURE__ */ __name(async (args) => {
747
+ const { idOpts, context } = args;
748
+ const identifier = await legacyGetIdentifier(idOpts, context);
749
+ const key = await getKey({
750
+ identifier,
751
+ vmRelationship: idOpts.verificationMethodSection,
752
+ kmsKeyRef: idOpts.kmsKeyRef
753
+ }, context);
754
+ const algorithm = await (0, import_ssi_sdk_ext.signatureAlgorithmFromKey)({
755
+ key
756
+ });
757
+ return async (data) => {
758
+ const input = data instanceof Object.getPrototypeOf(Uint8Array) ? new TextDecoder().decode(data) : data;
759
+ return await context.agent.keyManagerSign({
760
+ keyRef: key.kid,
761
+ algorithm,
762
+ data: input
763
+ });
764
+ };
765
+ }, "getDidSigner");
766
+ //# sourceMappingURL=index.cjs.map