@sphereon/ssi-sdk-ext.did-utils 0.36.1-feature.integration.fides.71 → 0.36.1-feature.integration.fides.74
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 +6 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
- package/src/did-functions.ts +8 -16
package/dist/index.cjs
CHANGED
|
@@ -644,6 +644,7 @@ var AgentDIDResolver = class {
|
|
|
644
644
|
return resolutionResult ?? origResolutionResult;
|
|
645
645
|
}
|
|
646
646
|
};
|
|
647
|
+
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");
|
|
647
648
|
function toDidDocument(identifier, opts) {
|
|
648
649
|
let didDocument = void 0;
|
|
649
650
|
if (identifier) {
|
|
@@ -665,7 +666,7 @@ function toDidDocument(identifier, opts) {
|
|
|
665
666
|
return vm;
|
|
666
667
|
}),
|
|
667
668
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
|
|
668
|
-
assertionMethod: identifier.keys.filter((key) => key
|
|
669
|
+
assertionMethod: identifier.keys.filter((key) => hasPurpose(key, "assertionMethod")).map((key) => {
|
|
669
670
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
670
671
|
return key.kid;
|
|
671
672
|
}
|
|
@@ -673,7 +674,7 @@ function toDidDocument(identifier, opts) {
|
|
|
673
674
|
})
|
|
674
675
|
},
|
|
675
676
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Signature)) && identifier.keys && {
|
|
676
|
-
authentication: identifier.keys.filter((key) => key
|
|
677
|
+
authentication: identifier.keys.filter((key) => hasPurpose(key, "authentication")).map((key) => {
|
|
677
678
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
678
679
|
return key.kid;
|
|
679
680
|
}
|
|
@@ -681,7 +682,7 @@ function toDidDocument(identifier, opts) {
|
|
|
681
682
|
})
|
|
682
683
|
},
|
|
683
684
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
|
|
684
|
-
keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
685
|
+
keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "keyAgreement")).map((key) => {
|
|
685
686
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
686
687
|
return key.kid;
|
|
687
688
|
}
|
|
@@ -689,7 +690,7 @@ function toDidDocument(identifier, opts) {
|
|
|
689
690
|
})
|
|
690
691
|
},
|
|
691
692
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
|
|
692
|
-
capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
693
|
+
capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityInvocation")).map((key) => {
|
|
693
694
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
694
695
|
return key.kid;
|
|
695
696
|
}
|
|
@@ -697,7 +698,7 @@ function toDidDocument(identifier, opts) {
|
|
|
697
698
|
})
|
|
698
699
|
},
|
|
699
700
|
...(opts?.use === void 0 || opts?.use?.includes(import_ssi_sdk_ext.JwkKeyUse.Encryption)) && identifier.keys && {
|
|
700
|
-
capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
701
|
+
capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityDelegation")).map((key) => {
|
|
701
702
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
702
703
|
return key.kid;
|
|
703
704
|
}
|
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 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\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,SAAO,MAAMC,wBACX;IACEN;IACAC;IACAC;IACAC;IACAC;IACAG,gBAAgB;EAClB,GACAF,OAAAA;AAEJ,GA3BoC;AA4B7B,IAAMC,0BAA0B,8BACrC,EACEN,YACAC,4BACAC,8BACAC,SACAC,eACAG,eAAc,GAShBF,YAAAA;AAEA,MAAIG,MAAiCC;AACrC,MAAI;AACFD,UACG,MAAME,kCACL;MACEV;MACAO;MACAI,iBAAiB;MACjBR;MACAC;IACF,GACAC,OAAAA,MAEDH,gCAA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AAA;EAC/C;AAEA,aAAOyN,0BAAUJ,SAASC,YAAYF,MAAAA;AACxC,GAR0B;AAanB,IAAMI,eAAe,8BAC1BL,SAAAA;AAiBA,QAAM,EAAE5C,QAAQvK,QAAO,IAAKmN;AAE5B,QAAMxN,aAAa,MAAMoL,oBAAoBR,QAAQvK,OAAAA;AACrD,QAAMG,MAAM,MAAMuK,OAChB;IACE/K;IACAO,gBAAgBqK,OAAOmD;IACvBtJ,WAAWmG,OAAOnG;EACpB,GACApE,OAAAA;AAEF,QAAM2N,YAAY,UAAMC,8CAA0B;IAAEzN;EAAI,CAAA;AAExD,SAAO,OAAO0N,SAAAA;AACZ,UAAM3G,QAAQ2G,gBAAgBC,OAAOC,eAAetG,UAAAA,IAAc,IAAIuG,YAAAA,EAAcC,OAAOJ,IAAAA,IAAuBA;AAClH,WAAO,MAAM7N,QAAQwC,MAAM0L,eAAe;MACxCC,QAAQhO,IAAIe;MACZyM;MACAE,MAAM3G;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","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","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 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 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 [x: string]: any\n}\n\nexport type CreateIdentifierOpts = {\n method: SupportedDidMethodEnum\n createOpts?: CreateIdentifierCreateOpts\n}\n\nexport type CreateIdentifierCreateOpts = {\n kms?: string\n alias?: string\n options?: IdentifierProviderOpts\n}\n\nexport type CreateOrGetIdentifierOpts = {\n method: SupportedDidMethodEnum\n createOpts?: CreateIdentifierCreateOpts\n}\n\nexport const DID_PREFIX = 'did:'\n\nexport interface GetOrCreateResult<T> {\n created: boolean\n result: T\n}\n\n/**\n * @deprecated Replaced by new signer\n */\nexport type SignJwtArgs = {\n idOpts: LegacyIIdentifierOpts\n header: Partial<JWTHeader>\n payload: Partial<JWTPayload>\n options: { issuer: string; expiresIn?: number; canonicalize?: boolean }\n context: IRequiredSignAgentContext\n}\n\n/**\n * @deprecated Replaced by new signer\n */\nexport type GetSignerArgs = {\n idOpts: LegacyIIdentifierOpts\n context: IRequiredSignAgentContext\n}\n\n/**\n * @deprecated Replaced by the identifier resolution service\n */\ntype LegacyIIdentifierOpts = {\n identifier: IIdentifier | string\n}\nexport type IRequiredSignAgentContext = IAgentContext<IKeyManager & IDIDManager & IResolver>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA,0BAA+B;AAC/B,4BAA4B;AAC5B,yBAWO;AACP,IAAAA,sBAA4B;AAC5B,qBAA0F;AAE1F,qBAAyC;AAEzC,mBASO;AACP,qBAAkC;AAGlC,sBAAqB;AAErB,UAAqB;;;AC7Bd,IAAKC,yBAAAA,0BAAAA,yBAAAA;;;;;;;;;SAAAA;;AAWL,IAAKC,sBAAAA,0BAAAA,sBAAAA;;SAAAA;;AA4CL,IAAMC,aAAa;;;ADZ1B,IAAM,EAAEC,YAAYC,SAAQ,IAAKC;AAE1B,IAAMC,uBAAuB,8BAClC,EACEC,YACAC,4BACAC,8BACAC,SACAC,cAAa,GAQfC,YAAAA;AAEA,SAAO,MAAMC,wBACX;IACEN;IACAC;IACAC;IACAC;IACAC;IACAG,gBAAgB;EAClB,GACAF,OAAAA;AAEJ,GA3BoC;AA4B7B,IAAMC,0BAA0B,8BACrC,EACEN,YACAC,4BACAC,8BACAC,SACAC,eACAG,eAAc,GAShBF,YAAAA;AAEA,MAAIG,MAAiCC;AACrC,MAAI;AACFD,UACG,MAAME,kCACL;MACEV;MACAO;MACAI,iBAAiB;MACjBR;MACAC;IACF,GACAC,OAAAA,MAEDH,gCAAgCK,mBAAmB,uBAChDE,SACA,MAAMC,kCACJ;MACEV;MACAO,g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zN,aAAa,MAAMoL,oBAAoBR,QAAQvK,OAAAA;AACrD,QAAMG,MAAM,MAAMuK,OAChB;IACE/K;IACAO,gBAAgBqK,OAAOoD;IACvBvJ,WAAWmG,OAAOnG;EACpB,GACApE,OAAAA;AAEF,QAAM4N,YAAY,UAAMC,8CAA0B;IAAE1N;EAAI,CAAA;AAExD,SAAO,OAAO2N,SAAAA;AACZ,UAAM5G,QAAQ4G,gBAAgBC,OAAOC,eAAevG,UAAAA,IAAc,IAAIwG,YAAAA,EAAcC,OAAOJ,IAAAA,IAAuBA;AAClH,WAAO,MAAM9N,QAAQwC,MAAM2L,eAAe;MACxCC,QAAQjO,IAAIe;MACZ0M;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","didManagerCreate","kms","getKms","alias","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.js
CHANGED
|
@@ -577,6 +577,7 @@ var AgentDIDResolver = class {
|
|
|
577
577
|
return resolutionResult ?? origResolutionResult;
|
|
578
578
|
}
|
|
579
579
|
};
|
|
580
|
+
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");
|
|
580
581
|
function toDidDocument(identifier, opts) {
|
|
581
582
|
let didDocument = void 0;
|
|
582
583
|
if (identifier) {
|
|
@@ -598,7 +599,7 @@ function toDidDocument(identifier, opts) {
|
|
|
598
599
|
return vm;
|
|
599
600
|
}),
|
|
600
601
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Signature)) && identifier.keys && {
|
|
601
|
-
assertionMethod: identifier.keys.filter((key) => key
|
|
602
|
+
assertionMethod: identifier.keys.filter((key) => hasPurpose(key, "assertionMethod")).map((key) => {
|
|
602
603
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
603
604
|
return key.kid;
|
|
604
605
|
}
|
|
@@ -606,7 +607,7 @@ function toDidDocument(identifier, opts) {
|
|
|
606
607
|
})
|
|
607
608
|
},
|
|
608
609
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Signature)) && identifier.keys && {
|
|
609
|
-
authentication: identifier.keys.filter((key) => key
|
|
610
|
+
authentication: identifier.keys.filter((key) => hasPurpose(key, "authentication")).map((key) => {
|
|
610
611
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
611
612
|
return key.kid;
|
|
612
613
|
}
|
|
@@ -614,7 +615,7 @@ function toDidDocument(identifier, opts) {
|
|
|
614
615
|
})
|
|
615
616
|
},
|
|
616
617
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
|
|
617
|
-
keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
618
|
+
keyAgreement: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "keyAgreement")).map((key) => {
|
|
618
619
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
619
620
|
return key.kid;
|
|
620
621
|
}
|
|
@@ -622,7 +623,7 @@ function toDidDocument(identifier, opts) {
|
|
|
622
623
|
})
|
|
623
624
|
},
|
|
624
625
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
|
|
625
|
-
capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
626
|
+
capabilityInvocation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityInvocation")).map((key) => {
|
|
626
627
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
627
628
|
return key.kid;
|
|
628
629
|
}
|
|
@@ -630,7 +631,7 @@ function toDidDocument(identifier, opts) {
|
|
|
630
631
|
})
|
|
631
632
|
},
|
|
632
633
|
...(opts?.use === void 0 || opts?.use?.includes(JwkKeyUse.Encryption)) && identifier.keys && {
|
|
633
|
-
capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || key
|
|
634
|
+
capabilityDelegation: identifier.keys.filter((key) => key.type === "X25519" || hasPurpose(key, "capabilityDelegation")).map((key) => {
|
|
634
635
|
if (key.kid.startsWith(did) && key.kid.includes("#")) {
|
|
635
636
|
return key.kid;
|
|
636
637
|
}
|
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 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\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,Q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c,IAAIuG,YAAAA,EAAcC,OAAOJ,IAAAA,IAAuBA;AAClH,WAAO,MAAM7N,QAAQwC,MAAM0L,eAAe;MACxCC,QAAQhO,IAAIe;MACZyM;MACAE,MAAM3G;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","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","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 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 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 [x: string]: any\n}\n\nexport type CreateIdentifierOpts = {\n method: SupportedDidMethodEnum\n createOpts?: CreateIdentifierCreateOpts\n}\n\nexport type CreateIdentifierCreateOpts = {\n kms?: string\n alias?: string\n options?: IdentifierProviderOpts\n}\n\nexport type CreateOrGetIdentifierOpts = {\n method: SupportedDidMethodEnum\n createOpts?: CreateIdentifierCreateOpts\n}\n\nexport const DID_PREFIX = 'did:'\n\nexport interface GetOrCreateResult<T> {\n created: boolean\n result: T\n}\n\n/**\n * @deprecated Replaced by new signer\n */\nexport type SignJwtArgs = {\n idOpts: LegacyIIdentifierOpts\n header: Partial<JWTHeader>\n payload: Partial<JWTPayload>\n options: { issuer: string; expiresIn?: number; canonicalize?: boolean }\n context: IRequiredSignAgentContext\n}\n\n/**\n * @deprecated Replaced by new signer\n */\nexport type GetSignerArgs = {\n idOpts: LegacyIIdentifierOpts\n context: IRequiredSignAgentContext\n}\n\n/**\n * @deprecated Replaced by the identifier resolution service\n */\ntype LegacyIIdentifierOpts = {\n identifier: IIdentifier | string\n}\nexport type IRequiredSignAgentContext = IAgentContext<IKeyManager & IDIDManager & IResolver>\n"],"mappings":";;;;AAAA,SAASA,sBAAsB;AAC/B,SAASC,mBAAmB;AAC5B,SACEC,cACAC,QACAC,WACAC,+BACAC,mBACAC,cACAC,2BAEAC,OACAC,sBACK;AACP,SAASC,mBAAmB;AAC5B,SAASC,eAAeC,eAAeC,YAAYC,YAAYC,2BAA2B;AAE1F,SAASC,gCAAgC;AAEzC,SAIEC,iCACAC,iCACAC,oBACAC,WACAC,8BACK;AACP,SAASC,iBAAyB;AAGlC,OAAOC,cAAc;AAErB,YAAYC,SAAS;;;AC7Bd,IAAKC,yBAAAA,0BAAAA,yBAAAA;;;;;;;;;SAAAA;;AAWL,IAAKC,sBAAAA,0BAAAA,sBAAAA;;SAAAA;;AA4CL,IAAMC,aAAa;;;ADZ1B,IAAM,EAAEC,YAAYC,SAAQ,IAAKC;AAE1B,IAAMC,uBAAuB,8BAClC,EACEC,YACAC,4BACAC,8BACAC,SACAC,cAAa,GAQfC,YAAAA;AAEA,SAAO,MAAMC,wBACX;IACEN;IACAC;IACAC;IACAC;IACAC;IACAG,gBAAgB;EAClB,GACAF,OAAAA;AAEJ,GA3BoC;AA4B7B,IAAMC,0BAA0B,8BACrC,EACEN,YACAC,4BACAC,8BACAC,SACAC,eACAG,eAAc,GAShBF,YAAAA;AAEA,MAAIG,MAAiCC;AACrC,MAAI;AACFD,UACG,MAAME,kCACL;MACEV;MACAO;MACAI,iBAAiB;MACjBR;MACAC;IACF,GACAC,OAAAA,MAEDH,gCAAgCK,mBAAmB,uBAChDE,SACA,MAAMC,kCACJ;MACEV;MACAO,gBAAgB;MAChBI,iBAAiB;MACjBR;MACAC;IACF,GACAC,OAAAA;EAEV,SAASO,GAAG;AACV,QAAIA,aAAaC,OAAO;AACtB,UAAI,CAACD,EAAEE,QAAQC,SAAS,KAAA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EAAI,CAAA;AAExD,SAAO,OAAO2N,SAAAA;AACZ,UAAM5G,QAAQ4G,gBAAgBC,OAAOC,eAAevG,UAAAA,IAAc,IAAIwG,YAAAA,EAAcC,OAAOJ,IAAAA,IAAuBA;AAClH,WAAO,MAAM9N,QAAQwC,MAAM2L,eAAe;MACxCC,QAAQjO,IAAIe;MACZ0M;MACAE,MAAM5G;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","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.integration.fides.
|
|
4
|
+
"version": "0.36.1-feature.integration.fides.74+0d17e392",
|
|
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.integration.fides.
|
|
29
|
-
"@sphereon/ssi-sdk-ext.x509-utils": "0.36.1-feature.integration.fides.
|
|
30
|
-
"@sphereon/ssi-sdk.agent-config": "0.36.1-feature.integration.fides.
|
|
31
|
-
"@sphereon/ssi-sdk.core": "0.36.1-feature.integration.fides.
|
|
32
|
-
"@sphereon/ssi-types": "0.36.1-feature.integration.fides.
|
|
28
|
+
"@sphereon/ssi-sdk-ext.key-utils": "0.36.1-feature.integration.fides.74+0d17e392",
|
|
29
|
+
"@sphereon/ssi-sdk-ext.x509-utils": "0.36.1-feature.integration.fides.74+0d17e392",
|
|
30
|
+
"@sphereon/ssi-sdk.agent-config": "0.36.1-feature.integration.fides.74+0d17e392",
|
|
31
|
+
"@sphereon/ssi-sdk.core": "0.36.1-feature.integration.fides.74+0d17e392",
|
|
32
|
+
"@sphereon/ssi-types": "0.36.1-feature.integration.fides.74+0d17e392",
|
|
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": "0d17e392eadbabaf626832e1841493cc29be7787"
|
|
57
57
|
}
|
package/src/did-functions.ts
CHANGED
|
@@ -855,6 +855,9 @@ export class AgentDIDResolver implements Resolvable {
|
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
857
|
|
|
858
|
+
const hasPurpose = (key: IKey, purpose: string) =>
|
|
859
|
+
(key?.meta?.purpose === undefined && key?.meta?.purposes === undefined) || key?.meta?.purpose === purpose || key?.meta?.purposes?.includes(purpose)
|
|
860
|
+
|
|
858
861
|
/**
|
|
859
862
|
* Please note that this is not an exact representation of the actual DID Document.
|
|
860
863
|
*
|
|
@@ -899,10 +902,7 @@ export function toDidDocument(
|
|
|
899
902
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&
|
|
900
903
|
identifier.keys && {
|
|
901
904
|
assertionMethod: identifier.keys
|
|
902
|
-
.filter(
|
|
903
|
-
(key) =>
|
|
904
|
-
key?.meta?.purpose === undefined || key?.meta?.purpose === 'assertionMethod' || key?.meta?.purposes?.includes('assertionMethod'),
|
|
905
|
-
)
|
|
905
|
+
.filter((key) => hasPurpose(key, 'assertionMethod'))
|
|
906
906
|
.map((key) => {
|
|
907
907
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
908
908
|
return key.kid
|
|
@@ -913,9 +913,7 @@ export function toDidDocument(
|
|
|
913
913
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Signature)) &&
|
|
914
914
|
identifier.keys && {
|
|
915
915
|
authentication: identifier.keys
|
|
916
|
-
.filter(
|
|
917
|
-
(key) => key?.meta?.purpose === undefined || key?.meta?.purpose === 'authentication' || key?.meta?.purposes?.includes('authentication'),
|
|
918
|
-
)
|
|
916
|
+
.filter((key) => hasPurpose(key, 'authentication'))
|
|
919
917
|
.map((key) => {
|
|
920
918
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
921
919
|
return key.kid
|
|
@@ -926,7 +924,7 @@ export function toDidDocument(
|
|
|
926
924
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
|
|
927
925
|
identifier.keys && {
|
|
928
926
|
keyAgreement: identifier.keys
|
|
929
|
-
.filter((key) => key.type === 'X25519' || key
|
|
927
|
+
.filter((key) => key.type === 'X25519' || hasPurpose(key, 'keyAgreement'))
|
|
930
928
|
.map((key) => {
|
|
931
929
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
932
930
|
return key.kid
|
|
@@ -937,10 +935,7 @@ export function toDidDocument(
|
|
|
937
935
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
|
|
938
936
|
identifier.keys && {
|
|
939
937
|
capabilityInvocation: identifier.keys
|
|
940
|
-
.filter(
|
|
941
|
-
(key) =>
|
|
942
|
-
key.type === 'X25519' || key?.meta?.purpose === 'capabilityInvocation' || key?.meta?.purposes?.includes('capabilityInvocation'),
|
|
943
|
-
)
|
|
938
|
+
.filter((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityInvocation'))
|
|
944
939
|
.map((key) => {
|
|
945
940
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
946
941
|
return key.kid
|
|
@@ -951,10 +946,7 @@ export function toDidDocument(
|
|
|
951
946
|
...((opts?.use === undefined || opts?.use?.includes(JwkKeyUse.Encryption)) &&
|
|
952
947
|
identifier.keys && {
|
|
953
948
|
capabilityDelegation: identifier.keys
|
|
954
|
-
.filter(
|
|
955
|
-
(key) =>
|
|
956
|
-
key.type === 'X25519' || key?.meta?.purpose === 'capabilityDelegation' || key?.meta?.purposes?.includes('capabilityDelegation'),
|
|
957
|
-
)
|
|
949
|
+
.filter((key) => key.type === 'X25519' || hasPurpose(key, 'capabilityDelegation'))
|
|
958
950
|
.map((key) => {
|
|
959
951
|
if (key.kid.startsWith(did) && key.kid.includes('#')) {
|
|
960
952
|
return key.kid
|