@sphereon/ssi-sdk-ext.did-utils 0.36.1-feature.SSISDK.82.and.SSISDK.70.37 → 0.36.1-feature.SSISDK.97.branding.incremental.sync.128
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 +35 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +35 -8
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
- package/src/did-functions.ts +46 -21
- package/src/types.ts +2 -0
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
|
-
|
|
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
|
|
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
|
}
|
|
@@ -438,7 +454,17 @@ async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship
|
|
|
438
454
|
return null;
|
|
439
455
|
}
|
|
440
456
|
}).filter(import_utils.isDefined);
|
|
441
|
-
|
|
457
|
+
const allKeys = Array.from(new Set(keys.concat(extendedKeys)));
|
|
458
|
+
if (vmRelationship === "verificationMethod") {
|
|
459
|
+
return allKeys;
|
|
460
|
+
}
|
|
461
|
+
return allKeys.filter((key) => {
|
|
462
|
+
const purposes = key.meta?.purposes;
|
|
463
|
+
if (!purposes || purposes.length === 0) {
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
return purposes.includes(vmRelationship);
|
|
467
|
+
});
|
|
442
468
|
}
|
|
443
469
|
__name(mapIdentifierKeysToDocWithJwkSupport, "mapIdentifierKeysToDocWithJwkSupport");
|
|
444
470
|
function compareBlockchainAccountId(localKey, verificationMethod) {
|
|
@@ -633,6 +659,7 @@ var AgentDIDResolver = class {
|
|
|
633
659
|
return resolutionResult ?? origResolutionResult;
|
|
634
660
|
}
|
|
635
661
|
};
|
|
662
|
+
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
663
|
function toDidDocument(identifier, opts) {
|
|
637
664
|
let didDocument = void 0;
|
|
638
665
|
if (identifier) {
|
|
@@ -654,7 +681,7 @@ function toDidDocument(identifier, opts) {
|
|
|
654
681
|
return vm;
|
|
655
682
|
}),
|
|
656
683
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
|
|
657
|
-
assertionMethod: identifier.keys.filter((key) => key
|
|
684
|
+
assertionMethod: identifier.keys.filter((key) => hasPurpose(key, "assertionMethod")).map((key) => {
|
|
658
685
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
659
686
|
return key.kid;
|
|
660
687
|
}
|
|
@@ -662,7 +689,7 @@ function toDidDocument(identifier, opts) {
|
|
|
662
689
|
})
|
|
663
690
|
},
|
|
664
691
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
|
|
665
|
-
authentication: identifier.keys.filter((key) => key
|
|
692
|
+
authentication: identifier.keys.filter((key) => hasPurpose(key, "authentication")).map((key) => {
|
|
666
693
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
667
694
|
return key.kid;
|
|
668
695
|
}
|
|
@@ -670,7 +697,7 @@ function toDidDocument(identifier, opts) {
|
|
|
670
697
|
})
|
|
671
698
|
},
|
|
672
699
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
|
|
673
|
-
keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
700
|
+
keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "keyAgreement")).map((key) => {
|
|
674
701
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
675
702
|
return key.kid;
|
|
676
703
|
}
|
|
@@ -678,7 +705,7 @@ function toDidDocument(identifier, opts) {
|
|
|
678
705
|
})
|
|
679
706
|
},
|
|
680
707
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
|
|
681
|
-
capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
708
|
+
capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityInvocation")).map((key) => {
|
|
682
709
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
683
710
|
return key.kid;
|
|
684
711
|
}
|
|
@@ -686,7 +713,7 @@ function toDidDocument(identifier, opts) {
|
|
|
686
713
|
})
|
|
687
714
|
},
|
|
688
715
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
|
|
689
|
-
capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
716
|
+
capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityDelegation")).map((key) => {
|
|
690
717
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
691
718
|
return key.kid;
|
|
692
719
|
}
|
package/dist/index.cjs.map
CHANGED
|
@@ -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 // 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(\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,S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,YAAYF,MAAAA;AACxC,GAR0B;AAanB,IAAMI,eAAe,8BAC1BL,SAAAA;AAiBA,QAAM,EAAE5C,QAAQrK,QAAO,IAAKiN;AAE5B,QAAMtN,aAAa,MAAMkL,oBAAoBR,QAAQrK,OAAAA;AACrD,QAAMG,MAAM,MAAMqK,OAChB;IACE7K;IACAO,gBAAgBmK,OAAOmD;IACvBrJ,WAAWkG,OAAOlG;EACpB,GACAnE,OAAAA;AAEF,QAAMyN,YAAY,UAAMC,8CAA0B;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":["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","use","ENC_KEY_ALGS","JwkKeyUse","Encryption","Signature","controller","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\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 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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CAAA;EACd;AACA,MAAIgB,IAAIoI,WAAW,UAAA,GAAa;AAC9B,WAAOpI;EACT;AACA,SAAO,WAAWA,IAAI6F,QAAQ,2BAA2B,IAAA,EAAMrD,YAAW,CAAA;AAC5E;AATsBmJ;AAcf,IAAME,aAAa,8BAAOC,SAAAA;AAC/B,QAAM,EAAE7C,QAAQ8C,QAAQC,SAASxN,SAAS8B,QAAO,IAAKwL;AACtD,QAAMG,aAAa;IACjB,GAAG3L;IACH4L,QAAQ,MAAMC,aAAa;MAAElD;MAAQzK;IAAQ,CAAA;EAC/C;AAEA,aAAO4N,0BAAUJ,SAASC,YAAYF,MAAAA;AACxC,GAR0B;AAanB,IAAMI,eAAe,8BAC1BL,SAAAA;AAiBA,QAAM,EAAE7C,QAAQzK,QAAO,IAAKsN;AAE5B,QAAM3N,aAAa,MAAMsL,oBAAoBR,QAAQzK,OAAAA;AACrD,QAAMG,MAAM,MAAMyK,OAChB;IACEjL;IACAO,gBAAgBuK,OAAOoD;IACvBvJ,WAAWmG,OAAOnG;EACpB,GACAtE,OAAAA;AAEF,QAAM8N,YAAY,UAAMC,8CAA0B;IAAE5N;EAAI,CAAA;AAExD,SAAO,OAAO6N,SAAAA;AACZ,UAAM5G,QAAQ4G,gBAAgBC,OAAOC,eAAevG,UAAAA,IAAc,IAAIwG,YAAAA,EAAcC,OAAOJ,IAAAA,IAAuBA;AAClH,WAAO,MAAMhO,QAAQwC,MAAM6L,eAAe;MACxCC,QAAQnO,IAAIe;MACZ4M;MACAE,MAAM5G;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","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
package/dist/index.d.ts
CHANGED
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
|
-
|
|
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
|
|
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
|
}
|
|
@@ -371,7 +387,17 @@ async function mapIdentifierKeysToDocWithJwkSupport({ identifier, vmRelationship
|
|
|
371
387
|
return null;
|
|
372
388
|
}
|
|
373
389
|
}).filter(isDefined);
|
|
374
|
-
|
|
390
|
+
const allKeys = Array.from(new Set(keys.concat(extendedKeys)));
|
|
391
|
+
if (vmRelationship === "verificationMethod") {
|
|
392
|
+
return allKeys;
|
|
393
|
+
}
|
|
394
|
+
return allKeys.filter((key) => {
|
|
395
|
+
const purposes = key.meta?.purposes;
|
|
396
|
+
if (!purposes || purposes.length === 0) {
|
|
397
|
+
return true;
|
|
398
|
+
}
|
|
399
|
+
return purposes.includes(vmRelationship);
|
|
400
|
+
});
|
|
375
401
|
}
|
|
376
402
|
__name(mapIdentifierKeysToDocWithJwkSupport, "mapIdentifierKeysToDocWithJwkSupport");
|
|
377
403
|
function compareBlockchainAccountId(localKey, verificationMethod) {
|
|
@@ -566,6 +592,7 @@ var AgentDIDResolver = class {
|
|
|
566
592
|
return resolutionResult ?? origResolutionResult;
|
|
567
593
|
}
|
|
568
594
|
};
|
|
595
|
+
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
596
|
function toDidDocument(identifier, opts) {
|
|
570
597
|
let didDocument = void 0;
|
|
571
598
|
if (identifier) {
|
|
@@ -587,7 +614,7 @@ function toDidDocument(identifier, opts) {
|
|
|
587
614
|
return vm;
|
|
588
615
|
}),
|
|
589
616
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Signature)) && identifier.keys && {
|
|
590
|
-
assertionMethod: identifier.keys.filter((key) => key
|
|
617
|
+
assertionMethod: identifier.keys.filter((key) => hasPurpose(key, "assertionMethod")).map((key) => {
|
|
591
618
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
592
619
|
return key.kid;
|
|
593
620
|
}
|
|
@@ -595,7 +622,7 @@ function toDidDocument(identifier, opts) {
|
|
|
595
622
|
})
|
|
596
623
|
},
|
|
597
624
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Signature)) && identifier.keys && {
|
|
598
|
-
authentication: identifier.keys.filter((key) => key
|
|
625
|
+
authentication: identifier.keys.filter((key) => hasPurpose(key, "authentication")).map((key) => {
|
|
599
626
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
600
627
|
return key.kid;
|
|
601
628
|
}
|
|
@@ -603,7 +630,7 @@ function toDidDocument(identifier, opts) {
|
|
|
603
630
|
})
|
|
604
631
|
},
|
|
605
632
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
|
|
606
|
-
keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
633
|
+
keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "keyAgreement")).map((key) => {
|
|
607
634
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
608
635
|
return key.kid;
|
|
609
636
|
}
|
|
@@ -611,7 +638,7 @@ function toDidDocument(identifier, opts) {
|
|
|
611
638
|
})
|
|
612
639
|
},
|
|
613
640
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
|
|
614
|
-
capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
641
|
+
capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityInvocation")).map((key) => {
|
|
615
642
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
616
643
|
return key.kid;
|
|
617
644
|
}
|
|
@@ -619,7 +646,7 @@ function toDidDocument(identifier, opts) {
|
|
|
619
646
|
})
|
|
620
647
|
},
|
|
621
648
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
|
|
622
|
-
capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
649
|
+
capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityDelegation")).map((key) => {
|
|
623
650
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
624
651
|
return key.kid;
|
|
625
652
|
}
|
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 // 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(\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,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J,SAASC,YAAYF,MAAAA;AACxC,GAR0B;AAanB,IAAMI,eAAe,8BAC1BL,SAAAA;AAiBA,QAAM,EAAE5C,QAAQrK,QAAO,IAAKiN;AAE5B,QAAMtN,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","use","ENC_KEY_ALGS","JwkKeyUse","Encryption","Signature","controller","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\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 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,SAAS;;;AC7Bd,IAAKC,yBAAAA,0BAAAA,yBAAAA;;;;;;;;;SAAAA;;AAWL,IAAKC,sBAAAA,0BAAAA,sBAAAA;;SAAAA;;AA8CL,IAAMC,aAAa;;;ADd1B,IAAM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F,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","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-feature.SSISDK.
|
|
4
|
+
"version": "0.36.1-feature.SSISDK.97.branding.incremental.sync.128+33ba68a0",
|
|
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-feature.SSISDK.
|
|
29
|
-
"@sphereon/ssi-sdk-ext.x509-utils": "0.36.1-feature.SSISDK.
|
|
30
|
-
"@sphereon/ssi-sdk.agent-config": "0.36.1-feature.SSISDK.
|
|
31
|
-
"@sphereon/ssi-sdk.core": "0.36.1-feature.SSISDK.
|
|
32
|
-
"@sphereon/ssi-types": "0.36.1-feature.SSISDK.
|
|
28
|
+
"@sphereon/ssi-sdk-ext.key-utils": "0.36.1-feature.SSISDK.97.branding.incremental.sync.128+33ba68a0",
|
|
29
|
+
"@sphereon/ssi-sdk-ext.x509-utils": "0.36.1-feature.SSISDK.97.branding.incremental.sync.128+33ba68a0",
|
|
30
|
+
"@sphereon/ssi-sdk.agent-config": "0.36.1-feature.SSISDK.97.branding.incremental.sync.128+33ba68a0",
|
|
31
|
+
"@sphereon/ssi-sdk.core": "0.36.1-feature.SSISDK.97.branding.incremental.sync.128+33ba68a0",
|
|
32
|
+
"@sphereon/ssi-types": "0.36.1-feature.SSISDK.97.branding.incremental.sync.128+33ba68a0",
|
|
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": "
|
|
56
|
+
"gitHead": "33ba68a0b288b6d50d847b9aaaea0553915efe98"
|
|
57
57
|
}
|
package/src/did-functions.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
233
|
-
(key) =>
|
|
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
|
}
|
|
@@ -575,7 +595,20 @@ export async function mapIdentifierKeysToDocWithJwkSupport(
|
|
|
575
595
|
})
|
|
576
596
|
.filter(isDefined)
|
|
577
597
|
|
|
578
|
-
|
|
598
|
+
const allKeys = Array.from(new Set(keys.concat(extendedKeys)))
|
|
599
|
+
|
|
600
|
+
// Filter based on key metadata purposes, except when requesting all verificationMethods
|
|
601
|
+
if (vmRelationship === 'verificationMethod') {
|
|
602
|
+
return allKeys
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
return allKeys.filter((key) => {
|
|
606
|
+
const purposes = key.meta?.purposes
|
|
607
|
+
if (!purposes || purposes.length === 0) {
|
|
608
|
+
return true
|
|
609
|
+
}
|
|
610
|
+
return purposes.includes(vmRelationship)
|
|
611
|
+
})
|
|
579
612
|
}
|
|
580
613
|
|
|
581
614
|
/**
|
|
@@ -840,6 +873,9 @@ export class AgentDIDResolver implements Resolvable {
|
|
|
840
873
|
}
|
|
841
874
|
}
|
|
842
875
|
|
|
876
|
+
const hasPurpose = (key: IKey, purpose: string) =>
|
|
877
|
+
(key?.meta?.purpose === undefined && key?.meta?.purposes === undefined) || key?.meta?.purpose === purpose || key?.meta?.purposes?.includes(purpose)
|
|
878
|
+
|
|
843
879
|
/**
|
|
844
880
|
* Please note that this is not an exact representation of the actual DID Document.
|
|
845
881
|
*
|
|
@@ -884,10 +920,7 @@ export function toDidDocument(
|
|
|
884
920
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&
|
|
885
921
|
identifier.keys && {
|
|
886
922
|
assertionMethod: identifier.keys
|
|
887
|
-
.filter(
|
|
888
|
-
(key) =>
|
|
889
|
-
key?.meta?.purpose === undefined || key?.meta?.purpose === 'assertionMethod' || key?.meta?.purposes?.includes('assertionMethod'),
|
|
890
|
-
)
|
|
923
|
+
.filter((key) => hasPurpose(key, 'assertionMethod'))
|
|
891
924
|
.map((key) => {
|
|
892
925
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
893
926
|
return key.kid
|
|
@@ -898,9 +931,7 @@ export function toDidDocument(
|
|
|
898
931
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&
|
|
899
932
|
identifier.keys && {
|
|
900
933
|
authentication: identifier.keys
|
|
901
|
-
.filter(
|
|
902
|
-
(key) => key?.meta?.purpose === undefined || key?.meta?.purpose === 'authentication' || key?.meta?.purposes?.includes('authentication'),
|
|
903
|
-
)
|
|
934
|
+
.filter((key) => hasPurpose(key, 'authentication'))
|
|
904
935
|
.map((key) => {
|
|
905
936
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
906
937
|
return key.kid
|
|
@@ -911,7 +942,7 @@ export function toDidDocument(
|
|
|
911
942
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
|
|
912
943
|
identifier.keys && {
|
|
913
944
|
keyAgreement: identifier.keys
|
|
914
|
-
.filter((key) => key.type === 'X25519' || key
|
|
945
|
+
.filter((key) => key.type === 'X25519' || hasPurpose(key, 'keyAgreement'))
|
|
915
946
|
.map((key) => {
|
|
916
947
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
917
948
|
return key.kid
|
|
@@ -922,10 +953,7 @@ export function toDidDocument(
|
|
|
922
953
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
|
|
923
954
|
identifier.keys && {
|
|
924
955
|
capabilityInvocation: identifier.keys
|
|
925
|
-
.filter(
|
|
926
|
-
(key) =>
|
|
927
|
-
key.type === 'X25519' || key?.meta?.purpose === 'capabilityInvocation' || key?.meta?.purposes?.includes('capabilityInvocation'),
|
|
928
|
-
)
|
|
956
|
+
.filter((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityInvocation'))
|
|
929
957
|
.map((key) => {
|
|
930
958
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
931
959
|
return key.kid
|
|
@@ -936,10 +964,7 @@ export function toDidDocument(
|
|
|
936
964
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
|
|
937
965
|
identifier.keys && {
|
|
938
966
|
capabilityDelegation: identifier.keys
|
|
939
|
-
.filter(
|
|
940
|
-
(key) =>
|
|
941
|
-
key.type === 'X25519' || key?.meta?.purpose === 'capabilityDelegation' || key?.meta?.purposes?.includes('capabilityDelegation'),
|
|
942
|
-
)
|
|
967
|
+
.filter((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityDelegation'))
|
|
943
968
|
.map((key) => {
|
|
944
969
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
945
970
|
return key.kid
|