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

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