@sphereon/ssi-sdk-ext.did-utils 0.36.1-next.50 → 0.37.0

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
@@ -193,7 +193,22 @@ var getPrimaryIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
193
193
  const identifiers = (await context.agent.didManagerFind(opts?.method ? {
194
194
  provider: `${DID_PREFIX}${opts?.method}`
195
195
  } : {})).filter((identifier) => opts?.type === void 0 || identifier.keys.some((key) => key.type === opts?.type));
196
- return identifiers && identifiers.length > 0 ? identifiers[0] : void 0;
196
+ if (!identifiers || identifiers.length === 0) {
197
+ return void 0;
198
+ }
199
+ if (opts?.did) {
200
+ const didMatch = identifiers.find((identifier) => identifier.did === opts.did);
201
+ if (didMatch) {
202
+ return didMatch;
203
+ }
204
+ }
205
+ if (opts?.alias) {
206
+ const aliasMatch = identifiers.find((identifier) => identifier.alias === opts.alias);
207
+ if (aliasMatch) {
208
+ return aliasMatch;
209
+ }
210
+ }
211
+ return identifiers[0];
197
212
  }, "getPrimaryIdentifier");
198
213
  var createIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
199
214
  return await context.agent.didManagerCreate({
@@ -212,7 +227,8 @@ var getFirstKeyWithRelationFromDIDDoc = /* @__PURE__ */ __name(async ({ identifi
212
227
  didDocument
213
228
  }, context);
214
229
  if (Array.isArray(matchedKeys) && matchedKeys.length > 0) {
215
- const result = matchedKeys.find((key) => keyType === void 0 || key.type === keyType || controllerKey && key.kid === identifier.controllerKeyId);
230
+ const controllerKeyMatch = identifier.controllerKeyId ? matchedKeys.find((key) => key.kid === identifier.controllerKeyId && (keyType === void 0 || key.type === keyType)) : void 0;
231
+ const result = controllerKeyMatch ?? matchedKeys.find((key) => keyType === void 0 || key.type === keyType);
216
232
  if (result) {
217
233
  return result;
218
234
  }
@@ -422,7 +438,21 @@ async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship
422
438
  const extendedKeys = documentKeys.map((verificationMethod) => {
423
439
  let vmKey = verificationMethod.publicKeyHex;
424
440
  if (vmKey?.startsWith("30")) {
425
- vmKey = (0, import_ssi_sdk_ext.toPkcs1FromHex)(vmKey);
441
+ const vmType = verificationMethod.type;
442
+ const isEdKey = [
443
+ "Ed25519",
444
+ "Ed25519VerificationKey2018",
445
+ "Ed25519VerificationKey2020",
446
+ "X25519",
447
+ "X25519KeyAgreementKey2019",
448
+ "X25519KeyAgreementKey2020"
449
+ ].includes(vmType) || vmType === "JsonWebKey2020" && [
450
+ "Ed25519",
451
+ "X25519"
452
+ ].includes(verificationMethod.publicKeyJwk?.crv);
453
+ if (!isEdKey) {
454
+ vmKey = (0, import_ssi_sdk_ext.toPkcs1FromHex)(vmKey);
455
+ }
426
456
  }
427
457
  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));
428
458
  if (localKey) {
@@ -438,7 +468,17 @@ async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship
438
468
  return null;
439
469
  }
440
470
  }).filter(import_utils.isDefined);
441
- return Array.from(new Set(keys.concat(extendedKeys)));
471
+ const allKeys = Array.from(new Set(keys.concat(extendedKeys)));
472
+ if (vmRelationship === "verificationMethod") {
473
+ return allKeys;
474
+ }
475
+ return allKeys.filter((key) => {
476
+ const purposes = key.meta?.purposes;
477
+ if (!purposes || purposes.length === 0) {
478
+ return true;
479
+ }
480
+ return purposes.includes(vmRelationship);
481
+ });
442
482
  }
443
483
  __name(mapIdentifierKeysToDocWithJwkSupport, "mapIdentifierKeysToDocWithJwkSupport");
444
484
  function compareBlockchainAccountId(localKey, verificationMethod) {
@@ -633,6 +673,7 @@ var AgentDIDResolver = class {
633
673
  return resolutionResult ?? origResolutionResult;
634
674
  }
635
675
  };
676
+ var hasPurpose = /* @__PURE__ */ __name((key, purpose) => key?.meta?.purpose === void 0 && key?.meta?.purposes === void 0 || key?.meta?.purpose === purpose || key?.meta?.purposes?.includes(purpose), "hasPurpose");
636
677
  function toDidDocument(identifier, opts) {
637
678
  let didDocument = void 0;
638
679
  if (identifier) {
@@ -641,19 +682,20 @@ function toDidDocument(identifier, opts) {
641
682
  "@context": "https://www.w3.org/ns/did/v1",
642
683
  id: did,
643
684
  verificationMethod: identifier.keys.map((key) => {
685
+ const publicKeyJwk = key.meta?.jwk ? (0, import_ssi_sdk_ext.sanitizedJwk)(key.meta.jwk) : (0, import_ssi_sdk_ext.toJwk)(key.publicKeyHex, key.type, {
686
+ use: import_ssi_sdk_ext.ENC_KEY_ALGS.includes(key.type) ? import_ssi_sdk_ext.JwkKeyUse.Encryption : import_ssi_sdk_ext.JwkKeyUse.Signature,
687
+ key
688
+ });
644
689
  const vm = {
645
690
  controller: did,
646
691
  id: key.kid.startsWith(did) && key.kid.includes("#") ? key.kid : `${did}#${key.kid}`,
647
- publicKeyJwk: (0, import_ssi_sdk_ext.toJwk)(key.publicKeyHex, key.type, {
648
- use: import_ssi_sdk_ext.ENC_KEY_ALGS.includes(key.type) ? import_ssi_sdk_ext.JwkKeyUse.Encryption : import_ssi_sdk_ext.JwkKeyUse.Signature,
649
- key
650
- }),
692
+ publicKeyJwk,
651
693
  type: "JsonWebKey2020"
652
694
  };
653
695
  return vm;
654
696
  }),
655
697
  ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
656
- assertionMethod: identifier.keys.filter((key) => key?.meta?.purpose === void 0 || key?.meta?.purpose === "assertionMethod" || key?.meta?.purposes?.includes("assertionMethod")).map((key) => {
698
+ assertionMethod: identifier.keys.filter((key) => hasPurpose(key, "assertionMethod")).map((key) => {
657
699
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
658
700
  return key.kid;
659
701
  }
@@ -661,7 +703,7 @@ function toDidDocument(identifier, opts) {
661
703
  })
662
704
  },
663
705
  ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
664
- authentication: identifier.keys.filter((key) => key?.meta?.purpose === void 0 || key?.meta?.purpose === "authentication" || key?.meta?.purposes?.includes("authentication")).map((key) => {
706
+ authentication: identifier.keys.filter((key) => hasPurpose(key, "authentication")).map((key) => {
665
707
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
666
708
  return key.kid;
667
709
  }
@@ -669,7 +711,7 @@ function toDidDocument(identifier, opts) {
669
711
  })
670
712
  },
671
713
  ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
672
- keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "keyAgreement" || key?.meta?.purposes?.includes("keyAgreement")).map((key) => {
714
+ keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "keyAgreement")).map((key) => {
673
715
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
674
716
  return key.kid;
675
717
  }
@@ -677,7 +719,7 @@ function toDidDocument(identifier, opts) {
677
719
  })
678
720
  },
679
721
  ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
680
- capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "capabilityInvocation" || key?.meta?.purposes?.includes("capabilityInvocation")).map((key) => {
722
+ capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityInvocation")).map((key) => {
681
723
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
682
724
  return key.kid;
683
725
  }
@@ -685,7 +727,7 @@ function toDidDocument(identifier, opts) {
685
727
  })
686
728
  },
687
729
  ...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
688
- capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "capabilityDelegation" || key?.meta?.purposes?.includes("capabilityDelegation")).map((key) => {
730
+ capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityDelegation")).map((key) => {
689
731
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
690
732
  return key.kid;
691
733
  }
@@ -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 rsaJwkToRawHexKey,\n sanitizedJwk,\n signatureAlgorithmFromKey,\n type TKeyType,\n toJwk,\n toPkcs1FromHex,\n} from '@sphereon/ssi-sdk-ext.key-utils'\nimport { base64ToHex } from '@sphereon/ssi-sdk-ext.x509-utils'\nimport { base58ToBytes, base64ToBytes, bytesToHex, hexToBytes, multibaseKeyToBytes } from '@sphereon/ssi-sdk.core'\nimport type { JWK } from '@sphereon/ssi-types'\nimport { convertPublicKeyToX25519 } from '@stablelib/ed25519'\nimport type { DIDDocument, DIDDocumentSection, DIDResolutionResult, IAgentContext, IDIDManager, IIdentifier, IKey, IResolver } from '@veramo/core'\nimport {\n type _ExtendedIKey,\n type _ExtendedVerificationMethod,\n type _NormalizedVerificationMethod,\n compressIdentifierSecp256k1Keys,\n convertIdentifierEncryptionKeys,\n getEthereumAddress,\n isDefined,\n mapIdentifierKeysToDoc,\n} from '@veramo/utils'\nimport { createJWT, Signer } from 'did-jwt'\nimport type { DIDResolutionOptions, JsonWebKey, Resolvable, VerificationMethod } from 'did-resolver'\n// @ts-ignore\nimport elliptic from 'elliptic'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nimport {\n type CreateIdentifierOpts,\n type CreateOrGetIdentifierOpts,\n DID_PREFIX,\n type GetOrCreateResult,\n type GetSignerArgs,\n IdentifierAliasEnum,\n type IdentifierProviderOpts,\n type IDIDOptions,\n type SignJwtArgs,\n SupportedDidMethodEnum,\n} from './types'\n\nconst { fromString, toString } = u8a\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 rsaJwkToRawHexKey(jwk)\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, errorOnNotFound = true): JWK | null {\n let jwk: JWK | undefined = vm.publicKeyJwk as JWK\n if (!jwk) {\n let publicKeyHex = vm.publicKeyHex ?? toString(extractPublicKeyBytes(vm), 'hex')\n if (publicKeyHex && publicKeyHex.trim() !== '') {\n jwk = toJwk(publicKeyHex, keyTypeFromCryptographicSuite({ crv: vm.type }))\n }\n }\n if (!jwk) {\n if (errorOnNotFound) {\n throw Error(`Could not convert verification method ${vm.id} to jwk`)\n }\n return null\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, false))\n .filter(isDefined),\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 kmsKeyRef,\n }: {\n identifier: IIdentifier\n vmRelationship?: DIDDocumentSection\n didDocument?: DIDDocument\n kmsKeyRef?: string\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 if (kmsKeyRef) {\n let found = keys.filter((key) => key.kid === kmsKeyRef)\n if (found.length > 0) {\n return found\n }\n }\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 let vmKey = verificationMethod.publicKeyHex\n if (vmKey?.startsWith('30')) {\n // DER encoded\n vmKey = toPkcs1FromHex(vmKey)\n }\n\n const localKey = localKeys.find(\n (localKey) =>\n localKey.publicKeyHex === vmKey ||\n (localKey.type === 'RSA' && vmKey?.startsWith('30') && toPkcs1FromHex(localKey.publicKeyHex) === vmKey) ||\n vmKey?.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 Array.from(new Set(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<_ExtendedIKey> {\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 // const keyRefKeys = kmsKeyRef ? identifier.keys.find((key: IKey) => key.kid === kid || key?.meta?.jwkThumbprint === kid) : undefined\n let identifierKey: _ExtendedIKey | undefined = undefined\n\n const keys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship: vmRelationship, kmsKeyRef: kmsKeyRef }, 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) =>\n 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) =>\n 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 type { TKeyType } from '@sphereon/ssi-sdk-ext.key-utils'\nimport type { IAgentContext, IDIDManager, IIdentifier, IKeyManager, IResolver } from '@veramo/core'\nimport type { JWTHeader, JWTPayload, JWTVerifyOptions } from 'did-jwt'\nimport type { 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 DID_WEB = 'web',\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,yBAWO;AACP,IAAAA,sBAA4B;AAC5B,qBAA0F;AAE1F,qBAAyC;AAEzC,mBASO;AACP,qBAAkC;AAGlC,sBAAqB;AAErB,UAAqB;;;AC7Bd,IAAKC,yBAAAA,0BAAAA,yBAAAA;;;;;;;;;SAAAA;;AAWL,IAAKC,sBAAAA,0BAAAA,sBAAAA;;SAAAA;;AA4CL,IAAMC,aAAa;;;ADZ1B,IAAM,EAAEC,YAAYC,SAAQ,IAAKC;AAE1B,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,SACAC,eACAG,eAAc,GAShBF,YAAAA;AAEA,MAAIG,MAAiCC;AACrC,MAAI;AACFD,UACG,MAAME,kCACL;MACEV;MACAO;MACAI,iBAAiB;MACjBR;MACAC;IACF,GACAC,OAAAA,MAEDH,gCAAgCK,mBAAmB,uBAChDE,SACA,MAAMC,kCACJ;MACEV;MACAO,gBAAgB;MAChBI,iBAAiB;MACjBR;MACAC;IACF,GACAC,OAAAA;EAE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AAMwL,eAAe;MACxCC,QAAQ9N,IAAIe;MACZuM;MACAE,MAAM1G;IACR,CAAA;EACF;AACF,GAvC4B;","names":["import_ssi_sdk_ext","SupportedDidMethodEnum","IdentifierAliasEnum","DID_PREFIX","fromString","toString","u8a","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","rsaJwkToRawHexKey","extractPublicKeyHex","isEvenHexString","lastChar","keyBytes","extractPublicKeyBytes","convertPublicKeyToX25519","bytesToHex","input","replace","base58ToBytes","publicKeyMultibase","multibaseKeyToBytes","base64ToBytes","hexToBytes","Uint8Array","verificationMethodToJwk","trim","toJwk","keyTypeFromCryptographicSuite","id","didDocumentSectionToJwks","didDocumentSection","searchForVerificationMethods","verificationMethods","jwks","Set","vmOrId","from","didDocumentToJwks","publicKey","assertionMethod","authentication","keyAgreement","capabilityInvocation","capabilityDelegation","didDoc","getAgentResolver","resolve","then","mapIdentifierKeysToDoc","documentKeys","found","localKeys","convertIdentifierEncryptionKeys","compressIdentifierSecp256k1Keys","extendedKeys","vmKey","startsWith","toPkcs1FromHex","localKey","compareBlockchainAccountId","localProps","concat","vmEthAddr","getEthereumAddress","computedAddr","getAgentDIDMethods","didManagerGetProviders","getDID","idOpts","toDID","toDIDs","getKey","reject","kmsKeyRefParts","split","identifierKey","legacyGetIdentifier","didManagerGet","determineKid","mappedKeys","extendedKey","getSupportedDIDMethods","didOpts","supportedDIDMethods","AgentDIDResolver","resolverResolution","uniresolverResolution","localResolution","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":["../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 rsaJwkToRawHexKey,\n sanitizedJwk,\n signatureAlgorithmFromKey,\n type TKeyType,\n toJwk,\n toPkcs1FromHex,\n} from '@sphereon/ssi-sdk-ext.key-utils'\nimport { base64ToHex } from '@sphereon/ssi-sdk-ext.x509-utils'\nimport { base58ToBytes, base64ToBytes, bytesToHex, hexToBytes, multibaseKeyToBytes } from '@sphereon/ssi-sdk.core'\nimport type { JWK } from '@sphereon/ssi-types'\nimport { convertPublicKeyToX25519 } from '@stablelib/ed25519'\nimport type { DIDDocument, DIDDocumentSection, DIDResolutionResult, IAgentContext, IDIDManager, IIdentifier, IKey, IResolver } from '@veramo/core'\nimport {\n type _ExtendedIKey,\n type _ExtendedVerificationMethod,\n type _NormalizedVerificationMethod,\n compressIdentifierSecp256k1Keys,\n convertIdentifierEncryptionKeys,\n getEthereumAddress,\n isDefined,\n mapIdentifierKeysToDoc,\n} from '@veramo/utils'\nimport { createJWT, Signer } from 'did-jwt'\nimport type { DIDResolutionOptions, JsonWebKey, Resolvable, VerificationMethod } from 'did-resolver'\n// @ts-ignore\nimport elliptic from 'elliptic'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nimport {\n type CreateIdentifierOpts,\n type CreateOrGetIdentifierOpts,\n DID_PREFIX,\n type GetOrCreateResult,\n type GetSignerArgs,\n IdentifierAliasEnum,\n type IdentifierProviderOpts,\n type IDIDOptions,\n type SignJwtArgs,\n SupportedDidMethodEnum,\n} from './types'\n\nconst { fromString, toString } = u8a\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 if (!identifiers || identifiers.length === 0) {\n return undefined\n }\n\n if (opts?.did) {\n const didMatch = identifiers.find((identifier: IIdentifier) => identifier.did === opts.did)\n if (didMatch) {\n return didMatch\n }\n }\n\n if (opts?.alias) {\n const aliasMatch = identifiers.find((identifier: IIdentifier) => identifier.alias === opts.alias)\n if (aliasMatch) {\n return aliasMatch\n }\n }\n\n return identifiers[0]\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 controllerKeyMatch = identifier.controllerKeyId\n ? matchedKeys.find((key) => key.kid === identifier.controllerKeyId && (keyType === undefined || key.type === keyType))\n : undefined\n\n const result = controllerKeyMatch ?? matchedKeys.find((key) => keyType === undefined || key.type === keyType)\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 rsaJwkToRawHexKey(jwk)\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, errorOnNotFound = true): JWK | null {\n let jwk: JWK | undefined = vm.publicKeyJwk as JWK\n if (!jwk) {\n let publicKeyHex = vm.publicKeyHex ?? toString(extractPublicKeyBytes(vm), 'hex')\n if (publicKeyHex && publicKeyHex.trim() !== '') {\n jwk = toJwk(publicKeyHex, keyTypeFromCryptographicSuite({ crv: vm.type }))\n }\n }\n if (!jwk) {\n if (errorOnNotFound) {\n throw Error(`Could not convert verification method ${vm.id} to jwk`)\n }\n return null\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, false))\n .filter(isDefined),\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 kmsKeyRef,\n }: {\n identifier: IIdentifier\n vmRelationship?: DIDDocumentSection\n didDocument?: DIDDocument\n kmsKeyRef?: string\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 if (kmsKeyRef) {\n let found = keys.filter((key) => key.kid === kmsKeyRef)\n if (found.length > 0) {\n return found\n }\n }\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 let vmKey = verificationMethod.publicKeyHex\n if (vmKey?.startsWith('30')) {\n // DER encoded - but only attempt PKCS#1 conversion for RSA/EC keys, not Ed25519/X25519\n const vmType = verificationMethod.type\n const isEdKey =\n ['Ed25519', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'X25519', 'X25519KeyAgreementKey2019', 'X25519KeyAgreementKey2020'].includes(\n vmType,\n ) ||\n (vmType === 'JsonWebKey2020' && ['Ed25519', 'X25519'].includes(verificationMethod.publicKeyJwk?.crv as string))\n if (!isEdKey) {\n vmKey = toPkcs1FromHex(vmKey)\n }\n }\n\n const localKey = localKeys.find(\n (localKey) =>\n localKey.publicKeyHex === vmKey ||\n (localKey.type === 'RSA' && vmKey?.startsWith('30') && toPkcs1FromHex(localKey.publicKeyHex) === vmKey) ||\n vmKey?.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 const allKeys = Array.from(new Set(keys.concat(extendedKeys)))\n\n // Filter based on key metadata purposes, except when requesting all verificationMethods\n if (vmRelationship === 'verificationMethod') {\n return allKeys\n }\n\n return allKeys.filter((key) => {\n const purposes = key.meta?.purposes\n if (!purposes || purposes.length === 0) {\n return true\n }\n return purposes.includes(vmRelationship)\n })\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<_ExtendedIKey> {\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 // const keyRefKeys = kmsKeyRef ? identifier.keys.find((key: IKey) => key.kid === kid || key?.meta?.jwkThumbprint === kid) : undefined\n let identifierKey: _ExtendedIKey | undefined = undefined\n\n const keys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship: vmRelationship, kmsKeyRef: kmsKeyRef }, 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\nconst hasPurpose = (key: IKey, purpose: string) =>\n (key?.meta?.purpose === undefined && key?.meta?.purposes === undefined) || key?.meta?.purpose === purpose || key?.meta?.purposes?.includes(purpose)\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 // Use existing JWK from meta if available, otherwise convert from publicKeyHex\n const publicKeyJwk = key.meta?.jwk\n ? sanitizedJwk(key.meta.jwk as JWK)\n : toJwk(key.publicKeyHex, key.type, {\n use: ENC_KEY_ALGS.includes(key.type) ? JwkKeyUse.Encryption : JwkKeyUse.Signature,\n key,\n })\n\n const vm: VerificationMethod = {\n controller: did,\n id: key.kid.startsWith(did) && key.kid.includes('#') ? key.kid : `${did}#${key.kid}`,\n publicKeyJwk: publicKeyJwk 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((key) => hasPurpose(key, 'assertionMethod'))\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((key) => hasPurpose(key, 'authentication'))\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' || hasPurpose(key, '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((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityInvocation'))\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((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityDelegation'))\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 type { TKeyType } from '@sphereon/ssi-sdk-ext.key-utils'\nimport type { IAgentContext, IDIDManager, IIdentifier, IKeyManager, IResolver } from '@veramo/core'\nimport type { JWTHeader, JWTPayload, JWTVerifyOptions } from 'did-jwt'\nimport type { 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 DID_WEB = 'web',\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 did?: string\n alias?: string\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,yBAWO;AACP,IAAAA,sBAA4B;AAC5B,qBAA0F;AAE1F,qBAAyC;AAEzC,mBASO;AACP,qBAAkC;AAGlC,sBAAqB;AAErB,UAAqB;;;AC7Bd,IAAKC,yBAAAA,0BAAAA,yBAAAA;;;;;;;;;SAAAA;;AAWL,IAAKC,sBAAAA,0BAAAA,sBAAAA;;SAAAA;;AA8CL,IAAMC,aAAa;;;ADd1B,IAAM,EAAEC,YAAYC,SAAQ,IAAKC;AAE1B,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,SACAC,eACAG,eAAc,GAShBF,YAAAA;AAEA,MAAIG,MAAiCC;AACrC,MAAI;AACFD,UACG,MAAME,kCACL;MACEV;MACAO;MACAI,iBAAiB;MACjBR;MACAC;IACF,GACAC,OAAAA,MAEDH,gCAAgCK,mBAAmB,uBAChDE,SACA,MAAMC,kCACJ;MACEV;MACAO,gBAAgB;MAChBI,iBAAiB;MACjBR;MACAC;IACF,GACAC,OAAAA;EAEV,SAASO,G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AACA,MAAIgB,IAAIoI,WAAW,UAAA,GAAa;AAC9B,WAAOpI;EACT;AACA,SAAO,WAAWA,IAAI6F,QAAQ,2BAA2B,IAAA,EAAMrD,YAAW,CAAA;AAC5E;AATsBqJ;AAcf,IAAME,aAAa,8BAAOC,SAAAA;AAC/B,QAAM,EAAE7C,QAAQ8C,QAAQC,SAAS1N,SAAS8B,QAAO,IAAK0L;AACtD,QAAMG,aAAa;IACjB,GAAG7L;IACH8L,QAAQ,MAAMC,aAAa;MAAElD;MAAQ3K;IAAQ,CAAA;EAC/C;AAEA,aAAO8N,0BAAUJ,SAASC,YAAYF,MAAAA;AACxC,GAR0B;AAanB,IAAMI,eAAe,8BAC1BL,SAAAA;AAiBA,QAAM,EAAE7C,QAAQ3K,QAAO,IAAKwN;AAE5B,QAAM7N,aAAa,MAAMwL,oBAAoBR,QAAQ3K,OAAAA;AACrD,QAAMG,MAAM,MAAM2K,OAChB;IACEnL;IACAO,gBAAgByK,OAAOoD;IACvBzJ,WAAWqG,OAAOrG;EACpB,GACAtE,OAAAA;AAEF,QAAMgO,YAAY,UAAMC,8CAA0B;IAAE9N;EAAI,CAAA;AAExD,SAAO,OAAO+N,SAAAA;AACZ,UAAM9G,QAAQ8G,gBAAgBC,OAAOC,eAAezG,UAAAA,IAAc,IAAI0G,YAAAA,EAAcC,OAAOJ,IAAAA,IAAuBA;AAClH,WAAO,MAAMlO,QAAQwC,MAAM+L,eAAe;MACxCC,QAAQrO,IAAIe;MACZ8M;MACAE,MAAM9G;IACR,CAAA;EACF;AACF,GAvC4B;","names":["import_ssi_sdk_ext","SupportedDidMethodEnum","IdentifierAliasEnum","DID_PREFIX","fromString","toString","u8a","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","didMatch","alias","aliasMatch","didManagerCreate","kms","getKms","IdentifierAliasEnum","PRIMARY","Date","getTime","matchedKeys","mapIdentifierKeysToDocWithJwkSupport","Array","isArray","controllerKeyMatch","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","rsaJwkToRawHexKey","extractPublicKeyHex","isEvenHexString","lastChar","keyBytes","extractPublicKeyBytes","convertPublicKeyToX25519","bytesToHex","input","replace","base58ToBytes","publicKeyMultibase","multibaseKeyToBytes","base64ToBytes","hexToBytes","Uint8Array","verificationMethodToJwk","trim","toJwk","keyTypeFromCryptographicSuite","id","didDocumentSectionToJwks","didDocumentSection","searchForVerificationMethods","verificationMethods","jwks","Set","vmOrId","from","didDocumentToJwks","publicKey","assertionMethod","authentication","keyAgreement","capabilityInvocation","capabilityDelegation","didDoc","getAgentResolver","resolve","then","mapIdentifierKeysToDoc","documentKeys","found","localKeys","convertIdentifierEncryptionKeys","compressIdentifierSecp256k1Keys","extendedKeys","vmKey","startsWith","vmType","isEdKey","toPkcs1FromHex","localKey","compareBlockchainAccountId","localProps","allKeys","concat","vmEthAddr","getEthereumAddress","computedAddr","getAgentDIDMethods","didManagerGetProviders","getDID","idOpts","toDID","toDIDs","getKey","reject","kmsKeyRefParts","split","identifierKey","legacyGetIdentifier","didManagerGet","determineKid","mappedKeys","extendedKey","getSupportedDIDMethods","didOpts","supportedDIDMethods","AgentDIDResolver","resolverResolution","uniresolverResolution","localResolution","resolutionResult","origResolutionResult","err","resolveDid","log","iIdentifier","toDidResolutionResult","UniResolver","hasPurpose","purpose","use","ENC_KEY_ALGS","JwkKeyUse","Encryption","Signature","controller","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"]}
package/dist/index.d.cts CHANGED
@@ -37,6 +37,8 @@ type IdentifierProviderOpts = {
37
37
  type?: TKeyType;
38
38
  use?: string;
39
39
  method?: SupportedDidMethodEnum;
40
+ did?: string;
41
+ alias?: string;
40
42
  [x: string]: any;
41
43
  };
42
44
  type CreateIdentifierOpts = {
package/dist/index.d.ts CHANGED
@@ -37,6 +37,8 @@ type IdentifierProviderOpts = {
37
37
  type?: TKeyType;
38
38
  use?: string;
39
39
  method?: SupportedDidMethodEnum;
40
+ did?: string;
41
+ alias?: string;
40
42
  [x: string]: any;
41
43
  };
42
44
  type CreateIdentifierOpts = {
package/dist/index.js CHANGED
@@ -126,7 +126,22 @@ var getPrimaryIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
126
126
  const identifiers = (await context.agent.didManagerFind(opts?.method ? {
127
127
  provider: `${DID_PREFIX}${opts?.method}`
128
128
  } : {})).filter((identifier) => opts?.type === void 0 || identifier.keys.some((key) => key.type === opts?.type));
129
- return identifiers && identifiers.length > 0 ? identifiers[0] : void 0;
129
+ if (!identifiers || identifiers.length === 0) {
130
+ return void 0;
131
+ }
132
+ if (opts?.did) {
133
+ const didMatch = identifiers.find((identifier) => identifier.did === opts.did);
134
+ if (didMatch) {
135
+ return didMatch;
136
+ }
137
+ }
138
+ if (opts?.alias) {
139
+ const aliasMatch = identifiers.find((identifier) => identifier.alias === opts.alias);
140
+ if (aliasMatch) {
141
+ return aliasMatch;
142
+ }
143
+ }
144
+ return identifiers[0];
130
145
  }, "getPrimaryIdentifier");
131
146
  var createIdentifier = /* @__PURE__ */ __name(async (context, opts) => {
132
147
  return await context.agent.didManagerCreate({
@@ -145,7 +160,8 @@ var getFirstKeyWithRelationFromDIDDoc = /* @__PURE__ */ __name(async ({ identifi
145
160
  didDocument
146
161
  }, context);
147
162
  if (Array.isArray(matchedKeys) && matchedKeys.length > 0) {
148
- const result = matchedKeys.find((key) => keyType === void 0 || key.type === keyType || controllerKey && key.kid === identifier.controllerKeyId);
163
+ const controllerKeyMatch = identifier.controllerKeyId ? matchedKeys.find((key) => key.kid === identifier.controllerKeyId && (keyType === void 0 || key.type === keyType)) : void 0;
164
+ const result = controllerKeyMatch ?? matchedKeys.find((key) => keyType === void 0 || key.type === keyType);
149
165
  if (result) {
150
166
  return result;
151
167
  }
@@ -355,7 +371,21 @@ async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship
355
371
  const extendedKeys = documentKeys.map((verificationMethod) => {
356
372
  let vmKey = verificationMethod.publicKeyHex;
357
373
  if (vmKey?.startsWith("30")) {
358
- vmKey = toPkcs1FromHex(vmKey);
374
+ const vmType = verificationMethod.type;
375
+ const isEdKey = [
376
+ "Ed25519",
377
+ "Ed25519VerificationKey2018",
378
+ "Ed25519VerificationKey2020",
379
+ "X25519",
380
+ "X25519KeyAgreementKey2019",
381
+ "X25519KeyAgreementKey2020"
382
+ ].includes(vmType) || vmType === "JsonWebKey2020" && [
383
+ "Ed25519",
384
+ "X25519"
385
+ ].includes(verificationMethod.publicKeyJwk?.crv);
386
+ if (!isEdKey) {
387
+ vmKey = toPkcs1FromHex(vmKey);
388
+ }
359
389
  }
360
390
  const localKey = localKeys.find((localKey2) => localKey2.publicKeyHex === vmKey || localKey2.type === "RSA" && vmKey?.startsWith("30") && toPkcs1FromHex(localKey2.publicKeyHex) === vmKey || vmKey?.startsWith(localKey2.publicKeyHex) || compareBlockchainAccountId(localKey2, verificationMethod));
361
391
  if (localKey) {
@@ -371,7 +401,17 @@ async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship
371
401
  return null;
372
402
  }
373
403
  }).filter(isDefined);
374
- return Array.from(new Set(keys.concat(extendedKeys)));
404
+ const allKeys = Array.from(new Set(keys.concat(extendedKeys)));
405
+ if (vmRelationship === "verificationMethod") {
406
+ return allKeys;
407
+ }
408
+ return allKeys.filter((key) => {
409
+ const purposes = key.meta?.purposes;
410
+ if (!purposes || purposes.length === 0) {
411
+ return true;
412
+ }
413
+ return purposes.includes(vmRelationship);
414
+ });
375
415
  }
376
416
  __name(mapIdentifierKeysToDocWithJwkSupport, "mapIdentifierKeysToDocWithJwkSupport");
377
417
  function compareBlockchainAccountId(localKey, verificationMethod) {
@@ -566,6 +606,7 @@ var AgentDIDResolver = class {
566
606
  return resolutionResult ?? origResolutionResult;
567
607
  }
568
608
  };
609
+ var hasPurpose = /* @__PURE__ */ __name((key, purpose) => key?.meta?.purpose === void 0 && key?.meta?.purposes === void 0 || key?.meta?.purpose === purpose || key?.meta?.purposes?.includes(purpose), "hasPurpose");
569
610
  function toDidDocument(identifier, opts) {
570
611
  let didDocument = void 0;
571
612
  if (identifier) {
@@ -574,19 +615,20 @@ function toDidDocument(identifier, opts) {
574
615
  "@context": "https://www.w3.org/ns/did/v1",
575
616
  id: did,
576
617
  verificationMethod: identifier.keys.map((key) => {
618
+ const publicKeyJwk = key.meta?.jwk ? sanitizedJwk(key.meta.jwk) : toJwk(key.publicKeyHex, key.type, {
619
+ use: ENC_KEY_ALGS.includes(key.type) ? JwkKeyUse.Encryption : JwkKeyUse.Signature,
620
+ key
621
+ });
577
622
  const vm = {
578
623
  controller: did,
579
624
  id: key.kid.startsWith(did) && key.kid.includes("#") ? key.kid : `${did}#${key.kid}`,
580
- publicKeyJwk: toJwk(key.publicKeyHex, key.type, {
581
- use: ENC_KEY_ALGS.includes(key.type) ? JwkKeyUse.Encryption : JwkKeyUse.Signature,
582
- key
583
- }),
625
+ publicKeyJwk,
584
626
  type: "JsonWebKey2020"
585
627
  };
586
628
  return vm;
587
629
  }),
588
630
  ...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Signature)) && identifier.keys && {
589
- assertionMethod: identifier.keys.filter((key) => key?.meta?.purpose === void 0 || key?.meta?.purpose === "assertionMethod" || key?.meta?.purposes?.includes("assertionMethod")).map((key) => {
631
+ assertionMethod: identifier.keys.filter((key) => hasPurpose(key, "assertionMethod")).map((key) => {
590
632
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
591
633
  return key.kid;
592
634
  }
@@ -594,7 +636,7 @@ function toDidDocument(identifier, opts) {
594
636
  })
595
637
  },
596
638
  ...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Signature)) && identifier.keys && {
597
- authentication: identifier.keys.filter((key) => key?.meta?.purpose === void 0 || key?.meta?.purpose === "authentication" || key?.meta?.purposes?.includes("authentication")).map((key) => {
639
+ authentication: identifier.keys.filter((key) => hasPurpose(key, "authentication")).map((key) => {
598
640
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
599
641
  return key.kid;
600
642
  }
@@ -602,7 +644,7 @@ function toDidDocument(identifier, opts) {
602
644
  })
603
645
  },
604
646
  ...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
605
- keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "keyAgreement" || key?.meta?.purposes?.includes("keyAgreement")).map((key) => {
647
+ keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "keyAgreement")).map((key) => {
606
648
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
607
649
  return key.kid;
608
650
  }
@@ -610,7 +652,7 @@ function toDidDocument(identifier, opts) {
610
652
  })
611
653
  },
612
654
  ...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
613
- capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "capabilityInvocation" || key?.meta?.purposes?.includes("capabilityInvocation")).map((key) => {
655
+ capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityInvocation")).map((key) => {
614
656
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
615
657
  return key.kid;
616
658
  }
@@ -618,7 +660,7 @@ function toDidDocument(identifier, opts) {
618
660
  })
619
661
  },
620
662
  ...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
621
- capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || key?.meta?.purpose === "capabilityDelegation" || key?.meta?.purposes?.includes("capabilityDelegation")).map((key) => {
663
+ capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityDelegation")).map((key) => {
622
664
  if (key.kid.startsWith(did) && key.kid.includes("#")) {
623
665
  return key.kid;
624
666
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/did-functions.ts","../src/types.ts"],"sourcesContent":["import { computeAddress } from '@ethersproject/transactions'\nimport { UniResolver } from '@sphereon/did-uni-client'\nimport {\n ENC_KEY_ALGS,\n getKms,\n JwkKeyUse,\n keyTypeFromCryptographicSuite,\n rsaJwkToRawHexKey,\n sanitizedJwk,\n signatureAlgorithmFromKey,\n type TKeyType,\n toJwk,\n toPkcs1FromHex,\n} from '@sphereon/ssi-sdk-ext.key-utils'\nimport { base64ToHex } from '@sphereon/ssi-sdk-ext.x509-utils'\nimport { base58ToBytes, base64ToBytes, bytesToHex, hexToBytes, multibaseKeyToBytes } from '@sphereon/ssi-sdk.core'\nimport type { JWK } from '@sphereon/ssi-types'\nimport { convertPublicKeyToX25519 } from '@stablelib/ed25519'\nimport type { DIDDocument, DIDDocumentSection, DIDResolutionResult, IAgentContext, IDIDManager, IIdentifier, IKey, IResolver } from '@veramo/core'\nimport {\n type _ExtendedIKey,\n type _ExtendedVerificationMethod,\n type _NormalizedVerificationMethod,\n compressIdentifierSecp256k1Keys,\n convertIdentifierEncryptionKeys,\n getEthereumAddress,\n isDefined,\n mapIdentifierKeysToDoc,\n} from '@veramo/utils'\nimport { createJWT, Signer } from 'did-jwt'\nimport type { DIDResolutionOptions, JsonWebKey, Resolvable, VerificationMethod } from 'did-resolver'\n// @ts-ignore\nimport elliptic from 'elliptic'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nimport {\n type CreateIdentifierOpts,\n type CreateOrGetIdentifierOpts,\n DID_PREFIX,\n type GetOrCreateResult,\n type GetSignerArgs,\n IdentifierAliasEnum,\n type IdentifierProviderOpts,\n type IDIDOptions,\n type SignJwtArgs,\n SupportedDidMethodEnum,\n} from './types'\n\nconst { fromString, toString } = u8a\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 rsaJwkToRawHexKey(jwk)\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, errorOnNotFound = true): JWK | null {\n let jwk: JWK | undefined = vm.publicKeyJwk as JWK\n if (!jwk) {\n let publicKeyHex = vm.publicKeyHex ?? toString(extractPublicKeyBytes(vm), 'hex')\n if (publicKeyHex && publicKeyHex.trim() !== '') {\n jwk = toJwk(publicKeyHex, keyTypeFromCryptographicSuite({ crv: vm.type }))\n }\n }\n if (!jwk) {\n if (errorOnNotFound) {\n throw Error(`Could not convert verification method ${vm.id} to jwk`)\n }\n return null\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, false))\n .filter(isDefined),\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 kmsKeyRef,\n }: {\n identifier: IIdentifier\n vmRelationship?: DIDDocumentSection\n didDocument?: DIDDocument\n kmsKeyRef?: string\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 if (kmsKeyRef) {\n let found = keys.filter((key) => key.kid === kmsKeyRef)\n if (found.length > 0) {\n return found\n }\n }\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 let vmKey = verificationMethod.publicKeyHex\n if (vmKey?.startsWith('30')) {\n // DER encoded\n vmKey = toPkcs1FromHex(vmKey)\n }\n\n const localKey = localKeys.find(\n (localKey) =>\n localKey.publicKeyHex === vmKey ||\n (localKey.type === 'RSA' && vmKey?.startsWith('30') && toPkcs1FromHex(localKey.publicKeyHex) === vmKey) ||\n vmKey?.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 Array.from(new Set(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<_ExtendedIKey> {\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 // const keyRefKeys = kmsKeyRef ? identifier.keys.find((key: IKey) => key.kid === kid || key?.meta?.jwkThumbprint === kid) : undefined\n let identifierKey: _ExtendedIKey | undefined = undefined\n\n const keys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship: vmRelationship, kmsKeyRef: kmsKeyRef }, 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) =>\n 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) =>\n 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 type { TKeyType } from '@sphereon/ssi-sdk-ext.key-utils'\nimport type { IAgentContext, IDIDManager, IIdentifier, IKeyManager, IResolver } from '@veramo/core'\nimport type { JWTHeader, JWTPayload, JWTVerifyOptions } from 'did-jwt'\nimport type { 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 DID_WEB = 'web',\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,SAASA,sBAAsB;AAC/B,SAASC,mBAAmB;AAC5B,SACEC,cACAC,QACAC,WACAC,+BACAC,mBACAC,cACAC,2BAEAC,OACAC,sBACK;AACP,SAASC,mBAAmB;AAC5B,SAASC,eAAeC,eAAeC,YAAYC,YAAYC,2BAA2B;AAE1F,SAASC,gCAAgC;AAEzC,SAIEC,iCACAC,iCACAC,oBACAC,WACAC,8BACK;AACP,SAASC,iBAAyB;AAGlC,OAAOC,cAAc;AAErB,YAAYC,SAAS;;;AC7Bd,IAAKC,yBAAAA,0BAAAA,yBAAAA;;;;;;;;;SAAAA;;AAWL,IAAKC,sBAAAA,0BAAAA,sBAAAA;;SAAAA;;AA4CL,IAAMC,aAAa;;;ADZ1B,IAAM,EAAEC,YAAYC,SAAQ,IAAKC;AAE1B,IAAMC,uBAAuB,8BAClC,EACEC,YACAC,4BACAC,8BACAC,SACAC,cAAa,GAQfC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AAMtN,aAAa,MAAMkL,oBAAoBR,QAAQrK,OAAAA;AACrD,QAAMG,MAAM,MAAMqK,OAChB;IACE7K;IACAO,gBAAgBmK,OAAOmD;IACvBrJ,WAAWkG,OAAOlG;EACpB,GACAnE,OAAAA;AAEF,QAAMyN,YAAY,MAAMC,0BAA0B;IAAEvN;EAAI,CAAA;AAExD,SAAO,OAAOwN,SAAAA;AACZ,UAAM1G,QAAQ0G,gBAAgBC,OAAOC,eAAerG,UAAAA,IAAc,IAAIsG,YAAAA,EAAcC,OAAOJ,IAAAA,IAAuBA;AAClH,WAAO,MAAM3N,QAAQwC,MAAMwL,eAAe;MACxCC,QAAQ9N,IAAIe;MACZuM;MACAE,MAAM1G;IACR,CAAA;EACF;AACF,GAvC4B;","names":["computeAddress","UniResolver","ENC_KEY_ALGS","getKms","JwkKeyUse","keyTypeFromCryptographicSuite","rsaJwkToRawHexKey","sanitizedJwk","signatureAlgorithmFromKey","toJwk","toPkcs1FromHex","base64ToHex","base58ToBytes","base64ToBytes","bytesToHex","hexToBytes","multibaseKeyToBytes","convertPublicKeyToX25519","compressIdentifierSecp256k1Keys","convertIdentifierEncryptionKeys","getEthereumAddress","isDefined","mapIdentifierKeysToDoc","createJWT","elliptic","u8a","SupportedDidMethodEnum","IdentifierAliasEnum","DID_PREFIX","fromString","toString","u8a","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","rsaJwkToRawHexKey","extractPublicKeyHex","isEvenHexString","lastChar","keyBytes","extractPublicKeyBytes","convertPublicKeyToX25519","bytesToHex","input","replace","base58ToBytes","publicKeyMultibase","multibaseKeyToBytes","base64ToBytes","hexToBytes","Uint8Array","verificationMethodToJwk","trim","toJwk","keyTypeFromCryptographicSuite","id","didDocumentSectionToJwks","didDocumentSection","searchForVerificationMethods","verificationMethods","jwks","Set","vmOrId","from","didDocumentToJwks","publicKey","assertionMethod","authentication","keyAgreement","capabilityInvocation","capabilityDelegation","didDoc","getAgentResolver","resolve","then","mapIdentifierKeysToDoc","documentKeys","found","localKeys","convertIdentifierEncryptionKeys","compressIdentifierSecp256k1Keys","extendedKeys","vmKey","startsWith","toPkcs1FromHex","localKey","compareBlockchainAccountId","localProps","concat","vmEthAddr","getEthereumAddress","computedAddr","getAgentDIDMethods","didManagerGetProviders","getDID","idOpts","toDID","toDIDs","getKey","reject","kmsKeyRefParts","split","identifierKey","legacyGetIdentifier","didManagerGet","determineKid","mappedKeys","extendedKey","getSupportedDIDMethods","didOpts","supportedDIDMethods","AgentDIDResolver","resolverResolution","uniresolverResolution","localResolution","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":["../src/did-functions.ts","../src/types.ts"],"sourcesContent":["import { computeAddress } from '@ethersproject/transactions'\nimport { UniResolver } from '@sphereon/did-uni-client'\nimport {\n ENC_KEY_ALGS,\n getKms,\n JwkKeyUse,\n keyTypeFromCryptographicSuite,\n rsaJwkToRawHexKey,\n sanitizedJwk,\n signatureAlgorithmFromKey,\n type TKeyType,\n toJwk,\n toPkcs1FromHex,\n} from '@sphereon/ssi-sdk-ext.key-utils'\nimport { base64ToHex } from '@sphereon/ssi-sdk-ext.x509-utils'\nimport { base58ToBytes, base64ToBytes, bytesToHex, hexToBytes, multibaseKeyToBytes } from '@sphereon/ssi-sdk.core'\nimport type { JWK } from '@sphereon/ssi-types'\nimport { convertPublicKeyToX25519 } from '@stablelib/ed25519'\nimport type { DIDDocument, DIDDocumentSection, DIDResolutionResult, IAgentContext, IDIDManager, IIdentifier, IKey, IResolver } from '@veramo/core'\nimport {\n type _ExtendedIKey,\n type _ExtendedVerificationMethod,\n type _NormalizedVerificationMethod,\n compressIdentifierSecp256k1Keys,\n convertIdentifierEncryptionKeys,\n getEthereumAddress,\n isDefined,\n mapIdentifierKeysToDoc,\n} from '@veramo/utils'\nimport { createJWT, Signer } from 'did-jwt'\nimport type { DIDResolutionOptions, JsonWebKey, Resolvable, VerificationMethod } from 'did-resolver'\n// @ts-ignore\nimport elliptic from 'elliptic'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nimport {\n type CreateIdentifierOpts,\n type CreateOrGetIdentifierOpts,\n DID_PREFIX,\n type GetOrCreateResult,\n type GetSignerArgs,\n IdentifierAliasEnum,\n type IdentifierProviderOpts,\n type IDIDOptions,\n type SignJwtArgs,\n SupportedDidMethodEnum,\n} from './types'\n\nconst { fromString, toString } = u8a\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 if (!identifiers || identifiers.length === 0) {\n return undefined\n }\n\n if (opts?.did) {\n const didMatch = identifiers.find((identifier: IIdentifier) => identifier.did === opts.did)\n if (didMatch) {\n return didMatch\n }\n }\n\n if (opts?.alias) {\n const aliasMatch = identifiers.find((identifier: IIdentifier) => identifier.alias === opts.alias)\n if (aliasMatch) {\n return aliasMatch\n }\n }\n\n return identifiers[0]\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 controllerKeyMatch = identifier.controllerKeyId\n ? matchedKeys.find((key) => key.kid === identifier.controllerKeyId && (keyType === undefined || key.type === keyType))\n : undefined\n\n const result = controllerKeyMatch ?? matchedKeys.find((key) => keyType === undefined || key.type === keyType)\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 rsaJwkToRawHexKey(jwk)\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, errorOnNotFound = true): JWK | null {\n let jwk: JWK | undefined = vm.publicKeyJwk as JWK\n if (!jwk) {\n let publicKeyHex = vm.publicKeyHex ?? toString(extractPublicKeyBytes(vm), 'hex')\n if (publicKeyHex && publicKeyHex.trim() !== '') {\n jwk = toJwk(publicKeyHex, keyTypeFromCryptographicSuite({ crv: vm.type }))\n }\n }\n if (!jwk) {\n if (errorOnNotFound) {\n throw Error(`Could not convert verification method ${vm.id} to jwk`)\n }\n return null\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, false))\n .filter(isDefined),\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 kmsKeyRef,\n }: {\n identifier: IIdentifier\n vmRelationship?: DIDDocumentSection\n didDocument?: DIDDocument\n kmsKeyRef?: string\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 if (kmsKeyRef) {\n let found = keys.filter((key) => key.kid === kmsKeyRef)\n if (found.length > 0) {\n return found\n }\n }\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 let vmKey = verificationMethod.publicKeyHex\n if (vmKey?.startsWith('30')) {\n // DER encoded - but only attempt PKCS#1 conversion for RSA/EC keys, not Ed25519/X25519\n const vmType = verificationMethod.type\n const isEdKey =\n ['Ed25519', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'X25519', 'X25519KeyAgreementKey2019', 'X25519KeyAgreementKey2020'].includes(\n vmType,\n ) ||\n (vmType === 'JsonWebKey2020' && ['Ed25519', 'X25519'].includes(verificationMethod.publicKeyJwk?.crv as string))\n if (!isEdKey) {\n vmKey = toPkcs1FromHex(vmKey)\n }\n }\n\n const localKey = localKeys.find(\n (localKey) =>\n localKey.publicKeyHex === vmKey ||\n (localKey.type === 'RSA' && vmKey?.startsWith('30') && toPkcs1FromHex(localKey.publicKeyHex) === vmKey) ||\n vmKey?.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 const allKeys = Array.from(new Set(keys.concat(extendedKeys)))\n\n // Filter based on key metadata purposes, except when requesting all verificationMethods\n if (vmRelationship === 'verificationMethod') {\n return allKeys\n }\n\n return allKeys.filter((key) => {\n const purposes = key.meta?.purposes\n if (!purposes || purposes.length === 0) {\n return true\n }\n return purposes.includes(vmRelationship)\n })\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<_ExtendedIKey> {\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 // const keyRefKeys = kmsKeyRef ? identifier.keys.find((key: IKey) => key.kid === kid || key?.meta?.jwkThumbprint === kid) : undefined\n let identifierKey: _ExtendedIKey | undefined = undefined\n\n const keys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship: vmRelationship, kmsKeyRef: kmsKeyRef }, 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\nconst hasPurpose = (key: IKey, purpose: string) =>\n (key?.meta?.purpose === undefined && key?.meta?.purposes === undefined) || key?.meta?.purpose === purpose || key?.meta?.purposes?.includes(purpose)\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 // Use existing JWK from meta if available, otherwise convert from publicKeyHex\n const publicKeyJwk = key.meta?.jwk\n ? sanitizedJwk(key.meta.jwk as JWK)\n : toJwk(key.publicKeyHex, key.type, {\n use: ENC_KEY_ALGS.includes(key.type) ? JwkKeyUse.Encryption : JwkKeyUse.Signature,\n key,\n })\n\n const vm: VerificationMethod = {\n controller: did,\n id: key.kid.startsWith(did) && key.kid.includes('#') ? key.kid : `${did}#${key.kid}`,\n publicKeyJwk: publicKeyJwk 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((key) => hasPurpose(key, 'assertionMethod'))\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((key) => hasPurpose(key, 'authentication'))\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' || hasPurpose(key, '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((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityInvocation'))\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((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityDelegation'))\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 type { TKeyType } from '@sphereon/ssi-sdk-ext.key-utils'\nimport type { IAgentContext, IDIDManager, IIdentifier, IKeyManager, IResolver } from '@veramo/core'\nimport type { JWTHeader, JWTPayload, JWTVerifyOptions } from 'did-jwt'\nimport type { 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 DID_WEB = 'web',\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 did?: string\n alias?: string\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,SAASA,sBAAsB;AAC/B,SAASC,mBAAmB;AAC5B,SACEC,cACAC,QACAC,WACAC,+BACAC,mBACAC,cACAC,2BAEAC,OACAC,sBACK;AACP,SAASC,mBAAmB;AAC5B,SAASC,eAAeC,eAAeC,YAAYC,YAAYC,2BAA2B;AAE1F,SAASC,gCAAgC;AAEzC,SAIEC,iCACAC,iCACAC,oBACAC,WACAC,8BACK;AACP,SAASC,iBAAyB;AAGlC,OAAOC,cAAc;AAErB,YAAYC,SAA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AO,gBAAgByK,OAAOoD;IACvBzJ,WAAWqG,OAAOrG;EACpB,GACAtE,OAAAA;AAEF,QAAMgO,YAAY,MAAMC,0BAA0B;IAAE9N;EAAI,CAAA;AAExD,SAAO,OAAO+N,SAAAA;AACZ,UAAM9G,QAAQ8G,gBAAgBC,OAAOC,eAAezG,UAAAA,IAAc,IAAI0G,YAAAA,EAAcC,OAAOJ,IAAAA,IAAuBA;AAClH,WAAO,MAAMlO,QAAQwC,MAAM+L,eAAe;MACxCC,QAAQrO,IAAIe;MACZ8M;MACAE,MAAM9G;IACR,CAAA;EACF;AACF,GAvC4B;","names":["computeAddress","UniResolver","ENC_KEY_ALGS","getKms","JwkKeyUse","keyTypeFromCryptographicSuite","rsaJwkToRawHexKey","sanitizedJwk","signatureAlgorithmFromKey","toJwk","toPkcs1FromHex","base64ToHex","base58ToBytes","base64ToBytes","bytesToHex","hexToBytes","multibaseKeyToBytes","convertPublicKeyToX25519","compressIdentifierSecp256k1Keys","convertIdentifierEncryptionKeys","getEthereumAddress","isDefined","mapIdentifierKeysToDoc","createJWT","elliptic","u8a","SupportedDidMethodEnum","IdentifierAliasEnum","DID_PREFIX","fromString","toString","u8a","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","didMatch","alias","aliasMatch","didManagerCreate","kms","getKms","IdentifierAliasEnum","PRIMARY","Date","getTime","matchedKeys","mapIdentifierKeysToDocWithJwkSupport","Array","isArray","controllerKeyMatch","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","rsaJwkToRawHexKey","extractPublicKeyHex","isEvenHexString","lastChar","keyBytes","extractPublicKeyBytes","convertPublicKeyToX25519","bytesToHex","input","replace","base58ToBytes","publicKeyMultibase","multibaseKeyToBytes","base64ToBytes","hexToBytes","Uint8Array","verificationMethodToJwk","trim","toJwk","keyTypeFromCryptographicSuite","id","didDocumentSectionToJwks","didDocumentSection","searchForVerificationMethods","verificationMethods","jwks","Set","vmOrId","from","didDocumentToJwks","publicKey","assertionMethod","authentication","keyAgreement","capabilityInvocation","capabilityDelegation","didDoc","getAgentResolver","resolve","then","mapIdentifierKeysToDoc","documentKeys","found","localKeys","convertIdentifierEncryptionKeys","compressIdentifierSecp256k1Keys","extendedKeys","vmKey","startsWith","vmType","isEdKey","toPkcs1FromHex","localKey","compareBlockchainAccountId","localProps","allKeys","concat","vmEthAddr","getEthereumAddress","computedAddr","getAgentDIDMethods","didManagerGetProviders","getDID","idOpts","toDID","toDIDs","getKey","reject","kmsKeyRefParts","split","identifierKey","legacyGetIdentifier","didManagerGet","determineKid","mappedKeys","extendedKey","getSupportedDIDMethods","didOpts","supportedDIDMethods","AgentDIDResolver","resolverResolution","uniresolverResolution","localResolution","resolutionResult","origResolutionResult","err","resolveDid","log","iIdentifier","toDidResolutionResult","UniResolver","hasPurpose","purpose","use","ENC_KEY_ALGS","JwkKeyUse","Encryption","Signature","controller","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"]}
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.36.1-next.50+49074a02",
4
+ "version": "0.37.0",
5
5
  "source": "./src/index.ts",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",
@@ -25,11 +25,11 @@
25
25
  "@ethersproject/networks": "^5.7.1",
26
26
  "@ethersproject/transactions": "^5.7.0",
27
27
  "@sphereon/did-uni-client": "^0.6.3",
28
- "@sphereon/ssi-sdk-ext.key-utils": "0.36.1-next.50+49074a02",
29
- "@sphereon/ssi-sdk-ext.x509-utils": "0.36.1-next.50+49074a02",
30
- "@sphereon/ssi-sdk.agent-config": "0.36.1-next.50+49074a02",
31
- "@sphereon/ssi-sdk.core": "0.36.1-next.50+49074a02",
32
- "@sphereon/ssi-types": "0.36.1-next.50+49074a02",
28
+ "@sphereon/ssi-sdk-ext.key-utils": "0.37.0",
29
+ "@sphereon/ssi-sdk-ext.x509-utils": "0.37.0",
30
+ "@sphereon/ssi-sdk.agent-config": "0.37.0",
31
+ "@sphereon/ssi-sdk.core": "0.37.0",
32
+ "@sphereon/ssi-types": "0.37.0",
33
33
  "@stablelib/ed25519": "^1.0.3",
34
34
  "@veramo/core": "4.2.0",
35
35
  "@veramo/utils": "4.2.0",
@@ -53,5 +53,5 @@
53
53
  "author": "Sphereon <dev@sphereon.com>",
54
54
  "license": "Apache-2.0",
55
55
  "keywords": [],
56
- "gitHead": "49074a0266b42bdd8012e0872d471f655a0b5736"
56
+ "gitHead": "2fc0740c1eca0e790cb06f292339ee729f94fec9"
57
57
  }
@@ -197,7 +197,25 @@ export const getPrimaryIdentifier = async (context: IAgentContext<IDIDManager>,
197
197
  (identifier: IIdentifier) => opts?.type === undefined || identifier.keys.some((key: IKey) => key.type === opts?.type),
198
198
  )
199
199
 
200
- return identifiers && identifiers.length > 0 ? identifiers[0] : undefined
200
+ if (!identifiers || identifiers.length === 0) {
201
+ return undefined
202
+ }
203
+
204
+ if (opts?.did) {
205
+ const didMatch = identifiers.find((identifier: IIdentifier) => identifier.did === opts.did)
206
+ if (didMatch) {
207
+ return didMatch
208
+ }
209
+ }
210
+
211
+ if (opts?.alias) {
212
+ const aliasMatch = identifiers.find((identifier: IIdentifier) => identifier.alias === opts.alias)
213
+ if (aliasMatch) {
214
+ return aliasMatch
215
+ }
216
+ }
217
+
218
+ return identifiers[0]
201
219
  }
202
220
 
203
221
  export const createIdentifier = async (context: IAgentContext<IDIDManager>, opts?: CreateIdentifierOpts): Promise<IIdentifier> => {
@@ -229,9 +247,11 @@ export const getFirstKeyWithRelationFromDIDDoc = async (
229
247
  ): Promise<_ExtendedIKey | undefined> => {
230
248
  const matchedKeys = await mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship, didDocument }, context)
231
249
  if (Array.isArray(matchedKeys) && matchedKeys.length > 0) {
232
- const result = matchedKeys.find(
233
- (key) => keyType === undefined || key.type === keyType || (controllerKey && key.kid === identifier.controllerKeyId),
234
- )
250
+ const controllerKeyMatch = identifier.controllerKeyId
251
+ ? matchedKeys.find((key) => key.kid === identifier.controllerKeyId && (keyType === undefined || key.type === keyType))
252
+ : undefined
253
+
254
+ const result = controllerKeyMatch ?? matchedKeys.find((key) => keyType === undefined || key.type === keyType)
235
255
  if (result) {
236
256
  return result
237
257
  }
@@ -555,8 +575,16 @@ export async function mapIdentifierKeysToDocWithJwkSupport(
555
575
  .map((verificationMethod) => {
556
576
  let vmKey = verificationMethod.publicKeyHex
557
577
  if (vmKey?.startsWith('30')) {
558
- // DER encoded
559
- vmKey = toPkcs1FromHex(vmKey)
578
+ // DER encoded - but only attempt PKCS#1 conversion for RSA/EC keys, not Ed25519/X25519
579
+ const vmType = verificationMethod.type
580
+ const isEdKey =
581
+ ['Ed25519', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'X25519', 'X25519KeyAgreementKey2019', 'X25519KeyAgreementKey2020'].includes(
582
+ vmType,
583
+ ) ||
584
+ (vmType === 'JsonWebKey2020' && ['Ed25519', 'X25519'].includes(verificationMethod.publicKeyJwk?.crv as string))
585
+ if (!isEdKey) {
586
+ vmKey = toPkcs1FromHex(vmKey)
587
+ }
560
588
  }
561
589
 
562
590
  const localKey = localKeys.find(
@@ -575,7 +603,20 @@ export async function mapIdentifierKeysToDocWithJwkSupport(
575
603
  })
576
604
  .filter(isDefined)
577
605
 
578
- return Array.from(new Set(keys.concat(extendedKeys)))
606
+ const allKeys = Array.from(new Set(keys.concat(extendedKeys)))
607
+
608
+ // Filter based on key metadata purposes, except when requesting all verificationMethods
609
+ if (vmRelationship === 'verificationMethod') {
610
+ return allKeys
611
+ }
612
+
613
+ return allKeys.filter((key) => {
614
+ const purposes = key.meta?.purposes
615
+ if (!purposes || purposes.length === 0) {
616
+ return true
617
+ }
618
+ return purposes.includes(vmRelationship)
619
+ })
579
620
  }
580
621
 
581
622
  /**
@@ -840,6 +881,9 @@ export class AgentDIDResolver implements Resolvable {
840
881
  }
841
882
  }
842
883
 
884
+ const hasPurpose = (key: IKey, purpose: string) =>
885
+ (key?.meta?.purpose === undefined && key?.meta?.purposes === undefined) || key?.meta?.purpose === purpose || key?.meta?.purposes?.includes(purpose)
886
+
843
887
  /**
844
888
  * Please note that this is not an exact representation of the actual DID Document.
845
889
  *
@@ -865,13 +909,18 @@ export function toDidDocument(
865
909
  '@context': 'https://www.w3.org/ns/did/v1',
866
910
  id: did,
867
911
  verificationMethod: identifier.keys.map((key) => {
912
+ // Use existing JWK from meta if available, otherwise convert from publicKeyHex
913
+ const publicKeyJwk = key.meta?.jwk
914
+ ? sanitizedJwk(key.meta.jwk as JWK)
915
+ : toJwk(key.publicKeyHex, key.type, {
916
+ use: ENC_KEY_ALGS.includes(key.type) ? JwkKeyUse.Encryption : JwkKeyUse.Signature,
917
+ key,
918
+ })
919
+
868
920
  const vm: VerificationMethod = {
869
921
  controller: did,
870
922
  id: key.kid.startsWith(did) && key.kid.includes('#') ? key.kid : `${did}#${key.kid}`,
871
- publicKeyJwk: toJwk(key.publicKeyHex, key.type, {
872
- use: ENC_KEY_ALGS.includes(key.type) ? JwkKeyUse.Encryption : JwkKeyUse.Signature,
873
- key,
874
- }) as JsonWebKey,
923
+ publicKeyJwk: publicKeyJwk as JsonWebKey,
875
924
  type: 'JsonWebKey2020',
876
925
  }
877
926
  return vm
@@ -879,10 +928,7 @@ export function toDidDocument(
879
928
  ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&
880
929
  identifier.keys && {
881
930
  assertionMethod: identifier.keys
882
- .filter(
883
- (key) =>
884
- key?.meta?.purpose === undefined || key?.meta?.purpose === 'assertionMethod' || key?.meta?.purposes?.includes('assertionMethod'),
885
- )
931
+ .filter((key) => hasPurpose(key, 'assertionMethod'))
886
932
  .map((key) => {
887
933
  if (key.kid.startsWith(did) && key.kid.includes('#')) {
888
934
  return key.kid
@@ -893,9 +939,7 @@ export function toDidDocument(
893
939
  ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&
894
940
  identifier.keys && {
895
941
  authentication: identifier.keys
896
- .filter(
897
- (key) => key?.meta?.purpose === undefined || key?.meta?.purpose === 'authentication' || key?.meta?.purposes?.includes('authentication'),
898
- )
942
+ .filter((key) => hasPurpose(key, 'authentication'))
899
943
  .map((key) => {
900
944
  if (key.kid.startsWith(did) && key.kid.includes('#')) {
901
945
  return key.kid
@@ -906,7 +950,7 @@ export function toDidDocument(
906
950
  ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
907
951
  identifier.keys && {
908
952
  keyAgreement: identifier.keys
909
- .filter((key) => key.type === 'X25519' || key?.meta?.purpose === 'keyAgreement' || key?.meta?.purposes?.includes('keyAgreement'))
953
+ .filter((key) => key.type === 'X25519' || hasPurpose(key, 'keyAgreement'))
910
954
  .map((key) => {
911
955
  if (key.kid.startsWith(did) && key.kid.includes('#')) {
912
956
  return key.kid
@@ -917,10 +961,7 @@ export function toDidDocument(
917
961
  ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
918
962
  identifier.keys && {
919
963
  capabilityInvocation: identifier.keys
920
- .filter(
921
- (key) =>
922
- key.type === 'X25519' || key?.meta?.purpose === 'capabilityInvocation' || key?.meta?.purposes?.includes('capabilityInvocation'),
923
- )
964
+ .filter((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityInvocation'))
924
965
  .map((key) => {
925
966
  if (key.kid.startsWith(did) && key.kid.includes('#')) {
926
967
  return key.kid
@@ -931,10 +972,7 @@ export function toDidDocument(
931
972
  ...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
932
973
  identifier.keys && {
933
974
  capabilityDelegation: identifier.keys
934
- .filter(
935
- (key) =>
936
- key.type === 'X25519' || key?.meta?.purpose === 'capabilityDelegation' || key?.meta?.purposes?.includes('capabilityDelegation'),
937
- )
975
+ .filter((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityDelegation'))
938
976
  .map((key) => {
939
977
  if (key.kid.startsWith(did) && key.kid.includes('#')) {
940
978
  return key.kid
package/src/types.ts CHANGED
@@ -39,6 +39,8 @@ export type IdentifierProviderOpts = {
39
39
  type?: TKeyType
40
40
  use?: string
41
41
  method?: SupportedDidMethodEnum
42
+ did?: string
43
+ alias?: string
42
44
  [x: string]: any
43
45
  }
44
46