@sphereon/ssi-sdk.credential-vcdm2-sdjwt-provider 0.34.1-next.88 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/agent/CredentialProviderVcdm2SdJwt.ts","../src/did-jwt/JWT.ts","../src/did-jwt/util.ts","../src/did-jwt/SignerAlgorithm.ts","../src/did-jwt/VerifierAlgorithm.ts"],"sourcesContent":["export { CredentialProviderVcdm2SdJwt } from './agent/CredentialProviderVcdm2SdJwt'\n","import {\n type ExternalIdentifierDidOpts,\n ExternalIdentifierResult,\n type IIdentifierResolution,\n isDidIdentifier,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport type { IJwtService, JwsHeader, JwsPayload } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { signatureAlgorithmFromKey } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { contextHasPlugin } from '@sphereon/ssi-sdk.agent-config'\nimport { asArray, intersect, type VerifiableCredentialSP, type VerifiablePresentationSP } from '@sphereon/ssi-sdk.core'\nimport {\n type ICanIssueCredentialTypeArgs,\n type ICanVerifyDocumentTypeArgs,\n type ICreateVerifiableCredentialLDArgs,\n type ICreateVerifiablePresentationLDArgs,\n type IVcdmCredentialProvider,\n type IVcdmIssuerAgentContext,\n IVcdmVerifierAgentContext,\n IVerifyCredentialVcdmArgs,\n IVerifyPresentationLDArgs,\n pickSigningKey,\n preProcessCredentialPayload,\n preProcessPresentation,\n} from '@sphereon/ssi-sdk.credential-vcdm'\nimport { CredentialMapper, isVcdm2Credential, type IVerifyResult, type OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport type {\n IAgentContext,\n IDIDManager,\n IIdentifier,\n IKey,\n IKeyManager,\n IResolver,\n VerifiableCredential,\n VerificationPolicies,\n VerifierAgentContext,\n} from '@veramo/core'\n\nimport Debug from 'debug'\n\nimport { decodeJWT, JWT_ERROR } from 'did-jwt'\n\n// @ts-ignore\nimport { normalizeCredential, normalizePresentation, verifyPresentation as verifyPresentationJWT } from 'did-jwt-vc'\n\nimport { type Resolvable } from 'did-resolver'\n\nimport { SELF_ISSUED_V0_1, SELF_ISSUED_V2, SELF_ISSUED_V2_VC_INTEROP } from '../did-jwt/JWT'\nimport { getIssuerFromSdJwt, ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\n// import {validateCredentialPayload} from \"did-jwt-vc/src\";\n\nconst debug = Debug('sphereon:ssi-sdk:credential-vcdm2-sdjwt')\n\n/**\n * A handler that implements the {@link IVcdmCredentialProvider} methods.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport class CredentialProviderVcdm2SdJwt implements IVcdmCredentialProvider {\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.matchKeyForType} */\n matchKeyForType(key: IKey): boolean {\n return this.matchKeyForJWT(key)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.getTypeProofFormat} */\n getTypeProofFormat(): string {\n return 'vc+sd-jwt'\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canIssueCredentialType} */\n canIssueCredentialType(args: ICanIssueCredentialTypeArgs): boolean {\n const format = args.proofFormat.toLowerCase()\n // TODO: Create type\n return format === 'vc+sd-jwt' || format === 'vcdm2_sdjwt'\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canVerifyDocumentType */\n canVerifyDocumentType(args: ICanVerifyDocumentTypeArgs): boolean {\n const { document } = args\n const jwt = typeof document === 'string' ? document : (<VerifiableCredential>document)?.proof?.jwt\n if (!jwt) {\n return false\n }\n const { payload } = decodeJWT(jwt.split('~')[0])\n return isVcdm2Credential(payload)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiableCredential} */\n async createVerifiableCredential(args: ICreateVerifiableCredentialLDArgs, context: IVcdmIssuerAgentContext): Promise<VerifiableCredentialSP> {\n const { keyRef } = args\n const agent = assertContext(context).agent\n const { credential, issuer } = preProcessCredentialPayload(args)\n if (!isVcdm2Credential(credential)) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential. Context: ' + credential['@context']))\n } else if (!contextHasPlugin<ISDJwtPlugin>(context, 'createSdJwtVc')) {\n return Promise.reject(\n new Error('invalid_argument: SD-JWT plugin not available. Please install @sphereon/ssi-sdk.sd-jwt and configure agent for VCDM2 SD-JWT'),\n )\n }\n let identifier: IIdentifier\n try {\n identifier = await agent.didManagerGet({ did: issuer })\n } catch (e) {\n return Promise.reject(new Error(`invalid_argument: ${credential.issuer} must be a DID managed by this agent. ${e}`))\n }\n const managedIdentifier = await agent.identifierManagedGetByDid({ identifier: identifier.did, kmsKeyRef: keyRef })\n const key = await pickSigningKey({ identifier, kmsKeyRef: keyRef }, context)\n\n // TODO: Probably wise to give control to caller as well, as some key types allow multiple signature algos\n const alg = (await signatureAlgorithmFromKey({ key })) as string\n debug('Signing VC with', identifier.did, alg)\n credential.issuer = { id: identifier.did }\n\n const result = await context.agent.createSdJwtVc({\n type: 'vc+sd-jwt',\n credentialPayload: credential,\n resolution: managedIdentifier,\n disclosureFrame: args.opts?.disclosureFrame,\n })\n\n const jwt = result.credential.split('~')[0]\n\n // debug(jwt)\n const normalized = normalizeCredential(jwt)\n normalized.proof.jwt = result.credential\n return normalized\n }\n\n /** {@inheritdoc ICredentialVerifier.verifyCredential} */\n async verifyCredential(args: IVerifyCredentialVcdmArgs, context: VerifierAgentContext): Promise<IVerifyResult> {\n let { credential, policies /*...otherOptions*/ } = args\n const uniform = CredentialMapper.toUniformCredential(credential as OriginalVerifiableCredential)\n // let verifiedCredential: VerifiableCredential\n if (!isVcdm2Credential(uniform)) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential. Context: ' + uniform['@context']))\n } else if (!contextHasPlugin<ISDJwtPlugin>(context, 'createSdJwtVc')) {\n return Promise.reject(\n new Error('invalid_argument: SD-JWT plugin not available. Please install @sphereon/ssi-sdk.sd-jwt and configure agent for VCDM2 SD-JWT'),\n )\n }\n let verificationResult: IVerifyResult = { verified: false }\n let jwt: string | undefined = typeof credential === 'string' ? credential : asArray(uniform.proof)?.[0]?.jwt\n if (!jwt) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential in JOSE format (string)'))\n }\n\n try {\n const result = await context.agent.verifySdJwtVc({ credential: jwt })\n if (result.payload) {\n verificationResult = {\n verified: true,\n results: [\n {\n credential: credential as OriginalVerifiableCredential,\n verified: true,\n log: [\n {\n id: 'valid_signature',\n valid: true,\n },\n {\n id: 'issuer_did_resolves',\n valid: true,\n },\n ],\n },\n ],\n }\n }\n } catch (e) {\n verificationResult = { verified: false, error: { message: e.message, errorCode: e.name } }\n }\n\n policies = {\n ...policies,\n nbf: policies?.nbf ?? policies?.issuanceDate ?? policies?.validFrom,\n iat: policies?.iat ?? policies?.issuanceDate ?? policies?.validFrom,\n exp: policies?.exp ?? policies?.expirationDate ?? policies?.validUntil,\n aud: policies?.aud ?? policies?.audience,\n }\n verificationResult = await verifierSignature({ jwt: jwt.split('~')[0], policies }, context)\n return verificationResult\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiablePresentation} */\n async createVerifiablePresentation(args: ICreateVerifiablePresentationLDArgs, context: IVcdmIssuerAgentContext): Promise<VerifiablePresentationSP> {\n const { presentation, holder } = preProcessPresentation(args)\n let { domain, challenge, keyRef /* removeOriginalFields, keyRef, now, ...otherOptions*/ } = args\n\n const agent = assertContext(context).agent\n\n const managedIdentifier = await agent.identifierManagedGetByDid({ identifier: holder, kmsKeyRef: keyRef })\n const identifier = managedIdentifier.identifier\n const key = await pickSigningKey(\n {\n identifier: managedIdentifier.identifier,\n kmsKeyRef: managedIdentifier.kmsKeyRef,\n },\n context,\n )\n\n debug('Signing VC with', identifier.did)\n let alg = 'ES256'\n if (key.type === 'Ed25519') {\n alg = 'EdDSA'\n } else if (key.type === 'Secp256k1') {\n alg = 'ES256K'\n }\n\n const header: JwsHeader = {\n kid: key.meta.verificationMethod.id ?? key.kid,\n alg,\n typ: 'vp+jwt',\n cty: 'vp',\n }\n const payload: JwsPayload = {\n ...presentation,\n ...(domain && { aud: domain }),\n ...(challenge && { nonce: challenge }),\n }\n\n const jwt = await agent.jwtCreateJwsCompactSignature({\n mode: 'did',\n issuer: managedIdentifier,\n payload,\n protectedHeader: header,\n clientIdScheme: 'did',\n })\n\n debug(jwt)\n return normalizePresentation(jwt.jwt)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.verifyPresentation} */\n async verifyPresentation(args: IVerifyPresentationLDArgs, context: VerifierAgentContext): Promise<IVerifyResult> {\n let { presentation, domain, challenge, fetchRemoteContexts, policies, ...otherOptions } = args\n let jwt: string\n if (typeof presentation === 'string') {\n jwt = presentation\n } else {\n jwt = asArray(presentation.proof)[0].jwt\n }\n const resolver = {\n resolve: (didUrl: string) =>\n context.agent.resolveDid({\n didUrl,\n options: otherOptions?.resolutionOptions,\n }),\n } as Resolvable\n\n let audience = domain\n if (!audience) {\n const { payload } = await decodeJWT(jwt)\n if (payload.aud) {\n // automatically add a managed DID as audience if one is found\n const intendedAudience = asArray(payload.aud)\n const managedDids = await context.agent.didManagerFind()\n const filtered = managedDids.filter((identifier) => intendedAudience.includes(identifier.did))\n if (filtered.length > 0) {\n audience = filtered[0].did\n }\n }\n }\n\n let message, errorCode\n try {\n const result = await verifyPresentationJWT(jwt, resolver, {\n challenge,\n domain,\n audience,\n policies: {\n ...policies,\n nbf: policies?.nbf ?? policies?.issuanceDate,\n iat: policies?.iat ?? policies?.issuanceDate,\n exp: policies?.exp ?? policies?.expirationDate,\n aud: policies?.aud ?? policies?.audience,\n },\n ...otherOptions,\n })\n if (result) {\n /**\n * {id: 'valid_signature', valid: true},\n * // {id: 'issuer_did_resolves', valid: true},\n * // {id: 'expiration', valid: true},\n * // {id: 'revocation_status', valid: true},\n * // {id: 'suspension_status', valid: true}\n */\n return {\n verified: true,\n results: [\n {\n verified: true,\n presentation: result.verifiablePresentation,\n log: [\n {\n id: 'valid_signature',\n valid: true,\n },\n ],\n },\n ],\n } satisfies IVerifyResult\n }\n } catch (e: any) {\n message = e.message\n errorCode = e.errorCode\n }\n return {\n verified: false,\n error: {\n message,\n errorCode: errorCode ? errorCode : message?.split(':')[0],\n },\n }\n }\n\n /**\n * Checks if a key is suitable for signing JWT payloads.\n * @param key - the key to check\n * @param context - the Veramo agent context, unused here\n *\n * @beta\n */\n matchKeyForJWT(key: IKey): boolean {\n switch (key.type) {\n case 'Ed25519':\n case 'Secp256r1':\n return true\n case 'Secp256k1':\n return intersect(key.meta?.algorithms ?? [], ['ES256K', 'ES256K-R']).length > 0\n default:\n return false\n }\n }\n\n wrapSigner(context: IAgentContext<Pick<IKeyManager, 'keyManagerSign'>>, key: IKey, algorithm?: string) {\n return async (data: string | Uint8Array): Promise<string> => {\n const result = await context.agent.keyManagerSign({ keyRef: key.kid, data: <string>data, algorithm })\n return result\n }\n }\n}\n\nexport async function verifierSignature(\n { jwt, policies }: { jwt: string; policies: VerificationPolicies /*resolver: Resolvable*/ },\n verifierContext: VerifierAgentContext,\n): Promise<IVerifyResult> {\n let credIssuer: string | undefined = undefined\n const context = assertContext(verifierContext)\n const agent = context.agent\n const { payload, header /*signature, data*/ } = decodeJWT(jwt)\n\n\n\n if (!payload.issuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n const issuer = getIssuerFromSdJwt(payload)\n if (issuer === SELF_ISSUED_V2 || issuer === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.credentialSubject.id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT credentialSubject.id is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n credIssuer = payload.sub\n } else {\n credIssuer = (header.kid || '').split('#')[0]\n }\n } else if (issuer === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n credIssuer = payload.did\n } else if (!issuer && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n credIssuer = payload.client_id\n } else if (issuer?.indexOf('did:') === 0) {\n credIssuer = issuer\n } else if (header.kid?.indexOf('did:') === 0) {\n // OID4VCI expects iss to be the client and kid, to be the DID VM\n credIssuer = (header.kid || '').split('#')[0]\n } else if (typeof payload.issuer === 'string') {\n credIssuer = payload.issuer\n } else if (payload.issuer?.id) {\n credIssuer = payload.issuer.id\n }\n\n if (!credIssuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n let resolution: ExternalIdentifierResult | undefined = undefined\n try {\n resolution = await agent.identifierExternalResolve({ identifier: credIssuer })\n } catch (e: any) {}\n const credential = CredentialMapper.toUniformCredential(jwt)\n\n const validFromError =\n policies.nbf !== false &&\n policies.iat !== false &&\n 'validFrom' in credential &&\n !!credential.validFrom &&\n Date.parse(credential.validFrom) > new Date().getTime()\n const expired =\n policies.exp !== false && 'validUntil' in credential && !!credential.validUntil && Date.parse(credential.validUntil) < new Date().getTime()\n\n const didOpts = { method: 'did', identifier: credIssuer } satisfies ExternalIdentifierDidOpts\n const jwtResult = await agent.jwtVerifyJwsSignature({\n jws: jwt,\n // @ts-ignore\n jwk: resolution?.jwks[0].jwk,\n opts: { ...(isDidIdentifier(credIssuer) && { did: didOpts }) },\n })\n const error = jwtResult.error || expired || !resolution\n const errorMessage = expired\n ? 'Credential is expired'\n : validFromError\n ? 'Credential is not valid yet'\n : !resolution\n ? `Issuer ${credIssuer} could not be resolved`\n : jwtResult.message\n\n if (error) {\n const log = [\n {\n id: 'valid_signature',\n valid: !jwtResult.error,\n },\n { id: 'issuer_did_resolves', valid: resolution != undefined },\n { id: 'validFrom', valid: policies.nbf !== false && !validFromError },\n { id: 'expiration', valid: policies.exp !== false && !expired },\n ]\n return {\n verified: false,\n error: { message: errorMessage, errorCode: jwtResult.name },\n log,\n results: [\n {\n verified: false,\n credential: jwt,\n log,\n error: { message: errorMessage, errorCode: jwtResult.name },\n },\n ],\n payload,\n didResolutionResult: resolution,\n jwt,\n } satisfies IVerifyResult\n }\n\n const log = [\n {\n id: 'valid_signature',\n valid: true,\n },\n {\n id: 'issuer_did_resolves',\n valid: true,\n },\n {\n id: 'validFrom',\n valid: true,\n },\n {\n id: 'expiration',\n valid: true,\n },\n ]\n return {\n verified: true,\n log,\n results: [\n {\n verified: true,\n credential,\n log,\n },\n ],\n payload,\n didResolutionResult: resolution,\n jwt,\n } satisfies IVerifyResult\n}\n\n/*\nexport async function verifyDIDJWT(\n jwt: string,\n options: JWTVerifyOptions = {\n resolver: undefined,\n auth: undefined,\n audience: undefined,\n callbackUrl: undefined,\n skewTime: undefined,\n proofPurpose: undefined,\n policies: {},\n },\n verifierContext: VerifierAgentContext,\n): Promise<JWTVerified> {\n const context = assertContext(verifierContext)\n const agent = context.agent\n if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n const { payload, header, signature, data }: JWTDecoded = decodeJWT(jwt)\n const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n ? options.auth\n ? 'authentication'\n : undefined\n : options.proofPurpose\n\n let credIssuer: string | undefined = undefined\n\n if (!payload.iss && !payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n\n if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.sub) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n credIssuer = payload.sub\n } else {\n credIssuer = (header.kid || '').split('#')[0]\n }\n } else if (payload.iss === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n credIssuer = payload.did\n } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n credIssuer = payload.client_id\n } else if (payload.iss?.indexOf('did:') === 0) {\n credIssuer = payload.iss\n } else if (header.kid?.indexOf('did:') === 0) {\n // OID4VCI expects iss to be the client and kid, to be the DID VM\n credIssuer = (header.kid || '').split('#')[0]\n } else if (payload.iss) {\n credIssuer = payload.iss\n }\n\n if (!credIssuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n\n const resolution = await agent.identifierExternalResolve({ identifier: credIssuer })\n\n const didOpts = { method: 'did', identifier: credIssuer } satisfies ExternalIdentifierDidOpts\n const jwtResult = await agent.jwtVerifyJwsSignature({\n jws: jwt,\n // @ts-ignore\n jwk: resolution.jwks[0],\n opts: { ...(isDidIdentifier(credIssuer) && { did: didOpts }) },\n })\n\n if (jwtResult.error) {\n return Promise.reject(Error(`Error validating credential: ${jwtResult.error}`))\n }\n const { didResolutionResult, authenticators, issuer }: DIDAuthenticator = await resolveAuthenticator(\n options.resolver,\n header.alg,\n credIssuer,\n proofPurpose,\n )\n const signer: VerificationMethod = verifyJWSDecoded({ header, data, signature } as JWSDecoded, authenticators)\n const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n if (signer) {\n const nowSkewed = now + skewTime\n if (options.policies?.nbf !== false && payload.nbf) {\n if (payload.nbf > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n }\n } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n }\n if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n }\n if (options.policies?.aud !== false && payload.aud) {\n if (!options.audience && !options.callbackUrl) {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`)\n }\n const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n const matchedAudience = audArray.find((item: any) => options.audience === item || options.callbackUrl === item)\n\n if (typeof matchedAudience === 'undefined') {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n }\n }\n return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n }\n throw new Error(\n `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`,\n )\n}\n\nfunction verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n return signer\n}\n\n\nexport function validateCredentialPayload(payload: CredentialPayload): void {\n validateContext(asArray(payload['@context']))\n validateVcType(payload.type)\n validateCredentialSubject(payload.credentialSubject)\n if (payload.validFrom) validateTimestamp(payload.validFrom)\n if (payload.validUntil) validateTimestamp(payload.validUntil)\n}\n\nexport function validateContext(value: string | string[]): void {\n const input = asArray(value)\n if (input.length < 1 || input.indexOf(VCDM_CREDENTIAL_CONTEXT_V2) === -1) {\n throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: @context is missing default context \"${VCDM_CREDENTIAL_CONTEXT_V2}\"`)\n }\n}\n*/\nfunction assertContext(\n context: IVcdmIssuerAgentContext | IVcdmVerifierAgentContext,\n): IAgentContext<\n IResolver & IDIDManager & Pick<IKeyManager, 'keyManagerGet' | 'keyManagerSign' | 'keyManagerVerify'> & IJwtService & IIdentifierResolution\n> {\n if (!contextHasPlugin<IJwtService>(context, 'jwtPrepareJws')) {\n throw Error(\n 'JwtService plugin not found, which is required for JWT signing in the VCDM2 SD-JWT credential provider. Please add the JwtService plugin to your agent configuration.',\n )\n } else if (!contextHasPlugin<IIdentifierResolution>(context, 'identifierManagedGet')) {\n throw Error(\n 'Identifier resolution plugin not found, which is required for JWT signing in the VCDM2 SD-JWT credential provider. Please add the JwtService plugin to your agent configuration.',\n )\n }\n return context as IAgentContext<\n IResolver & IDIDManager & Pick<IKeyManager, 'keyManagerGet' | 'keyManagerSign' | 'keyManagerVerify'> & IJwtService & IIdentifierResolution\n >\n}\n","import canonicalizeData from 'canonicalize'\nimport { type DIDDocument, type DIDResolutionResult, parse, type ParsedDID, type Resolvable, type VerificationMethod } from 'did-resolver'\nimport SignerAlg from './SignerAlgorithm'\nimport { decodeBase64url, type EcdsaSignature, encodeBase64url, type KNOWN_JWA, SUPPORTED_PUBLIC_KEY_TYPES } from './util'\nimport VerifierAlgorithm from './VerifierAlgorithm'\nimport { JWT_ERROR } from 'did-jwt'\n\nexport type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>\nexport type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>\n\nexport type ProofPurposeTypes =\n | 'assertionMethod'\n | 'authentication'\n // | 'keyAgreement' // keyAgreement VerificationMethod should not be used for signing\n | 'capabilityDelegation'\n | 'capabilityInvocation'\n\nexport interface JWTOptions {\n issuer: string\n signer: Signer\n /**\n * @deprecated Please use `header.alg` to specify the JWT algorithm.\n */\n alg?: string\n expiresIn?: number\n canonicalize?: boolean\n}\n\nexport interface JWTVerifyOptions {\n /** @deprecated Please use `proofPurpose: 'authentication' instead` */\n auth?: boolean\n audience?: string\n callbackUrl?: string\n resolver?: Resolvable\n skewTime?: number\n /** See https://www.w3.org/TR/did-spec-registries/#verification-relationships */\n proofPurpose?: ProofPurposeTypes\n policies?: JWTVerifyPolicies\n didAuthenticator?: DIDAuthenticator\n}\n\n/**\n * Overrides the different types of checks performed on the JWT besides the signature check\n */\nexport interface JWTVerifyPolicies {\n // overrides the timestamp against which the validity interval is checked\n now?: number\n // when set to false, the timestamp checks ignore the Not Before(`nbf`) property\n nbf?: boolean\n // when set to false, the timestamp checks ignore the Issued At(`iat`) property\n iat?: boolean\n // when set to false, the timestamp checks ignore the Expires At(`exp`) property\n exp?: boolean\n // when set to false, the JWT audience check is skipped\n aud?: boolean\n}\n\nexport interface JWSCreationOptions {\n canonicalize?: boolean\n}\n\nexport interface DIDAuthenticator {\n authenticators: VerificationMethod[]\n issuer: string\n didResolutionResult: DIDResolutionResult\n}\n\nexport interface JWTHeader {\n typ: 'JWT'\n alg: string\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any\n}\n\nexport interface JWTPayload {\n iss?: string\n sub?: string\n aud?: string | string[]\n iat?: number\n nbf?: number\n exp?: number\n rexp?: number\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any\n}\n\nexport interface JWTDecoded {\n header: JWTHeader\n payload: JWTPayload\n signature: string\n data: string\n}\n\nexport interface JWSDecoded {\n header: JWTHeader\n payload: string\n signature: string\n data: string\n}\n\n/**\n * Result object returned by {@link verifyJWT}\n */\nexport interface JWTVerified {\n /**\n * Set to true for a JWT that passes all the required checks minus any verification overrides.\n */\n verified: true\n\n /**\n * The decoded JWT payload\n */\n payload: Partial<JWTPayload>\n\n /**\n * The result of resolving the issuer DID\n */\n didResolutionResult: DIDResolutionResult\n\n /**\n * the issuer DID\n */\n issuer: string\n\n /**\n * The public key of the issuer that matches the JWT signature\n */\n signer: VerificationMethod\n\n /**\n * The original JWT that was verified\n */\n jwt: string\n\n /**\n * Any overrides that were used during verification\n */\n policies?: JWTVerifyPolicies\n}\n\nexport const SELF_ISSUED_V2 = 'https://self-issued.me/v2'\nexport const SELF_ISSUED_V2_VC_INTEROP = 'https://self-issued.me/v2/openid-vc' // https://identity.foundation/jwt-vc-presentation-profile/#id-token-validation\nexport const SELF_ISSUED_V0_1 = 'https://self-issued.me'\n\ntype LegacyVerificationMethod = { publicKey?: string }\n\nconst defaultAlg: KNOWN_JWA = 'ES256K'\nconst DID_JSON = 'application/did+json'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction encodeSection(data: any, shouldCanonicalize = false): string {\n if (shouldCanonicalize) {\n return encodeBase64url(<string>canonicalizeData(data))\n } else {\n return encodeBase64url(JSON.stringify(data))\n }\n}\n\nexport const NBF_SKEW = 300\n\nfunction decodeJWS(jws: string): JWSDecoded {\n const parts = jws.match(/^([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)$/)\n if (parts) {\n return {\n header: JSON.parse(decodeBase64url(parts[1])),\n payload: parts[2],\n signature: parts[3],\n data: `${parts[1]}.${parts[2]}`,\n }\n }\n throw new Error('invalid_argument: Incorrect format JWS')\n}\n\n/**\n * Decodes a JWT and returns an object representing the payload\n *\n * @example\n * decodeJWT('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJpYXQiOjE1...')\n *\n * @param {String} jwt a JSON Web Token to verify\n * @param {Object} [recurse] whether to recurse into the payload to decode any nested JWTs\n * @return {Object} a JS object representing the decoded JWT\n */\nexport function decodeJWT(jwt: string, recurse = true): JWTDecoded {\n if (!jwt) throw new Error('invalid_argument: no JWT passed into decodeJWT')\n try {\n const jws = decodeJWS(jwt)\n const decodedJwt: JWTDecoded = Object.assign(jws, { payload: JSON.parse(decodeBase64url(jws.payload)) })\n const iss = decodedJwt.payload.iss\n\n if (decodedJwt.header.cty === 'JWT' && recurse) {\n const innerDecodedJwt = decodeJWT(decodedJwt.payload.jwt)\n\n if (innerDecodedJwt.payload.iss !== iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n return innerDecodedJwt\n }\n return decodedJwt\n } catch (e) {\n throw new Error(`invalid_argument: ${JWT_ERROR.INVALID_JWT}: ${e}`)\n }\n}\n\n/**\n * Creates a signed JWS given a payload, a signer, and an optional header.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * const jws = await createJWS({ my: 'payload' }, signer)\n *\n * @param {Object} payload payload object\n * @param {Signer} signer a signer, see `ES256KSigner or `EdDSASigner`\n * @param {Object} header optional object to specify or customize the JWS header\n * @param {Object} options can be used to trigger automatic canonicalization of header and\n * payload properties\n * @return {Promise<string>} a Promise which resolves to a JWS string or rejects with an error\n */\nexport async function createJWS(\n payload: string | Partial<JWTPayload>,\n signer: Signer,\n header: Partial<JWTHeader> = {},\n options: JWSCreationOptions = {},\n): Promise<string> {\n if (!header.alg) header.alg = defaultAlg\n const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload, options.canonicalize)\n const signingInput: string = [encodeSection(header, options.canonicalize), encodedPayload].join('.')\n\n const jwtSigner: SignerAlgorithm = SignerAlg(header.alg)\n const signature: string = await jwtSigner(signingInput, signer)\n\n // JWS Compact Serialization\n // https://www.rfc-editor.org/rfc/rfc7515#section-7.1\n return [signingInput, signature].join('.')\n}\n\n/**\n * Creates a signed JWT given an address which becomes the issuer, a signer, and a payload for which the signature is\n * over.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n * ...\n * })\n *\n * @param {Object} payload payload object\n * @param {Object} [options] an unsigned credential object\n * @param {String} options.issuer The DID of the issuer (signer) of JWT\n * @param {String} options.alg [DEPRECATED] The JWT signing algorithm to use. Supports:\n * [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n * @param {Signer} options.signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n * @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing\n * @param {Object} header optional object to specify or customize the JWT header\n * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or\n * rejects with an error\n */\nexport async function createJWT(\n payload: Partial<JWTPayload>,\n { issuer, signer, alg, expiresIn, canonicalize }: JWTOptions,\n header: Partial<JWTHeader> = {},\n): Promise<string> {\n if (!signer) throw new Error('missing_signer: No Signer functionality has been configured')\n if (!issuer) throw new Error('missing_issuer: No issuing DID has been configured')\n if (!header.typ) header.typ = 'JWT'\n if (!header.alg) header.alg = alg\n const timestamps: Partial<JWTPayload> = {\n iat: Math.floor(Date.now() / 1000),\n exp: undefined,\n }\n if (expiresIn) {\n if (typeof expiresIn === 'number') {\n timestamps.exp = <number>(payload.nbf || timestamps.iat) + Math.floor(expiresIn)\n } else {\n throw new Error('invalid_argument: JWT expiresIn is not a number')\n }\n }\n const fullPayload = { ...timestamps, ...payload, iss: issuer }\n return createJWS(fullPayload, signer, header, { canonicalize })\n}\n\n/**\n * Creates a multi-signature signed JWT given multiple issuers and their corresponding signers, and a payload for\n * which the signature is over.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n * ...\n * })\n *\n * @param {Object} payload payload object\n * @param {Object} [options] an unsigned credential object\n * @param {boolean} options.expiresIn optional flag to denote the expiration time\n * @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing\n * @param {Object[]} issuers array of the issuers, their signers and algorithms\n * @param {string} issuers[].issuer The DID of the issuer (signer) of JWT\n * @param {Signer} issuers[].signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n * @param {String} issuers[].alg [DEPRECATED] The JWT signing algorithm to use. Supports:\n * [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or\n * rejects with an error\n */\nexport async function createMultisignatureJWT(\n payload: Partial<JWTPayload>,\n { expiresIn, canonicalize }: Partial<JWTOptions>,\n issuers: { issuer: string; signer: Signer; alg: string }[],\n): Promise<string> {\n if (issuers.length === 0) throw new Error('invalid_argument: must provide one or more issuers')\n\n let payloadResult: Partial<JWTPayload> = payload\n\n let jwt = ''\n for (let i = 0; i < issuers.length; i++) {\n const issuer = issuers[i]\n\n const header: Partial<JWTHeader> = {\n typ: 'JWT',\n alg: issuer.alg,\n }\n\n // Create nested JWT\n // See Point 5 of https://www.rfc-editor.org/rfc/rfc7519#section-7.1\n // After the first JWT is created (the first JWS), the next JWT is created by inputting the previous JWT as the\n // payload\n if (i !== 0) {\n header.cty = 'JWT'\n }\n\n jwt = await createJWT(payloadResult, { ...issuer, canonicalize, expiresIn }, header)\n\n payloadResult = { jwt }\n }\n return jwt\n}\n\nexport function verifyJWTDecoded(\n { header, payload, data, signature }: JWTDecoded,\n pubKeys: VerificationMethod | VerificationMethod[],\n): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n\n const iss = payload.iss\n let recurse = true\n do {\n if (iss !== payload.iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n\n try {\n const result = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n\n return result\n } catch (e) {\n if (!(e as Error).message.startsWith(JWT_ERROR.INVALID_SIGNATURE)) throw e\n }\n\n // TODO probably best to create copy objects than replace reference objects\n if (header.cty !== 'JWT') {\n recurse = false\n } else {\n ;({ payload, header, signature, data } = decodeJWT(payload.jwt, false))\n }\n } while (recurse)\n\n throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: no matching public key found`)\n}\n\nexport function verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n return signer\n}\n\n/**\n * Verifies given JWS. If the JWS is valid, returns the public key that was\n * used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.\n *\n * @example\n * const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })\n *\n * @param {String} jws A JWS string to verify\n * @param {Array<VerificationMethod> | VerificationMethod} pubKeys The public keys used to verify the JWS\n * @return {VerificationMethod} The public key used to sign the JWS\n */\nexport function verifyJWS(jws: string, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n const jwsDecoded: JWSDecoded = decodeJWS(jws)\n return verifyJWSDecoded(jwsDecoded, pubKeys)\n}\n\n/**\n * Verifies given JWT. If the JWT is valid, the promise returns an object including the JWT, the payload of the JWT,\n * and the DID document of the issuer of the JWT.\n *\n * @example\n * ```ts\n * verifyJWT(\n * 'did:uport:eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....',\n * {audience: '5A8bRWU3F7j3REx3vkJ...', callbackUrl: 'https://...'}\n * ).then(obj => {\n * const did = obj.did // DID of signer\n * const payload = obj.payload\n * const doc = obj.didResolutionResult.didDocument // DID Document of issuer\n * const jwt = obj.jwt\n * const signerKeyId = obj.signer.id // ID of key in DID document that signed JWT\n * ...\n * })\n * ```\n *\n * @param {String} jwt a JSON Web Token to verify\n * @param {Object} [options] an unsigned credential object\n * @param {Boolean} options.auth Require signer to be listed in the authentication section of the\n * DID document (for Authentication purposes)\n * @param {String} options.audience DID of the recipient of the JWT\n * @param {String} options.callbackUrl callback url in JWT\n * @return {Promise<Object, Error>} a promise which resolves with a response object or rejects with an\n * error\n */\nexport async function verifyJWT(\n jwt: string,\n options: JWTVerifyOptions = {\n resolver: undefined,\n auth: undefined,\n audience: undefined,\n callbackUrl: undefined,\n skewTime: undefined,\n proofPurpose: undefined,\n policies: {},\n didAuthenticator: undefined,\n },\n): Promise<JWTVerified> {\n if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n const { payload, header /*, signature, data*/ }: JWTDecoded = decodeJWT(jwt, false)\n const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n ? options.auth\n ? 'authentication'\n : undefined\n : options.proofPurpose\n\n let didUrl: string | undefined\n\n if (!payload.iss && !payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n\n if (options.didAuthenticator) {\n didUrl = options.didAuthenticator.issuer\n } else if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.sub) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n didUrl = payload.sub\n } else {\n didUrl = (header.kid || '').split('#')[0]\n }\n } else if (payload.iss === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n didUrl = payload.did\n } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n didUrl = payload.client_id\n } else {\n didUrl = payload.iss\n }\n\n if (!didUrl) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n\n let authenticators: VerificationMethod[]\n let issuer: string\n let didResolutionResult: DIDResolutionResult\n if (options.didAuthenticator) {\n ;({ didResolutionResult, authenticators, issuer } = options.didAuthenticator)\n } else {\n ;({ didResolutionResult, authenticators, issuer } = await resolveAuthenticator(options.resolver, header.alg, didUrl, proofPurpose))\n // Add to options object for recursive reference\n options.didAuthenticator = { didResolutionResult, authenticators, issuer }\n }\n\n const { did } = parse(didUrl) as ParsedDID\n\n let signer: VerificationMethod | null = null\n\n if (did !== didUrl) {\n const authenticator = authenticators.find((auth) => auth.id === didUrl)\n if (!authenticator) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No authenticator found for did URL ${didUrl}`)\n }\n\n // signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n } else {\n let i = 0\n while (!signer && i < authenticators.length) {\n // const authenticator = authenticators[i]\n try {\n // signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n } catch (e) {\n if (!(e as Error).message.includes(JWT_ERROR.INVALID_SIGNATURE) || i === authenticators.length - 1) throw e\n }\n\n i++\n }\n }\n\n if (signer) {\n const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n\n const nowSkewed = now + skewTime\n if (options.policies?.nbf !== false && payload.nbf) {\n if (payload.nbf > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n }\n } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n }\n if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n }\n if (options.policies?.aud !== false && payload.aud) {\n if (!options.audience && !options.callbackUrl) {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`)\n }\n const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n const matchedAudience = audArray.find((item) => options.audience === item || options.callbackUrl === item)\n\n if (typeof matchedAudience === 'undefined') {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n }\n }\n\n return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n }\n throw new Error(\n `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`,\n )\n}\n\n/**\n * Resolves relevant public keys or other authenticating material used to verify signature from the DID document of\n * provided DID\n *\n * @example\n * ```ts\n * resolveAuthenticator(resolver, 'ES256K', 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX').then(obj => {\n * const payload = obj.payload\n * const profile = obj.profile\n * const jwt = obj.jwt\n * // ...\n * })\n * ```\n *\n * @param resolver - {Resolvable} a DID resolver function that can obtain the `DIDDocument` for the `issuer`\n * @param alg - {String} a JWT algorithm\n * @param issuer - {String} a Decentralized Identifier (DID) to lookup\n * @param proofPurpose - {ProofPurposeTypes} *Optional* Use the verificationMethod linked in that section of the\n * issuer DID document\n * @return {Promise<DIDAuthenticator>} a promise which resolves with an object containing an array of authenticators\n * or rejects with an error if none exist\n */\nexport async function resolveAuthenticator(\n resolver: Resolvable,\n alg: string,\n issuer: string,\n proofPurpose?: ProofPurposeTypes,\n): Promise<DIDAuthenticator> {\n const types: string[] = SUPPORTED_PUBLIC_KEY_TYPES[alg as KNOWN_JWA]\n if (!types || types.length === 0) {\n throw new Error(`${JWT_ERROR.NOT_SUPPORTED}: No supported signature types for algorithm ${alg}`)\n }\n let didResult: DIDResolutionResult\n\n const result = (await resolver.resolve(issuer, { accept: DID_JSON })) as unknown\n // support legacy resolvers that do not produce DIDResolutionResult\n if (Object.getOwnPropertyNames(result).indexOf('didDocument') === -1) {\n didResult = {\n didDocument: result as DIDDocument,\n didDocumentMetadata: {},\n didResolutionMetadata: { contentType: DID_JSON },\n }\n } else {\n didResult = result as DIDResolutionResult\n }\n\n if (didResult.didResolutionMetadata?.error || didResult.didDocument == null) {\n const { error, message } = didResult.didResolutionMetadata\n throw new Error(`${JWT_ERROR.RESOLVER_ERROR}: Unable to resolve DID document for ${issuer}: ${error}, ${message || ''}`)\n }\n\n const getPublicKeyById = (verificationMethods: VerificationMethod[], pubid?: string): VerificationMethod | null => {\n const filtered = verificationMethods.filter(({ id }) => pubid === id)\n return filtered.length > 0 ? filtered[0] : null\n }\n\n let publicKeysToCheck: VerificationMethod[] = [...(didResult?.didDocument?.verificationMethod || []), ...(didResult?.didDocument?.publicKey || [])]\n if (typeof proofPurpose === 'string') {\n // support legacy DID Documents that do not list assertionMethod\n if (proofPurpose.startsWith('assertion') && !Object.getOwnPropertyNames(didResult?.didDocument).includes('assertionMethod')) {\n didResult.didDocument = { ...(<DIDDocument>didResult.didDocument) }\n didResult.didDocument.assertionMethod = [...publicKeysToCheck.map((pk) => pk.id)]\n }\n\n publicKeysToCheck = (didResult.didDocument[proofPurpose] || [])\n .map((verificationMethod) => {\n if (typeof verificationMethod === 'string') {\n return getPublicKeyById(publicKeysToCheck, verificationMethod)\n } else if (typeof (<LegacyVerificationMethod>verificationMethod).publicKey === 'string') {\n // this is a legacy format\n return getPublicKeyById(publicKeysToCheck, (<LegacyVerificationMethod>verificationMethod).publicKey)\n } else {\n return <VerificationMethod>verificationMethod\n }\n })\n .filter((key) => key != null) as VerificationMethod[]\n }\n\n const authenticators: VerificationMethod[] = publicKeysToCheck.filter(({ type }) => types.find((supported) => supported === type))\n\n if (typeof proofPurpose === 'string' && (!authenticators || authenticators.length === 0)) {\n throw new Error(\n `${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys suitable for ${alg} with ${proofPurpose} purpose`,\n )\n }\n if (!authenticators || authenticators.length === 0) {\n throw new Error(`${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys for ${alg}`)\n }\n return { authenticators, issuer, didResolutionResult: didResult }\n}\n","// @ts-ignore\nimport * as u8a from 'uint8arrays'\n// const { concat, fromString, toString } = u8a\nimport { x25519 } from '@noble/curves/ed25519'\n\n// @ts-ignore\nimport { varint } from 'multiformats'\nimport { BaseName, decode, encode } from 'multibase'\nimport type { VerificationMethod } from 'did-resolver'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\n\n// const u8a = { toString, fromString, concat }\n\nexport interface EphemeralPublicKey {\n kty?: string\n //ECC\n crv?: string\n x?: string\n y?: string\n //RSA\n n?: string\n e?: string\n}\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport interface EcdsaSignature {\n r: string\n s: string\n recoveryParam?: number\n}\n\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport type ECDSASignature = {\n compact: Uint8Array\n recovery?: number\n}\n\nexport type JsonWebKey = {\n crv: string\n kty: string\n x?: string\n y?: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n}\n\nexport function bytesToBase64url(b: Uint8Array): string {\n return u8a.toString(b, 'base64url')\n}\n\nexport function base64ToBytes(s: string): Uint8Array {\n const inputBase64Url = s.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n return u8a.fromString(inputBase64Url, 'base64url')\n}\n\nexport function bytesToBase64(b: Uint8Array): string {\n return u8a.toString(b, 'base64pad')\n}\n\nexport function base58ToBytes(s: string): Uint8Array {\n return u8a.fromString(s, 'base58btc')\n}\n\nexport function bytesToBase58(b: Uint8Array): string {\n return u8a.toString(b, 'base58btc')\n}\n\nexport type KNOWN_JWA = 'ES256' | 'ES256K' | 'ES256K-R' | 'Ed25519' | 'EdDSA'\n\nexport type KNOWN_VERIFICATION_METHOD =\n | 'JsonWebKey2020'\n | 'Multikey'\n | 'Secp256k1SignatureVerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'Secp256k1VerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'EcdsaSecp256k1VerificationKey2019' // ES256K / ES256K-R\n | 'EcdsaPublicKeySecp256k1' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'EcdsaSecp256k1RecoveryMethod2020' // ES256K-R (ES256K also supported with 1 less bit of security)\n | 'EcdsaSecp256r1VerificationKey2019' // ES256 / P-256\n | 'Ed25519VerificationKey2018'\n | 'Ed25519VerificationKey2020'\n | 'ED25519SignatureVerification' // deprecated\n | 'ConditionalProof2022'\n | 'X25519KeyAgreementKey2019' // deprecated\n | 'X25519KeyAgreementKey2020'\n\nexport type KNOWN_KEY_TYPE = 'Secp256k1' | 'Ed25519' | 'X25519' | 'Bls12381G1' | 'Bls12381G2' | 'P-256'\n\nexport type PublicKeyTypes = Record<KNOWN_JWA, KNOWN_VERIFICATION_METHOD[]>\n\nexport const SUPPORTED_PUBLIC_KEY_TYPES: PublicKeyTypes = {\n ES256: ['JsonWebKey2020', 'Multikey', 'EcdsaSecp256r1VerificationKey2019'],\n ES256K: [\n 'EcdsaSecp256k1VerificationKey2019',\n /**\n * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n */\n 'EcdsaSecp256k1RecoveryMethod2020',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1VerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1SignatureVerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'EcdsaPublicKeySecp256k1',\n /**\n * TODO - support R1 key as well\n * 'ConditionalProof2022',\n */\n 'JsonWebKey2020',\n 'Multikey',\n ],\n 'ES256K-R': [\n 'EcdsaSecp256k1VerificationKey2019',\n /**\n * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n */\n 'EcdsaSecp256k1RecoveryMethod2020',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1VerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1SignatureVerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'EcdsaPublicKeySecp256k1',\n 'ConditionalProof2022',\n 'JsonWebKey2020',\n 'Multikey',\n ],\n Ed25519: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'JsonWebKey2020', 'Multikey'],\n EdDSA: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'JsonWebKey2020', 'Multikey'],\n}\n\nexport const VM_TO_KEY_TYPE: Record<KNOWN_VERIFICATION_METHOD, KNOWN_KEY_TYPE | undefined> = {\n Secp256k1SignatureVerificationKey2018: 'Secp256k1',\n Secp256k1VerificationKey2018: 'Secp256k1',\n EcdsaSecp256k1VerificationKey2019: 'Secp256k1',\n EcdsaPublicKeySecp256k1: 'Secp256k1',\n EcdsaSecp256k1RecoveryMethod2020: 'Secp256k1',\n EcdsaSecp256r1VerificationKey2019: 'P-256',\n Ed25519VerificationKey2018: 'Ed25519',\n Ed25519VerificationKey2020: 'Ed25519',\n ED25519SignatureVerification: 'Ed25519',\n X25519KeyAgreementKey2019: 'X25519',\n X25519KeyAgreementKey2020: 'X25519',\n ConditionalProof2022: undefined,\n JsonWebKey2020: undefined, // key type must be specified in the JWK\n Multikey: undefined, // key type must be extracted from the multicodec\n}\n\nexport type KNOWN_CODECS = 'ed25519-pub' | 'x25519-pub' | 'secp256k1-pub' | 'bls12_381-g1-pub' | 'bls12_381-g2-pub' | 'p256-pub'\n\n// this is from the multicodec table https://github.com/multiformats/multicodec/blob/master/table.csv\nexport const supportedCodecs: Record<KNOWN_CODECS, number> = {\n 'ed25519-pub': 0xed,\n 'x25519-pub': 0xec,\n 'secp256k1-pub': 0xe7,\n 'bls12_381-g1-pub': 0xea,\n 'bls12_381-g2-pub': 0xeb,\n 'p256-pub': 0x1200,\n}\n\nexport const CODEC_TO_KEY_TYPE: Record<KNOWN_CODECS, KNOWN_KEY_TYPE> = {\n 'bls12_381-g1-pub': 'Bls12381G1',\n 'bls12_381-g2-pub': 'Bls12381G2',\n 'ed25519-pub': 'Ed25519',\n 'p256-pub': 'P-256',\n 'secp256k1-pub': 'Secp256k1',\n 'x25519-pub': 'X25519',\n}\n\n/**\n * Extracts the raw byte representation of a public key from a VerificationMethod along with an inferred key type\n * @param pk a VerificationMethod entry from a DIDDocument\n * @return an object containing the `keyBytes` of the public key and an inferred `keyType`\n */\nexport function extractPublicKeyBytes(pk: VerificationMethod): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n if (pk.publicKeyBase58) {\n return {\n keyBytes: base58ToBytes(pk.publicKeyBase58),\n keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n }\n } else if (pk.publicKeyBase64) {\n return {\n keyBytes: base64ToBytes(pk.publicKeyBase64),\n keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n }\n } else if (pk.publicKeyHex) {\n return { keyBytes: hexToBytes(pk.publicKeyHex), keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return {\n keyBytes: secp256k1.ProjectivePoint.fromAffine({\n x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n }).toRawBytes(false),\n keyType: 'Secp256k1',\n }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return {\n keyBytes: p256.ProjectivePoint.fromAffine({\n x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n }).toRawBytes(false),\n keyType: 'P-256',\n }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === 'OKP' && ['Ed25519', 'X25519'].includes(pk.publicKeyJwk.crv ?? '') && pk.publicKeyJwk.x) {\n return { keyBytes: base64ToBytes(pk.publicKeyJwk.x), keyType: pk.publicKeyJwk.crv as KNOWN_KEY_TYPE }\n } else if (pk.publicKeyMultibase) {\n const { keyBytes, keyType } = multibaseToBytes(pk.publicKeyMultibase)\n return { keyBytes, keyType: keyType ?? VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n }\n return { keyBytes: new Uint8Array() }\n}\n\n/**\n * Encodes the given byte array to a multibase string (defaulting to base58btc).\n * If a codec is provided, the corresponding multicodec prefix will be added.\n *\n * @param b - the Uint8Array to be encoded\n * @param base - the base to use for encoding (defaults to base58btc)\n * @param codec - the codec to use for encoding (defaults to no codec)\n *\n * @returns the multibase encoded string\n *\n * @public\n */\nexport function bytesToMultibase(b: Uint8Array, base: BaseName = 'base58btc', codec?: keyof typeof supportedCodecs | number): string {\n if (!codec) {\n return u8a.toString(encode(base, b), 'utf-8')\n } else {\n const codecCode = typeof codec === 'string' ? supportedCodecs[codec] : codec\n const prefixLength = varint.encodingLength(codecCode)\n const multicodecEncoding = new Uint8Array(prefixLength + b.length)\n varint.encodeTo(codecCode, multicodecEncoding) // set prefix\n multicodecEncoding.set(b, prefixLength) // add the original bytes\n return u8a.toString(encode(base, multicodecEncoding), 'utf-8')\n }\n}\n\n/**\n * Converts a multibase string to the Uint8Array it represents.\n * This method will assume the byte array that is multibase encoded is a multicodec and will attempt to decode it.\n *\n * @param s - the string to be converted\n *\n * @throws if the string is not formatted correctly.\n *\n * @public\n */\nexport function multibaseToBytes(s: string): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n const bytes = decode(s)\n\n // look for known key lengths first\n // Ed25519/X25519, secp256k1/P256 compressed or not, BLS12-381 G1/G2 compressed\n if ([32, 33, 48, 64, 65, 96].includes(bytes.length)) {\n return { keyBytes: bytes }\n }\n\n // then assume multicodec, otherwise return the bytes\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [codec, length] = varint.decode(bytes)\n const possibleCodec: string | undefined = Object.entries(supportedCodecs).filter(([, code]) => code === codec)?.[0][0] ?? ''\n return { keyBytes: bytes.slice(length), keyType: CODEC_TO_KEY_TYPE[possibleCodec as KNOWN_CODECS] }\n } catch (e) {\n // not a multicodec, return the bytes\n return { keyBytes: bytes }\n }\n}\n\nexport function hexToBytes(s: string, minLength?: number): Uint8Array {\n let input = s.startsWith('0x') ? s.substring(2) : s\n\n if (input.length % 2 !== 0) {\n input = `0${input}`\n }\n\n if (minLength) {\n const paddedLength = Math.max(input.length, minLength * 2)\n input = input.padStart(paddedLength, '00')\n }\n\n return u8a.fromString(input.toLowerCase(), 'base16')\n}\n\nexport function encodeBase64url(s: string): string {\n return bytesToBase64url(u8a.fromString(s))\n}\n\nexport function decodeBase64url(s: string): string {\n return u8a.toString(base64ToBytes(s))\n}\n\nexport function bytesToHex(b: Uint8Array): string {\n return u8a.toString(b, 'base16')\n}\n\nexport function bytesToBigInt(b: Uint8Array): bigint {\n return BigInt(`0x` + u8a.toString(b, 'base16'))\n}\n\nexport function bigintToBytes(n: bigint, minLength?: number): Uint8Array {\n return hexToBytes(n.toString(16), minLength)\n}\n\nexport function stringToBytes(s: string): Uint8Array {\n return u8a.fromString(s, 'utf-8')\n}\n\nexport function toJose({ r, s, recoveryParam }: EcdsaSignature, recoverable?: boolean): string {\n const jose = new Uint8Array(recoverable ? 65 : 64)\n jose.set(u8a.fromString(r, 'base16'), 0)\n jose.set(u8a.fromString(s, 'base16'), 32)\n if (recoverable) {\n if (typeof recoveryParam === 'undefined') {\n throw new Error('Signer did not return a recoveryParam')\n }\n jose[64] = <number>recoveryParam\n }\n return bytesToBase64url(jose)\n}\n\nexport function fromJose(signature: string): { r: string; s: string; recoveryParam?: number } {\n const signatureBytes: Uint8Array = base64ToBytes(signature)\n if (signatureBytes.length < 64 || signatureBytes.length > 65) {\n throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`)\n }\n const r = bytesToHex(signatureBytes.slice(0, 32))\n const s = bytesToHex(signatureBytes.slice(32, 64))\n const recoveryParam = signatureBytes.length === 65 ? signatureBytes[64] : undefined\n return { r, s, recoveryParam }\n}\n\nexport function toSealed(ciphertext: string, tag?: string): Uint8Array {\n return u8a.concat([base64ToBytes(ciphertext), tag ? base64ToBytes(tag) : new Uint8Array(0)])\n}\n\nexport function leftpad(data: string, size = 64): string {\n if (data.length === size) return data\n return '0'.repeat(size - data.length) + data\n}\n\n/**\n * Generate random x25519 key pair.\n */\nexport function generateKeyPair(): { secretKey: Uint8Array; publicKey: Uint8Array } {\n const secretKey = x25519.utils.randomPrivateKey()\n const publicKey = x25519.getPublicKey(secretKey)\n return {\n secretKey: secretKey,\n publicKey: publicKey,\n }\n}\n\n/**\n * Generate private-public x25519 key pair from `seed`.\n */\nexport function generateKeyPairFromSeed(seed: Uint8Array): { secretKey: Uint8Array; publicKey: Uint8Array } {\n if (seed.length !== 32) {\n throw new Error(`x25519: seed must be ${32} bytes`)\n }\n return {\n publicKey: x25519.getPublicKey(seed),\n secretKey: seed,\n }\n}\n/*\n\nexport function genX25519EphemeralKeyPair(): EphemeralKeyPair {\n const epk = generateKeyPair()\n return {\n publicKeyJWK: { kty: 'OKP', crv: 'X25519', x: bytesToBase64url(epk.publicKey) },\n secretKey: epk.secretKey,\n }\n}\n*/\n\n/**\n * Checks if a variable is defined and not null.\n * After this check, typescript sees the variable as defined.\n *\n * @param arg - The input to be verified\n *\n * @returns true if the input variable is defined.\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n return arg !== null && typeof arg !== 'undefined'\n}\n","import type { Signer, SignerAlgorithm } from './JWT'\nimport { type EcdsaSignature, fromJose, toJose } from './util'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction instanceOfEcdsaSignature(object: any): object is EcdsaSignature {\n return typeof object === 'object' && 'r' in object && 's' in object\n}\n\nexport function ES256SignerAlg(): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (instanceOfEcdsaSignature(signature)) {\n return toJose(signature)\n } else {\n return signature\n }\n }\n}\n\nexport function ES256KSignerAlg(recoverable?: boolean): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (instanceOfEcdsaSignature(signature)) {\n return toJose(signature, recoverable)\n } else {\n if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') {\n throw new Error(`not_supported: ES256K-R not supported when signer doesn't provide a recovery param`)\n }\n return signature\n }\n }\n}\n\nexport function Ed25519SignerAlg(): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (!instanceOfEcdsaSignature(signature)) {\n return signature\n } else {\n throw new Error('invalid_config: expected a signer function that returns a string instead of signature object')\n }\n }\n}\n\ninterface SignerAlgorithms {\n [alg: string]: SignerAlgorithm\n}\n\nconst algorithms: SignerAlgorithms = {\n ES256: ES256SignerAlg(),\n ES256K: ES256KSignerAlg(),\n // This is a non-standard algorithm but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/146\n 'ES256K-R': ES256KSignerAlg(true),\n // This is actually incorrect but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/130\n Ed25519: Ed25519SignerAlg(),\n EdDSA: Ed25519SignerAlg(),\n}\n\nfunction SignerAlg(alg: string): SignerAlgorithm {\n const impl: SignerAlgorithm = algorithms[alg]\n if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n return impl\n}\n\nexport default SignerAlg\n","import { toEthereumAddress } from 'did-jwt'\nimport type { VerificationMethod } from 'did-resolver'\nimport { base64ToBytes, bytesToHex, type EcdsaSignature, type ECDSASignature, extractPublicKeyBytes, type KNOWN_JWA, stringToBytes } from './util'\n// @ts-ignore\n// import { verifyBlockchainAccountId } from 'did-jwt'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\nimport { ed25519 } from '@noble/curves/ed25519'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nimport { sha256 as hash } from '@noble/hashes/sha256'\n\nexport function sha256(payload: string | Uint8Array): Uint8Array {\n const data = typeof payload === 'string' ? u8a.fromString(payload) : payload\n return hash(data)\n}\n// converts a JOSE signature to it's components\nexport function toSignatureObject(signature: string, recoverable = false): EcdsaSignature {\n const rawSig: Uint8Array = base64ToBytes(signature)\n if (rawSig.length !== (recoverable ? 65 : 64)) {\n throw new Error('wrong signature length')\n }\n const r: string = bytesToHex(rawSig.slice(0, 32))\n const s: string = bytesToHex(rawSig.slice(32, 64))\n const sigObj: EcdsaSignature = { r, s }\n if (recoverable) {\n sigObj.recoveryParam = rawSig[64]\n }\n return sigObj\n}\n\nexport function toSignatureObject2(signature: string, recoverable = false): ECDSASignature {\n const bytes = base64ToBytes(signature)\n if (bytes.length !== (recoverable ? 65 : 64)) {\n throw new Error('wrong signature length')\n }\n return {\n compact: bytes.slice(0, 64),\n recovery: bytes[64],\n }\n}\n\nexport function verifyES256(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const hash = sha256(data)\n const sig = p256.Signature.fromCompact(toSignatureObject2(signature).compact)\n const fullPublicKeys = authenticators.filter((a: VerificationMethod) => !a.ethereumAddress && !a.blockchainAccountId)\n\n const signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n try {\n const { keyBytes } = extractPublicKeyBytes(pk)\n return p256.verify(sig, hash, keyBytes)\n } catch (err) {\n return false\n }\n })\n\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\nexport function verifyES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const hash = sha256(data)\n const signatureNormalized = secp256k1.Signature.fromCompact(base64ToBytes(signature)).normalizeS()\n const fullPublicKeys = authenticators.filter((a: VerificationMethod) => {\n return !a.ethereumAddress && !a.blockchainAccountId\n })\n const blockchainAddressKeys = authenticators.filter((a: VerificationMethod) => {\n return a.ethereumAddress || a.blockchainAccountId\n })\n\n let signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n try {\n const { keyBytes } = extractPublicKeyBytes(pk)\n return secp256k1.verify(signatureNormalized, hash, keyBytes)\n } catch (err) {\n return false\n }\n })\n\n if (!signer && blockchainAddressKeys.length > 0) {\n signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys)\n }\n\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\nexport function verifyRecoverableES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const signatures: ECDSASignature[] = []\n if (signature.length > 86) {\n signatures.push(toSignatureObject2(signature, true))\n } else {\n const so = toSignatureObject2(signature, false)\n signatures.push({ ...so, recovery: 0 })\n signatures.push({ ...so, recovery: 1 })\n }\n const hash = sha256(data)\n\n const checkSignatureAgainstSigner = (sigObj: ECDSASignature): VerificationMethod | undefined => {\n const signature = secp256k1.Signature.fromCompact(sigObj.compact).addRecoveryBit(sigObj.recovery || 0)\n const recoveredPublicKey = signature.recoverPublicKey(hash)\n const recoveredAddress = toEthereumAddress(recoveredPublicKey.toHex(false)).toLowerCase()\n const recoveredPublicKeyHex = recoveredPublicKey.toHex(false)\n const recoveredCompressedPublicKeyHex = recoveredPublicKey.toHex(true)\n\n return authenticators.find((a: VerificationMethod) => {\n const { keyBytes } = extractPublicKeyBytes(a)\n const keyHex = bytesToHex(keyBytes)\n return (\n keyHex === recoveredPublicKeyHex ||\n keyHex === recoveredCompressedPublicKeyHex ||\n a.ethereumAddress?.toLowerCase() === recoveredAddress ||\n a.blockchainAccountId?.split('@eip155')?.[0].toLowerCase() === recoveredAddress //|| // CAIP-2\n // verifyBlockchainAccountId(recoveredPublicKeyHex, a.blockchainAccountId) // CAIP-10\n )\n })\n }\n\n // Find first verification method\n for (const signature of signatures) {\n const verificationMethod = checkSignatureAgainstSigner(signature)\n if (verificationMethod) return verificationMethod\n }\n // If no one found matching\n throw new Error('invalid_signature: Signature invalid for JWT')\n}\n\nexport function verifyEd25519(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const clear = stringToBytes(data)\n const signatureBytes = base64ToBytes(signature)\n const signer = authenticators.find((a: VerificationMethod) => {\n const { keyBytes, keyType } = extractPublicKeyBytes(a)\n if (keyType === 'Ed25519') {\n return ed25519.verify(signatureBytes, clear, keyBytes)\n } else {\n return false\n }\n })\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\ntype Verifier = (data: string, signature: string, authenticators: VerificationMethod[]) => VerificationMethod\n\ntype Algorithms = Record<KNOWN_JWA, Verifier>\n\nconst algorithms: Algorithms = {\n ES256: verifyES256,\n ES256K: verifyES256K,\n // This is a non-standard algorithm but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/146\n 'ES256K-R': verifyRecoverableES256K,\n // This is actually incorrect but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/130\n Ed25519: verifyEd25519,\n EdDSA: verifyEd25519,\n}\n\nfunction VerifierAlgorithm(alg: string): Verifier {\n const impl: Verifier = algorithms[alg as KNOWN_JWA]\n if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n return impl\n}\n\nVerifierAlgorithm.toSignatureObject = toSignatureObject\n\nexport default VerifierAlgorithm\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;ACAA,yBAKO;AAEP,IAAAA,sBAA0C;AAC1C,qBAAiC;AACjC,IAAAC,kBAA+F;AAC/F,IAAAA,kBAaO;AACP,uBAA2G;AAa3G,mBAAkB;AAElB,IAAAC,kBAAqC;AAGrC,wBAAwG;;;AC1CxG,0BAA6B;AAC7B,0BAA4H;;;ACA5H,UAAqB;AAErB,qBAAuB;AAGvB,0BAAuB;AACvB,uBAAyC;AAEzC,uBAA0B;AAC1B,kBAAqB;AAwCd,SAASC,iBAAiBC,GAAa;AAC5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AK;QAC5D;;MAEFnD;MACAuI,qBAAqBxG;MACrBjC;IACF;EACF;AAEA,QAAMgD,MAAM;IACV;MACEpB,IAAI;MACJqB,OAAO;IACT;IACA;MACErB,IAAI;MACJqB,OAAO;IACT;IACA;MACErB,IAAI;MACJqB,OAAO;IACT;IACA;MACErB,IAAI;MACJqB,OAAO;IACT;;AAEF,SAAO;IACLL,UAAU;IACVI;IACAD,SAAS;MACP;QACEH,UAAU;QACVjC;QACAqC;MACF;;IAEF9C;IACAuI,qBAAqBxG;IACrBjC;EACF;AACF;AA7IsB+D;AAyRtB,SAASrD,cACPH,SAA4D;AAI5D,MAAI,KAACU,iCAA8BV,SAAS,eAAA,GAAkB;AAC5D,UAAMS,MACJ,uKAAA;EAEJ,WAAW,KAACC,iCAAwCV,SAAS,sBAAA,GAAyB;AACpF,UAAMS,MACJ,kLAAA;EAEJ;AACA,SAAOT;AAGT;AAjBSG;","names":["import_ssi_sdk_ext","import_ssi_sdk","import_did_jwt","bytesToBase64url","b","toString","base64ToBytes","s","inputBase64Url","replace","fromString","base58ToBytes","s","fromString","VM_TO_KEY_TYPE","Secp256k1SignatureVerificationKey2018","Secp256k1VerificationKey2018","EcdsaSecp256k1VerificationKey2019","EcdsaPublicKeySecp256k1","EcdsaSecp256k1RecoveryMethod2020","EcdsaSecp256r1VerificationKey2019","Ed25519VerificationKey2018","Ed25519VerificationKey2020","ED25519SignatureVerification","X25519KeyAgreementKey2019","X25519KeyAgreementKey2020","ConditionalProof2022","undefined","JsonWebKey2020","Multikey","supportedCodecs","CODEC_TO_KEY_TYPE","extractPublicKeyBytes","pk","publicKeyBase58","keyBytes","base58ToBytes","keyType","type","publicKeyBase64","base64ToBytes","publicKeyHex","hexToBytes","publicKeyJwk","crv","x","y","secp256k1","ProjectivePoint","fromAffine","bytesToBigInt","toRawBytes","p256","kty","includes","publicKeyMultibase","multibaseToBytes","Uint8Array","multibaseToBytes","s","bytes","decode","includes","length","keyBytes","codec","varint","possibleCodec","Object","entries","supportedCodecs","filter","code","slice","keyType","CODEC_TO_KEY_TYPE","e","hexToBytes","minLength","input","startsWith","substring","paddedLength","Math","max","padStart","fromString","toLowerCase","bytesToHex","b","toString","bytesToBigInt","BigInt","stringToBytes","s","fromString","toJose","r","recoveryParam","recoverable","jose","Uint8Array","set","Error","bytesToBase64url","fromJose","signature","signatureBytes","base64ToBytes","length","TypeError","bytesToHex","slice","undefined","instanceOfEcdsaSignature","object","ES256SignerAlg","sign","payload","signer","signature","toJose","ES256KSignerAlg","recoverable","fromJose","recoveryParam","Error","Ed25519SignerAlg","algorithms","ES256","ES256K","Ed25519","EdDSA","import_secp256k1","import_p256","import_ed25519","u8a","sha256","payload","data","fromString","hash","toSignatureObject","signature","recoverable","rawSig","base64ToBytes","length","Error","r","bytesToHex","slice","s","sigObj","recoveryParam","toSignatureObject2","bytes","compact","recovery","verifyES256","authenticators","sig","p256","Signature","fromCompact","fullPublicKeys","filter","a","ethereumAddress","blockchainAccountId","signer","find","pk","keyBytes","extractPublicKeyBytes","verify","err","verifyES256K","signatureNormalized","secp256k1","normalizeS","blockchainAddressKeys","verifyRecoverableES256K","signatures","push","so","checkSignatureAgainstSigner","addRecoveryBit","recoveredPublicKey","recoverPublicKey","recoveredAddress","toEthereumAddress","toHex","toLowerCase","recoveredPublicKeyHex","recoveredCompressedPublicKeyHex","keyHex","split","verificationMethod","verifyEd25519","clear","stringToBytes","signatureBytes","keyType","ed25519","algorithms","ES256","ES256K","Ed25519","EdDSA","VerifierAlgorithm","alg","impl","import_did_jwt","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","SELF_ISSUED_V0_1","import_ssi_sdk","debug","Debug","CredentialProviderVcdm2SdJwt","matchKeyForType","key","matchKeyForJWT","getTypeProofFormat","canIssueCredentialType","args","format","proofFormat","toLowerCase","canVerifyDocumentType","document","jwt","proof","payload","decodeJWT","split","isVcdm2Credential","createVerifiableCredential","context","keyRef","agent","assertContext","credential","issuer","preProcessCredentialPayload","Promise","reject","Error","contextHasPlugin","identifier","didManagerGet","did","e","managedIdentifier","identifierManagedGetByDid","kmsKeyRef","pickSigningKey","alg","signatureAlgorithmFromKey","id","result","createSdJwtVc","type","credentialPayload","resolution","disclosureFrame","opts","normalized","normalizeCredential","verifyCredential","policies","uniform","CredentialMapper","toUniformCredential","verificationResult","verified","asArray","verifySdJwtVc","results","log","valid","error","message","errorCode","name","nbf","issuanceDate","validFrom","iat","exp","expirationDate","validUntil","aud","audience","verifierSignature","createVerifiablePresentation","presentation","holder","preProcessPresentation","domain","challenge","header","kid","meta","verificationMethod","typ","cty","nonce","jwtCreateJwsCompactSignature","mode","protectedHeader","clientIdScheme","normalizePresentation","verifyPresentation","fetchRemoteContexts","otherOptions","resolver","resolve","didUrl","resolveDid","options","resolutionOptions","intendedAudience","managedDids","didManagerFind","filtered","filter","includes","length","verifyPresentationJWT","verifiablePresentation","intersect","algorithms","wrapSigner","algorithm","data","keyManagerSign","verifierContext","credIssuer","undefined","JWT_ERROR","INVALID_JWT","getIssuerFromSdJwt","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","credentialSubject","sub_jwk","sub","SELF_ISSUED_V0_1","scope","redirect_uri","client_id","indexOf","identifierExternalResolve","validFromError","Date","parse","getTime","expired","didOpts","method","jwtResult","jwtVerifyJwsSignature","jws","jwk","jwks","isDidIdentifier","errorMessage","didResolutionResult"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/agent/CredentialProviderVcdm2SdJwt.ts","../src/did-jwt/JWT.ts","../src/did-jwt/util.ts","../src/did-jwt/SignerAlgorithm.ts","../src/did-jwt/VerifierAlgorithm.ts"],"sourcesContent":["export { CredentialProviderVcdm2SdJwt } from './agent/CredentialProviderVcdm2SdJwt'\n","import {\n type ExternalIdentifierDidOpts,\n ExternalIdentifierResult,\n type IIdentifierResolution,\n isDidIdentifier,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport type { IJwtService, JwsHeader, JwsPayload } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { signatureAlgorithmFromKey } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { contextHasPlugin } from '@sphereon/ssi-sdk.agent-config'\nimport { asArray, intersect, type VerifiableCredentialSP, type VerifiablePresentationSP } from '@sphereon/ssi-sdk.core'\nimport {\n type ICanIssueCredentialTypeArgs,\n type ICanVerifyDocumentTypeArgs,\n type ICreateVerifiableCredentialLDArgs,\n type ICreateVerifiablePresentationLDArgs,\n type IVcdmCredentialProvider,\n type IVcdmIssuerAgentContext,\n IVcdmVerifierAgentContext,\n IVerifyCredentialVcdmArgs,\n IVerifyPresentationLDArgs,\n pickSigningKey,\n preProcessCredentialPayload,\n preProcessPresentation,\n} from '@sphereon/ssi-sdk.credential-vcdm'\nimport { CredentialMapper, isVcdm2Credential, type IVerifyResult, type OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport type {\n IAgentContext,\n IDIDManager,\n IIdentifier,\n IKey,\n IKeyManager,\n IResolver,\n VerifiableCredential,\n VerificationPolicies,\n VerifierAgentContext,\n} from '@veramo/core'\n\nimport Debug from 'debug'\n\nimport { decodeJWT, JWT_ERROR } from 'did-jwt'\n\n// @ts-ignore\nimport { normalizeCredential, normalizePresentation, verifyPresentation as verifyPresentationJWT } from 'did-jwt-vc'\n\nimport { type Resolvable } from 'did-resolver'\n\nimport { SELF_ISSUED_V0_1, SELF_ISSUED_V2, SELF_ISSUED_V2_VC_INTEROP } from '../did-jwt/JWT'\nimport { getIssuerFromSdJwt, ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\n// import {validateCredentialPayload} from \"did-jwt-vc/src\";\n\nconst debug = Debug('sphereon:ssi-sdk:credential-vcdm2-sdjwt')\n\n/**\n * A handler that implements the {@link IVcdmCredentialProvider} methods.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport class CredentialProviderVcdm2SdJwt implements IVcdmCredentialProvider {\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.matchKeyForType} */\n matchKeyForType(key: IKey): boolean {\n return this.matchKeyForJWT(key)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.getTypeProofFormat} */\n getTypeProofFormat(): string {\n return 'vc+sd-jwt'\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canIssueCredentialType} */\n canIssueCredentialType(args: ICanIssueCredentialTypeArgs): boolean {\n const format = args.proofFormat.toLowerCase()\n // TODO: Create type\n return format === 'vc+sd-jwt' || format === 'vcdm2_sdjwt'\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canVerifyDocumentType */\n canVerifyDocumentType(args: ICanVerifyDocumentTypeArgs): boolean {\n const { document } = args\n const jwt = typeof document === 'string' ? document : (<VerifiableCredential>document)?.proof?.jwt\n if (!jwt) {\n return false\n }\n const { payload } = decodeJWT(jwt.split('~')[0])\n return isVcdm2Credential(payload)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiableCredential} */\n async createVerifiableCredential(args: ICreateVerifiableCredentialLDArgs, context: IVcdmIssuerAgentContext): Promise<VerifiableCredentialSP> {\n const { keyRef } = args\n const agent = assertContext(context).agent\n const { credential, issuer } = preProcessCredentialPayload(args)\n if (!isVcdm2Credential(credential)) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential. Context: ' + credential['@context']))\n } else if (!contextHasPlugin<ISDJwtPlugin>(context, 'createSdJwtVc')) {\n return Promise.reject(\n new Error('invalid_argument: SD-JWT plugin not available. Please install @sphereon/ssi-sdk.sd-jwt and configure agent for VCDM2 SD-JWT'),\n )\n }\n let identifier: IIdentifier\n try {\n identifier = await agent.didManagerGet({ did: issuer })\n } catch (e) {\n return Promise.reject(new Error(`invalid_argument: ${credential.issuer} must be a DID managed by this agent. ${e}`))\n }\n const managedIdentifier = await agent.identifierManagedGetByDid({ identifier: identifier.did, kmsKeyRef: keyRef })\n const key = await pickSigningKey({ identifier, kmsKeyRef: keyRef }, context)\n\n // TODO: Probably wise to give control to caller as well, as some key types allow multiple signature algos\n const alg = (await signatureAlgorithmFromKey({ key })) as string\n debug('Signing VC with', identifier.did, alg)\n credential.issuer = { id: identifier.did }\n\n const result = await context.agent.createSdJwtVc({\n type: 'vc+sd-jwt',\n credentialPayload: credential,\n resolution: managedIdentifier,\n disclosureFrame: args.opts?.disclosureFrame,\n })\n\n const jwt = result.credential.split('~')[0]\n\n // debug(jwt)\n const normalized = normalizeCredential(jwt)\n normalized.proof.jwt = result.credential\n return normalized\n }\n\n /** {@inheritdoc ICredentialVerifier.verifyCredential} */\n async verifyCredential(args: IVerifyCredentialVcdmArgs, context: VerifierAgentContext): Promise<IVerifyResult> {\n let { credential, policies /*...otherOptions*/ } = args\n const uniform = CredentialMapper.toUniformCredential(credential as OriginalVerifiableCredential)\n // let verifiedCredential: VerifiableCredential\n if (!isVcdm2Credential(uniform)) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential. Context: ' + uniform['@context']))\n } else if (!contextHasPlugin<ISDJwtPlugin>(context, 'createSdJwtVc')) {\n return Promise.reject(\n new Error('invalid_argument: SD-JWT plugin not available. Please install @sphereon/ssi-sdk.sd-jwt and configure agent for VCDM2 SD-JWT'),\n )\n }\n let verificationResult: IVerifyResult = { verified: false }\n let jwt: string | undefined = typeof credential === 'string' ? credential : asArray(uniform.proof)?.[0]?.jwt\n if (!jwt) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential in JOSE format (string)'))\n }\n\n try {\n const result = await context.agent.verifySdJwtVc({ credential: jwt })\n if (result.payload) {\n verificationResult = {\n verified: true,\n results: [\n {\n credential: credential as OriginalVerifiableCredential,\n verified: true,\n log: [\n {\n id: 'valid_signature',\n valid: true,\n },\n {\n id: 'issuer_did_resolves',\n valid: true,\n },\n ],\n },\n ],\n }\n }\n } catch (e) {\n verificationResult = { verified: false, error: { message: e.message, errorCode: e.name } }\n }\n\n policies = {\n ...policies,\n nbf: policies?.nbf ?? policies?.issuanceDate ?? policies?.validFrom,\n iat: policies?.iat ?? policies?.issuanceDate ?? policies?.validFrom,\n exp: policies?.exp ?? policies?.expirationDate ?? policies?.validUntil,\n aud: policies?.aud ?? policies?.audience,\n }\n verificationResult = await verifierSignature({ jwt: jwt.split('~')[0], policies }, context)\n return verificationResult\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiablePresentation} */\n async createVerifiablePresentation(args: ICreateVerifiablePresentationLDArgs, context: IVcdmIssuerAgentContext): Promise<VerifiablePresentationSP> {\n const { presentation, holder } = preProcessPresentation(args)\n let { domain, challenge, keyRef /* removeOriginalFields, keyRef, now, ...otherOptions*/ } = args\n\n const agent = assertContext(context).agent\n\n const managedIdentifier = await agent.identifierManagedGetByDid({ identifier: holder, kmsKeyRef: keyRef })\n const identifier = managedIdentifier.identifier\n const key = await pickSigningKey(\n {\n identifier: managedIdentifier.identifier,\n kmsKeyRef: managedIdentifier.kmsKeyRef,\n },\n context,\n )\n\n debug('Signing VC with', identifier.did)\n let alg = 'ES256'\n if (key.type === 'Ed25519') {\n alg = 'EdDSA'\n } else if (key.type === 'Secp256k1') {\n alg = 'ES256K'\n }\n\n const header: JwsHeader = {\n kid: key.meta.verificationMethod.id ?? key.kid,\n alg,\n typ: 'vp+jwt',\n cty: 'vp',\n }\n const payload: JwsPayload = {\n ...presentation,\n ...(domain && { aud: domain }),\n ...(challenge && { nonce: challenge }),\n }\n\n const jwt = await agent.jwtCreateJwsCompactSignature({\n mode: 'did',\n issuer: managedIdentifier,\n payload,\n protectedHeader: header,\n clientIdScheme: 'did',\n })\n\n debug(jwt)\n return normalizePresentation(jwt.jwt)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.verifyPresentation} */\n async verifyPresentation(args: IVerifyPresentationLDArgs, context: VerifierAgentContext): Promise<IVerifyResult> {\n let { presentation, domain, challenge, fetchRemoteContexts, policies, ...otherOptions } = args\n let jwt: string\n if (typeof presentation === 'string') {\n jwt = presentation\n } else {\n jwt = asArray(presentation.proof)[0].jwt\n }\n const resolver = {\n resolve: (didUrl: string) =>\n context.agent.resolveDid({\n didUrl,\n options: otherOptions?.resolutionOptions,\n }),\n } as Resolvable\n\n let audience = domain\n if (!audience) {\n const { payload } = await decodeJWT(jwt)\n if (payload.aud) {\n // automatically add a managed DID as audience if one is found\n const intendedAudience = asArray(payload.aud)\n const managedDids = await context.agent.didManagerFind()\n const filtered = managedDids.filter((identifier) => intendedAudience.includes(identifier.did))\n if (filtered.length > 0) {\n audience = filtered[0].did\n }\n }\n }\n\n let message, errorCode\n try {\n const result = await verifyPresentationJWT(jwt, resolver, {\n challenge,\n domain,\n audience,\n policies: {\n ...policies,\n nbf: policies?.nbf ?? policies?.issuanceDate,\n iat: policies?.iat ?? policies?.issuanceDate,\n exp: policies?.exp ?? policies?.expirationDate,\n aud: policies?.aud ?? policies?.audience,\n },\n ...otherOptions,\n })\n if (result) {\n /**\n * {id: 'valid_signature', valid: true},\n * // {id: 'issuer_did_resolves', valid: true},\n * // {id: 'expiration', valid: true},\n * // {id: 'revocation_status', valid: true},\n * // {id: 'suspension_status', valid: true}\n */\n return {\n verified: true,\n results: [\n {\n verified: true,\n presentation: result.verifiablePresentation,\n log: [\n {\n id: 'valid_signature',\n valid: true,\n },\n ],\n },\n ],\n } satisfies IVerifyResult\n }\n } catch (e: any) {\n message = e.message\n errorCode = e.errorCode\n }\n return {\n verified: false,\n error: {\n message,\n errorCode: errorCode ? errorCode : message?.split(':')[0],\n },\n }\n }\n\n /**\n * Checks if a key is suitable for signing JWT payloads.\n * @param key - the key to check\n * @param context - the Veramo agent context, unused here\n *\n * @beta\n */\n matchKeyForJWT(key: IKey): boolean {\n switch (key.type) {\n case 'Ed25519':\n case 'Secp256r1':\n return true\n case 'Secp256k1':\n return intersect(key.meta?.algorithms ?? [], ['ES256K', 'ES256K-R']).length > 0\n default:\n return false\n }\n }\n\n wrapSigner(context: IAgentContext<Pick<IKeyManager, 'keyManagerSign'>>, key: IKey, algorithm?: string) {\n return async (data: string | Uint8Array): Promise<string> => {\n const result = await context.agent.keyManagerSign({ keyRef: key.kid, data: <string>data, algorithm })\n return result\n }\n }\n}\n\nexport async function verifierSignature(\n { jwt, policies }: { jwt: string; policies: VerificationPolicies /*resolver: Resolvable*/ },\n verifierContext: VerifierAgentContext,\n): Promise<IVerifyResult> {\n let credIssuer: string | undefined = undefined\n const context = assertContext(verifierContext)\n const agent = context.agent\n const { payload, header /*signature, data*/ } = decodeJWT(jwt)\n\n if (!payload.issuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n const issuer = getIssuerFromSdJwt(payload)\n if (issuer === SELF_ISSUED_V2 || issuer === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.credentialSubject.id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT credentialSubject.id is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n credIssuer = payload.sub\n } else {\n credIssuer = (header.kid || '').split('#')[0]\n }\n } else if (issuer === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n credIssuer = payload.did\n } else if (!issuer && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n credIssuer = payload.client_id\n } else if (issuer?.indexOf('did:') === 0) {\n credIssuer = issuer\n } else if (header.kid?.indexOf('did:') === 0) {\n // OID4VCI expects iss to be the client and kid, to be the DID VM\n credIssuer = (header.kid || '').split('#')[0]\n } else if (typeof payload.issuer === 'string') {\n credIssuer = payload.issuer\n } else if (payload.issuer?.id) {\n credIssuer = payload.issuer.id\n }\n\n if (!credIssuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n let resolution: ExternalIdentifierResult | undefined = undefined\n try {\n resolution = await agent.identifierExternalResolve({ identifier: credIssuer })\n } catch (e: any) {}\n const credential = CredentialMapper.toUniformCredential(jwt)\n\n const validFromError =\n policies.nbf !== false &&\n policies.iat !== false &&\n 'validFrom' in credential &&\n !!credential.validFrom &&\n Date.parse(credential.validFrom) > new Date().getTime()\n const expired =\n policies.exp !== false && 'validUntil' in credential && !!credential.validUntil && Date.parse(credential.validUntil) < new Date().getTime()\n\n const didOpts = { method: 'did', identifier: credIssuer } satisfies ExternalIdentifierDidOpts\n const jwtResult = await agent.jwtVerifyJwsSignature({\n jws: jwt,\n // @ts-ignore\n jwk: resolution?.jwks[0].jwk,\n opts: { ...(isDidIdentifier(credIssuer) && { did: didOpts }) },\n })\n const error = jwtResult.error || expired || !resolution\n const errorMessage = expired\n ? 'Credential is expired'\n : validFromError\n ? 'Credential is not valid yet'\n : !resolution\n ? `Issuer ${credIssuer} could not be resolved`\n : jwtResult.message\n\n if (error) {\n const log = [\n {\n id: 'valid_signature',\n valid: !jwtResult.error,\n },\n { id: 'issuer_did_resolves', valid: resolution != undefined },\n { id: 'validFrom', valid: policies.nbf !== false && !validFromError },\n { id: 'expiration', valid: policies.exp !== false && !expired },\n ]\n return {\n verified: false,\n error: { message: errorMessage, errorCode: jwtResult.name },\n log,\n results: [\n {\n verified: false,\n credential: jwt,\n log,\n error: { message: errorMessage, errorCode: jwtResult.name },\n },\n ],\n payload,\n didResolutionResult: resolution,\n jwt,\n } satisfies IVerifyResult\n }\n\n const log = [\n {\n id: 'valid_signature',\n valid: true,\n },\n {\n id: 'issuer_did_resolves',\n valid: true,\n },\n {\n id: 'validFrom',\n valid: true,\n },\n {\n id: 'expiration',\n valid: true,\n },\n ]\n return {\n verified: true,\n log,\n results: [\n {\n verified: true,\n credential,\n log,\n },\n ],\n payload,\n didResolutionResult: resolution,\n jwt,\n } satisfies IVerifyResult\n}\n\n/*\nexport async function verifyDIDJWT(\n jwt: string,\n options: JWTVerifyOptions = {\n resolver: undefined,\n auth: undefined,\n audience: undefined,\n callbackUrl: undefined,\n skewTime: undefined,\n proofPurpose: undefined,\n policies: {},\n },\n verifierContext: VerifierAgentContext,\n): Promise<JWTVerified> {\n const context = assertContext(verifierContext)\n const agent = context.agent\n if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n const { payload, header, signature, data }: JWTDecoded = decodeJWT(jwt)\n const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n ? options.auth\n ? 'authentication'\n : undefined\n : options.proofPurpose\n\n let credIssuer: string | undefined = undefined\n\n if (!payload.iss && !payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n\n if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.sub) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n credIssuer = payload.sub\n } else {\n credIssuer = (header.kid || '').split('#')[0]\n }\n } else if (payload.iss === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n credIssuer = payload.did\n } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n credIssuer = payload.client_id\n } else if (payload.iss?.indexOf('did:') === 0) {\n credIssuer = payload.iss\n } else if (header.kid?.indexOf('did:') === 0) {\n // OID4VCI expects iss to be the client and kid, to be the DID VM\n credIssuer = (header.kid || '').split('#')[0]\n } else if (payload.iss) {\n credIssuer = payload.iss\n }\n\n if (!credIssuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n\n const resolution = await agent.identifierExternalResolve({ identifier: credIssuer })\n\n const didOpts = { method: 'did', identifier: credIssuer } satisfies ExternalIdentifierDidOpts\n const jwtResult = await agent.jwtVerifyJwsSignature({\n jws: jwt,\n // @ts-ignore\n jwk: resolution.jwks[0],\n opts: { ...(isDidIdentifier(credIssuer) && { did: didOpts }) },\n })\n\n if (jwtResult.error) {\n return Promise.reject(Error(`Error validating credential: ${jwtResult.error}`))\n }\n const { didResolutionResult, authenticators, issuer }: DIDAuthenticator = await resolveAuthenticator(\n options.resolver,\n header.alg,\n credIssuer,\n proofPurpose,\n )\n const signer: VerificationMethod = verifyJWSDecoded({ header, data, signature } as JWSDecoded, authenticators)\n const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n if (signer) {\n const nowSkewed = now + skewTime\n if (options.policies?.nbf !== false && payload.nbf) {\n if (payload.nbf > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n }\n } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n }\n if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n }\n if (options.policies?.aud !== false && payload.aud) {\n if (!options.audience && !options.callbackUrl) {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`)\n }\n const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n const matchedAudience = audArray.find((item: any) => options.audience === item || options.callbackUrl === item)\n\n if (typeof matchedAudience === 'undefined') {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n }\n }\n return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n }\n throw new Error(\n `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`,\n )\n}\n\nfunction verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n return signer\n}\n\n\nexport function validateCredentialPayload(payload: CredentialPayload): void {\n validateContext(asArray(payload['@context']))\n validateVcType(payload.type)\n validateCredentialSubject(payload.credentialSubject)\n if (payload.validFrom) validateTimestamp(payload.validFrom)\n if (payload.validUntil) validateTimestamp(payload.validUntil)\n}\n\nexport function validateContext(value: string | string[]): void {\n const input = asArray(value)\n if (input.length < 1 || input.indexOf(VCDM_CREDENTIAL_CONTEXT_V2) === -1) {\n throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: @context is missing default context \"${VCDM_CREDENTIAL_CONTEXT_V2}\"`)\n }\n}\n*/\nfunction assertContext(\n context: IVcdmIssuerAgentContext | IVcdmVerifierAgentContext,\n): IAgentContext<\n IResolver & IDIDManager & Pick<IKeyManager, 'keyManagerGet' | 'keyManagerSign' | 'keyManagerVerify'> & IJwtService & IIdentifierResolution\n> {\n if (!contextHasPlugin<IJwtService>(context, 'jwtPrepareJws')) {\n throw Error(\n 'JwtService plugin not found, which is required for JWT signing in the VCDM2 SD-JWT credential provider. Please add the JwtService plugin to your agent configuration.',\n )\n } else if (!contextHasPlugin<IIdentifierResolution>(context, 'identifierManagedGet')) {\n throw Error(\n 'Identifier resolution plugin not found, which is required for JWT signing in the VCDM2 SD-JWT credential provider. Please add the JwtService plugin to your agent configuration.',\n )\n }\n return context as IAgentContext<\n IResolver & IDIDManager & Pick<IKeyManager, 'keyManagerGet' | 'keyManagerSign' | 'keyManagerVerify'> & IJwtService & IIdentifierResolution\n >\n}\n","import canonicalizeData from 'canonicalize'\nimport { type DIDDocument, type DIDResolutionResult, parse, type ParsedDID, type Resolvable, type VerificationMethod } from 'did-resolver'\nimport SignerAlg from './SignerAlgorithm'\nimport { decodeBase64url, type EcdsaSignature, encodeBase64url, type KNOWN_JWA, SUPPORTED_PUBLIC_KEY_TYPES } from './util'\nimport VerifierAlgorithm from './VerifierAlgorithm'\nimport { JWT_ERROR } from 'did-jwt'\n\nexport type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>\nexport type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>\n\nexport type ProofPurposeTypes =\n | 'assertionMethod'\n | 'authentication'\n // | 'keyAgreement' // keyAgreement VerificationMethod should not be used for signing\n | 'capabilityDelegation'\n | 'capabilityInvocation'\n\nexport interface JWTOptions {\n issuer: string\n signer: Signer\n /**\n * @deprecated Please use `header.alg` to specify the JWT algorithm.\n */\n alg?: string\n expiresIn?: number\n canonicalize?: boolean\n}\n\nexport interface JWTVerifyOptions {\n /** @deprecated Please use `proofPurpose: 'authentication' instead` */\n auth?: boolean\n audience?: string\n callbackUrl?: string\n resolver?: Resolvable\n skewTime?: number\n /** See https://www.w3.org/TR/did-spec-registries/#verification-relationships */\n proofPurpose?: ProofPurposeTypes\n policies?: JWTVerifyPolicies\n didAuthenticator?: DIDAuthenticator\n}\n\n/**\n * Overrides the different types of checks performed on the JWT besides the signature check\n */\nexport interface JWTVerifyPolicies {\n // overrides the timestamp against which the validity interval is checked\n now?: number\n // when set to false, the timestamp checks ignore the Not Before(`nbf`) property\n nbf?: boolean\n // when set to false, the timestamp checks ignore the Issued At(`iat`) property\n iat?: boolean\n // when set to false, the timestamp checks ignore the Expires At(`exp`) property\n exp?: boolean\n // when set to false, the JWT audience check is skipped\n aud?: boolean\n}\n\nexport interface JWSCreationOptions {\n canonicalize?: boolean\n}\n\nexport interface DIDAuthenticator {\n authenticators: VerificationMethod[]\n issuer: string\n didResolutionResult: DIDResolutionResult\n}\n\nexport interface JWTHeader {\n typ: 'JWT'\n alg: string\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any\n}\n\nexport interface JWTPayload {\n iss?: string\n sub?: string\n aud?: string | string[]\n iat?: number\n nbf?: number\n exp?: number\n rexp?: number\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any\n}\n\nexport interface JWTDecoded {\n header: JWTHeader\n payload: JWTPayload\n signature: string\n data: string\n}\n\nexport interface JWSDecoded {\n header: JWTHeader\n payload: string\n signature: string\n data: string\n}\n\n/**\n * Result object returned by {@link verifyJWT}\n */\nexport interface JWTVerified {\n /**\n * Set to true for a JWT that passes all the required checks minus any verification overrides.\n */\n verified: true\n\n /**\n * The decoded JWT payload\n */\n payload: Partial<JWTPayload>\n\n /**\n * The result of resolving the issuer DID\n */\n didResolutionResult: DIDResolutionResult\n\n /**\n * the issuer DID\n */\n issuer: string\n\n /**\n * The public key of the issuer that matches the JWT signature\n */\n signer: VerificationMethod\n\n /**\n * The original JWT that was verified\n */\n jwt: string\n\n /**\n * Any overrides that were used during verification\n */\n policies?: JWTVerifyPolicies\n}\n\nexport const SELF_ISSUED_V2 = 'https://self-issued.me/v2'\nexport const SELF_ISSUED_V2_VC_INTEROP = 'https://self-issued.me/v2/openid-vc' // https://identity.foundation/jwt-vc-presentation-profile/#id-token-validation\nexport const SELF_ISSUED_V0_1 = 'https://self-issued.me'\n\ntype LegacyVerificationMethod = { publicKey?: string }\n\nconst defaultAlg: KNOWN_JWA = 'ES256K'\nconst DID_JSON = 'application/did+json'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction encodeSection(data: any, shouldCanonicalize = false): string {\n if (shouldCanonicalize) {\n return encodeBase64url(<string>canonicalizeData(data))\n } else {\n return encodeBase64url(JSON.stringify(data))\n }\n}\n\nexport const NBF_SKEW = 300\n\nfunction decodeJWS(jws: string): JWSDecoded {\n const parts = jws.match(/^([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)$/)\n if (parts) {\n return {\n header: JSON.parse(decodeBase64url(parts[1])),\n payload: parts[2],\n signature: parts[3],\n data: `${parts[1]}.${parts[2]}`,\n }\n }\n throw new Error('invalid_argument: Incorrect format JWS')\n}\n\n/**\n * Decodes a JWT and returns an object representing the payload\n *\n * @example\n * decodeJWT('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJpYXQiOjE1...')\n *\n * @param {String} jwt a JSON Web Token to verify\n * @param {Object} [recurse] whether to recurse into the payload to decode any nested JWTs\n * @return {Object} a JS object representing the decoded JWT\n */\nexport function decodeJWT(jwt: string, recurse = true): JWTDecoded {\n if (!jwt) throw new Error('invalid_argument: no JWT passed into decodeJWT')\n try {\n const jws = decodeJWS(jwt)\n const decodedJwt: JWTDecoded = Object.assign(jws, { payload: JSON.parse(decodeBase64url(jws.payload)) })\n const iss = decodedJwt.payload.iss\n\n if (decodedJwt.header.cty === 'JWT' && recurse) {\n const innerDecodedJwt = decodeJWT(decodedJwt.payload.jwt)\n\n if (innerDecodedJwt.payload.iss !== iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n return innerDecodedJwt\n }\n return decodedJwt\n } catch (e) {\n throw new Error(`invalid_argument: ${JWT_ERROR.INVALID_JWT}: ${e}`)\n }\n}\n\n/**\n * Creates a signed JWS given a payload, a signer, and an optional header.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * const jws = await createJWS({ my: 'payload' }, signer)\n *\n * @param {Object} payload payload object\n * @param {Signer} signer a signer, see `ES256KSigner or `EdDSASigner`\n * @param {Object} header optional object to specify or customize the JWS header\n * @param {Object} options can be used to trigger automatic canonicalization of header and\n * payload properties\n * @return {Promise<string>} a Promise which resolves to a JWS string or rejects with an error\n */\nexport async function createJWS(\n payload: string | Partial<JWTPayload>,\n signer: Signer,\n header: Partial<JWTHeader> = {},\n options: JWSCreationOptions = {},\n): Promise<string> {\n if (!header.alg) header.alg = defaultAlg\n const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload, options.canonicalize)\n const signingInput: string = [encodeSection(header, options.canonicalize), encodedPayload].join('.')\n\n const jwtSigner: SignerAlgorithm = SignerAlg(header.alg)\n const signature: string = await jwtSigner(signingInput, signer)\n\n // JWS Compact Serialization\n // https://www.rfc-editor.org/rfc/rfc7515#section-7.1\n return [signingInput, signature].join('.')\n}\n\n/**\n * Creates a signed JWT given an address which becomes the issuer, a signer, and a payload for which the signature is\n * over.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n * ...\n * })\n *\n * @param {Object} payload payload object\n * @param {Object} [options] an unsigned credential object\n * @param {String} options.issuer The DID of the issuer (signer) of JWT\n * @param {String} options.alg [DEPRECATED] The JWT signing algorithm to use. Supports:\n * [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n * @param {Signer} options.signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n * @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing\n * @param {Object} header optional object to specify or customize the JWT header\n * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or\n * rejects with an error\n */\nexport async function createJWT(\n payload: Partial<JWTPayload>,\n { issuer, signer, alg, expiresIn, canonicalize }: JWTOptions,\n header: Partial<JWTHeader> = {},\n): Promise<string> {\n if (!signer) throw new Error('missing_signer: No Signer functionality has been configured')\n if (!issuer) throw new Error('missing_issuer: No issuing DID has been configured')\n if (!header.typ) header.typ = 'JWT'\n if (!header.alg) header.alg = alg\n const timestamps: Partial<JWTPayload> = {\n iat: Math.floor(Date.now() / 1000),\n exp: undefined,\n }\n if (expiresIn) {\n if (typeof expiresIn === 'number') {\n timestamps.exp = <number>(payload.nbf || timestamps.iat) + Math.floor(expiresIn)\n } else {\n throw new Error('invalid_argument: JWT expiresIn is not a number')\n }\n }\n const fullPayload = { ...timestamps, ...payload, iss: issuer }\n return createJWS(fullPayload, signer, header, { canonicalize })\n}\n\n/**\n * Creates a multi-signature signed JWT given multiple issuers and their corresponding signers, and a payload for\n * which the signature is over.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n * ...\n * })\n *\n * @param {Object} payload payload object\n * @param {Object} [options] an unsigned credential object\n * @param {boolean} options.expiresIn optional flag to denote the expiration time\n * @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing\n * @param {Object[]} issuers array of the issuers, their signers and algorithms\n * @param {string} issuers[].issuer The DID of the issuer (signer) of JWT\n * @param {Signer} issuers[].signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n * @param {String} issuers[].alg [DEPRECATED] The JWT signing algorithm to use. Supports:\n * [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or\n * rejects with an error\n */\nexport async function createMultisignatureJWT(\n payload: Partial<JWTPayload>,\n { expiresIn, canonicalize }: Partial<JWTOptions>,\n issuers: { issuer: string; signer: Signer; alg: string }[],\n): Promise<string> {\n if (issuers.length === 0) throw new Error('invalid_argument: must provide one or more issuers')\n\n let payloadResult: Partial<JWTPayload> = payload\n\n let jwt = ''\n for (let i = 0; i < issuers.length; i++) {\n const issuer = issuers[i]\n\n const header: Partial<JWTHeader> = {\n typ: 'JWT',\n alg: issuer.alg,\n }\n\n // Create nested JWT\n // See Point 5 of https://www.rfc-editor.org/rfc/rfc7519#section-7.1\n // After the first JWT is created (the first JWS), the next JWT is created by inputting the previous JWT as the\n // payload\n if (i !== 0) {\n header.cty = 'JWT'\n }\n\n jwt = await createJWT(payloadResult, { ...issuer, canonicalize, expiresIn }, header)\n\n payloadResult = { jwt }\n }\n return jwt\n}\n\nexport function verifyJWTDecoded(\n { header, payload, data, signature }: JWTDecoded,\n pubKeys: VerificationMethod | VerificationMethod[],\n): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n\n const iss = payload.iss\n let recurse = true\n do {\n if (iss !== payload.iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n\n try {\n const result = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n\n return result\n } catch (e) {\n if (!(e as Error).message.startsWith(JWT_ERROR.INVALID_SIGNATURE)) throw e\n }\n\n // TODO probably best to create copy objects than replace reference objects\n if (header.cty !== 'JWT') {\n recurse = false\n } else {\n ;({ payload, header, signature, data } = decodeJWT(payload.jwt, false))\n }\n } while (recurse)\n\n throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: no matching public key found`)\n}\n\nexport function verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n return signer\n}\n\n/**\n * Verifies given JWS. If the JWS is valid, returns the public key that was\n * used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.\n *\n * @example\n * const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })\n *\n * @param {String} jws A JWS string to verify\n * @param {Array<VerificationMethod> | VerificationMethod} pubKeys The public keys used to verify the JWS\n * @return {VerificationMethod} The public key used to sign the JWS\n */\nexport function verifyJWS(jws: string, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n const jwsDecoded: JWSDecoded = decodeJWS(jws)\n return verifyJWSDecoded(jwsDecoded, pubKeys)\n}\n\n/**\n * Verifies given JWT. If the JWT is valid, the promise returns an object including the JWT, the payload of the JWT,\n * and the DID document of the issuer of the JWT.\n *\n * @example\n * ```ts\n * verifyJWT(\n * 'did:uport:eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....',\n * {audience: '5A8bRWU3F7j3REx3vkJ...', callbackUrl: 'https://...'}\n * ).then(obj => {\n * const did = obj.did // DID of signer\n * const payload = obj.payload\n * const doc = obj.didResolutionResult.didDocument // DID Document of issuer\n * const jwt = obj.jwt\n * const signerKeyId = obj.signer.id // ID of key in DID document that signed JWT\n * ...\n * })\n * ```\n *\n * @param {String} jwt a JSON Web Token to verify\n * @param {Object} [options] an unsigned credential object\n * @param {Boolean} options.auth Require signer to be listed in the authentication section of the\n * DID document (for Authentication purposes)\n * @param {String} options.audience DID of the recipient of the JWT\n * @param {String} options.callbackUrl callback url in JWT\n * @return {Promise<Object, Error>} a promise which resolves with a response object or rejects with an\n * error\n */\nexport async function verifyJWT(\n jwt: string,\n options: JWTVerifyOptions = {\n resolver: undefined,\n auth: undefined,\n audience: undefined,\n callbackUrl: undefined,\n skewTime: undefined,\n proofPurpose: undefined,\n policies: {},\n didAuthenticator: undefined,\n },\n): Promise<JWTVerified> {\n if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n const { payload, header /*, signature, data*/ }: JWTDecoded = decodeJWT(jwt, false)\n const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n ? options.auth\n ? 'authentication'\n : undefined\n : options.proofPurpose\n\n let didUrl: string | undefined\n\n if (!payload.iss && !payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n\n if (options.didAuthenticator) {\n didUrl = options.didAuthenticator.issuer\n } else if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.sub) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n didUrl = payload.sub\n } else {\n didUrl = (header.kid || '').split('#')[0]\n }\n } else if (payload.iss === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n didUrl = payload.did\n } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n didUrl = payload.client_id\n } else {\n didUrl = payload.iss\n }\n\n if (!didUrl) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n\n let authenticators: VerificationMethod[]\n let issuer: string\n let didResolutionResult: DIDResolutionResult\n if (options.didAuthenticator) {\n ;({ didResolutionResult, authenticators, issuer } = options.didAuthenticator)\n } else {\n ;({ didResolutionResult, authenticators, issuer } = await resolveAuthenticator(options.resolver, header.alg, didUrl, proofPurpose))\n // Add to options object for recursive reference\n options.didAuthenticator = { didResolutionResult, authenticators, issuer }\n }\n\n const { did } = parse(didUrl) as ParsedDID\n\n let signer: VerificationMethod | null = null\n\n if (did !== didUrl) {\n const authenticator = authenticators.find((auth) => auth.id === didUrl)\n if (!authenticator) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No authenticator found for did URL ${didUrl}`)\n }\n\n // signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n } else {\n let i = 0\n while (!signer && i < authenticators.length) {\n // const authenticator = authenticators[i]\n try {\n // signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n } catch (e) {\n if (!(e as Error).message.includes(JWT_ERROR.INVALID_SIGNATURE) || i === authenticators.length - 1) throw e\n }\n\n i++\n }\n }\n\n if (signer) {\n const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n\n const nowSkewed = now + skewTime\n if (options.policies?.nbf !== false && payload.nbf) {\n if (payload.nbf > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n }\n } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n }\n if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n }\n if (options.policies?.aud !== false && payload.aud) {\n if (!options.audience && !options.callbackUrl) {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`)\n }\n const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n const matchedAudience = audArray.find((item) => options.audience === item || options.callbackUrl === item)\n\n if (typeof matchedAudience === 'undefined') {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n }\n }\n\n return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n }\n throw new Error(\n `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`,\n )\n}\n\n/**\n * Resolves relevant public keys or other authenticating material used to verify signature from the DID document of\n * provided DID\n *\n * @example\n * ```ts\n * resolveAuthenticator(resolver, 'ES256K', 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX').then(obj => {\n * const payload = obj.payload\n * const profile = obj.profile\n * const jwt = obj.jwt\n * // ...\n * })\n * ```\n *\n * @param resolver - {Resolvable} a DID resolver function that can obtain the `DIDDocument` for the `issuer`\n * @param alg - {String} a JWT algorithm\n * @param issuer - {String} a Decentralized Identifier (DID) to lookup\n * @param proofPurpose - {ProofPurposeTypes} *Optional* Use the verificationMethod linked in that section of the\n * issuer DID document\n * @return {Promise<DIDAuthenticator>} a promise which resolves with an object containing an array of authenticators\n * or rejects with an error if none exist\n */\nexport async function resolveAuthenticator(\n resolver: Resolvable,\n alg: string,\n issuer: string,\n proofPurpose?: ProofPurposeTypes,\n): Promise<DIDAuthenticator> {\n const types: string[] = SUPPORTED_PUBLIC_KEY_TYPES[alg as KNOWN_JWA]\n if (!types || types.length === 0) {\n throw new Error(`${JWT_ERROR.NOT_SUPPORTED}: No supported signature types for algorithm ${alg}`)\n }\n let didResult: DIDResolutionResult\n\n const result = (await resolver.resolve(issuer, { accept: DID_JSON })) as unknown\n // support legacy resolvers that do not produce DIDResolutionResult\n if (Object.getOwnPropertyNames(result).indexOf('didDocument') === -1) {\n didResult = {\n didDocument: result as DIDDocument,\n didDocumentMetadata: {},\n didResolutionMetadata: { contentType: DID_JSON },\n }\n } else {\n didResult = result as DIDResolutionResult\n }\n\n if (didResult.didResolutionMetadata?.error || didResult.didDocument == null) {\n const { error, message } = didResult.didResolutionMetadata\n throw new Error(`${JWT_ERROR.RESOLVER_ERROR}: Unable to resolve DID document for ${issuer}: ${error}, ${message || ''}`)\n }\n\n const getPublicKeyById = (verificationMethods: VerificationMethod[], pubid?: string): VerificationMethod | null => {\n const filtered = verificationMethods.filter(({ id }) => pubid === id)\n return filtered.length > 0 ? filtered[0] : null\n }\n\n let publicKeysToCheck: VerificationMethod[] = [...(didResult?.didDocument?.verificationMethod || []), ...(didResult?.didDocument?.publicKey || [])]\n if (typeof proofPurpose === 'string') {\n // support legacy DID Documents that do not list assertionMethod\n if (proofPurpose.startsWith('assertion') && !Object.getOwnPropertyNames(didResult?.didDocument).includes('assertionMethod')) {\n didResult.didDocument = { ...(<DIDDocument>didResult.didDocument) }\n didResult.didDocument.assertionMethod = [...publicKeysToCheck.map((pk) => pk.id)]\n }\n\n publicKeysToCheck = (didResult.didDocument[proofPurpose] || [])\n .map((verificationMethod) => {\n if (typeof verificationMethod === 'string') {\n return getPublicKeyById(publicKeysToCheck, verificationMethod)\n } else if (typeof (<LegacyVerificationMethod>verificationMethod).publicKey === 'string') {\n // this is a legacy format\n return getPublicKeyById(publicKeysToCheck, (<LegacyVerificationMethod>verificationMethod).publicKey)\n } else {\n return <VerificationMethod>verificationMethod\n }\n })\n .filter((key) => key != null) as VerificationMethod[]\n }\n\n const authenticators: VerificationMethod[] = publicKeysToCheck.filter(({ type }) => types.find((supported) => supported === type))\n\n if (typeof proofPurpose === 'string' && (!authenticators || authenticators.length === 0)) {\n throw new Error(\n `${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys suitable for ${alg} with ${proofPurpose} purpose`,\n )\n }\n if (!authenticators || authenticators.length === 0) {\n throw new Error(`${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys for ${alg}`)\n }\n return { authenticators, issuer, didResolutionResult: didResult }\n}\n","// @ts-ignore\nimport * as u8a from 'uint8arrays'\n// const { concat, fromString, toString } = u8a\nimport { x25519 } from '@noble/curves/ed25519'\n\n// @ts-ignore\nimport { varint } from 'multiformats'\nimport { BaseName, decode, encode } from 'multibase'\nimport type { VerificationMethod } from 'did-resolver'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\n\n// const u8a = { toString, fromString, concat }\n\nexport interface EphemeralPublicKey {\n kty?: string\n //ECC\n crv?: string\n x?: string\n y?: string\n //RSA\n n?: string\n e?: string\n}\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport interface EcdsaSignature {\n r: string\n s: string\n recoveryParam?: number\n}\n\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport type ECDSASignature = {\n compact: Uint8Array\n recovery?: number\n}\n\nexport type JsonWebKey = {\n crv: string\n kty: string\n x?: string\n y?: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n}\n\nexport function bytesToBase64url(b: Uint8Array): string {\n return u8a.toString(b, 'base64url')\n}\n\nexport function base64ToBytes(s: string): Uint8Array {\n const inputBase64Url = s.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n return u8a.fromString(inputBase64Url, 'base64url')\n}\n\nexport function bytesToBase64(b: Uint8Array): string {\n return u8a.toString(b, 'base64pad')\n}\n\nexport function base58ToBytes(s: string): Uint8Array {\n return u8a.fromString(s, 'base58btc')\n}\n\nexport function bytesToBase58(b: Uint8Array): string {\n return u8a.toString(b, 'base58btc')\n}\n\nexport type KNOWN_JWA = 'ES256' | 'ES256K' | 'ES256K-R' | 'Ed25519' | 'EdDSA'\n\nexport type KNOWN_VERIFICATION_METHOD =\n | 'JsonWebKey2020'\n | 'Multikey'\n | 'Secp256k1SignatureVerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'Secp256k1VerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'EcdsaSecp256k1VerificationKey2019' // ES256K / ES256K-R\n | 'EcdsaPublicKeySecp256k1' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'EcdsaSecp256k1RecoveryMethod2020' // ES256K-R (ES256K also supported with 1 less bit of security)\n | 'EcdsaSecp256r1VerificationKey2019' // ES256 / P-256\n | 'Ed25519VerificationKey2018'\n | 'Ed25519VerificationKey2020'\n | 'ED25519SignatureVerification' // deprecated\n | 'ConditionalProof2022'\n | 'X25519KeyAgreementKey2019' // deprecated\n | 'X25519KeyAgreementKey2020'\n\nexport type KNOWN_KEY_TYPE = 'Secp256k1' | 'Ed25519' | 'X25519' | 'Bls12381G1' | 'Bls12381G2' | 'P-256'\n\nexport type PublicKeyTypes = Record<KNOWN_JWA, KNOWN_VERIFICATION_METHOD[]>\n\nexport const SUPPORTED_PUBLIC_KEY_TYPES: PublicKeyTypes = {\n ES256: ['JsonWebKey2020', 'Multikey', 'EcdsaSecp256r1VerificationKey2019'],\n ES256K: [\n 'EcdsaSecp256k1VerificationKey2019',\n /**\n * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n */\n 'EcdsaSecp256k1RecoveryMethod2020',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1VerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1SignatureVerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'EcdsaPublicKeySecp256k1',\n /**\n * TODO - support R1 key as well\n * 'ConditionalProof2022',\n */\n 'JsonWebKey2020',\n 'Multikey',\n ],\n 'ES256K-R': [\n 'EcdsaSecp256k1VerificationKey2019',\n /**\n * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n */\n 'EcdsaSecp256k1RecoveryMethod2020',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1VerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1SignatureVerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'EcdsaPublicKeySecp256k1',\n 'ConditionalProof2022',\n 'JsonWebKey2020',\n 'Multikey',\n ],\n Ed25519: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'JsonWebKey2020', 'Multikey'],\n EdDSA: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'JsonWebKey2020', 'Multikey'],\n}\n\nexport const VM_TO_KEY_TYPE: Record<KNOWN_VERIFICATION_METHOD, KNOWN_KEY_TYPE | undefined> = {\n Secp256k1SignatureVerificationKey2018: 'Secp256k1',\n Secp256k1VerificationKey2018: 'Secp256k1',\n EcdsaSecp256k1VerificationKey2019: 'Secp256k1',\n EcdsaPublicKeySecp256k1: 'Secp256k1',\n EcdsaSecp256k1RecoveryMethod2020: 'Secp256k1',\n EcdsaSecp256r1VerificationKey2019: 'P-256',\n Ed25519VerificationKey2018: 'Ed25519',\n Ed25519VerificationKey2020: 'Ed25519',\n ED25519SignatureVerification: 'Ed25519',\n X25519KeyAgreementKey2019: 'X25519',\n X25519KeyAgreementKey2020: 'X25519',\n ConditionalProof2022: undefined,\n JsonWebKey2020: undefined, // key type must be specified in the JWK\n Multikey: undefined, // key type must be extracted from the multicodec\n}\n\nexport type KNOWN_CODECS = 'ed25519-pub' | 'x25519-pub' | 'secp256k1-pub' | 'bls12_381-g1-pub' | 'bls12_381-g2-pub' | 'p256-pub'\n\n// this is from the multicodec table https://github.com/multiformats/multicodec/blob/master/table.csv\nexport const supportedCodecs: Record<KNOWN_CODECS, number> = {\n 'ed25519-pub': 0xed,\n 'x25519-pub': 0xec,\n 'secp256k1-pub': 0xe7,\n 'bls12_381-g1-pub': 0xea,\n 'bls12_381-g2-pub': 0xeb,\n 'p256-pub': 0x1200,\n}\n\nexport const CODEC_TO_KEY_TYPE: Record<KNOWN_CODECS, KNOWN_KEY_TYPE> = {\n 'bls12_381-g1-pub': 'Bls12381G1',\n 'bls12_381-g2-pub': 'Bls12381G2',\n 'ed25519-pub': 'Ed25519',\n 'p256-pub': 'P-256',\n 'secp256k1-pub': 'Secp256k1',\n 'x25519-pub': 'X25519',\n}\n\n/**\n * Extracts the raw byte representation of a public key from a VerificationMethod along with an inferred key type\n * @param pk a VerificationMethod entry from a DIDDocument\n * @return an object containing the `keyBytes` of the public key and an inferred `keyType`\n */\nexport function extractPublicKeyBytes(pk: VerificationMethod): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n if (pk.publicKeyBase58) {\n return {\n keyBytes: base58ToBytes(pk.publicKeyBase58),\n keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n }\n } else if (pk.publicKeyBase64) {\n return {\n keyBytes: base64ToBytes(pk.publicKeyBase64),\n keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n }\n } else if (pk.publicKeyHex) {\n return { keyBytes: hexToBytes(pk.publicKeyHex), keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return {\n keyBytes: secp256k1.ProjectivePoint.fromAffine({\n x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n }).toRawBytes(false),\n keyType: 'Secp256k1',\n }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return {\n keyBytes: p256.ProjectivePoint.fromAffine({\n x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n }).toRawBytes(false),\n keyType: 'P-256',\n }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === 'OKP' && ['Ed25519', 'X25519'].includes(pk.publicKeyJwk.crv ?? '') && pk.publicKeyJwk.x) {\n return { keyBytes: base64ToBytes(pk.publicKeyJwk.x), keyType: pk.publicKeyJwk.crv as KNOWN_KEY_TYPE }\n } else if (pk.publicKeyMultibase) {\n const { keyBytes, keyType } = multibaseToBytes(pk.publicKeyMultibase)\n return { keyBytes, keyType: keyType ?? VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n }\n return { keyBytes: new Uint8Array() }\n}\n\n/**\n * Encodes the given byte array to a multibase string (defaulting to base58btc).\n * If a codec is provided, the corresponding multicodec prefix will be added.\n *\n * @param b - the Uint8Array to be encoded\n * @param base - the base to use for encoding (defaults to base58btc)\n * @param codec - the codec to use for encoding (defaults to no codec)\n *\n * @returns the multibase encoded string\n *\n * @public\n */\nexport function bytesToMultibase(b: Uint8Array, base: BaseName = 'base58btc', codec?: keyof typeof supportedCodecs | number): string {\n if (!codec) {\n return u8a.toString(encode(base, b), 'utf-8')\n } else {\n const codecCode = typeof codec === 'string' ? supportedCodecs[codec] : codec\n const prefixLength = varint.encodingLength(codecCode)\n const multicodecEncoding = new Uint8Array(prefixLength + b.length)\n varint.encodeTo(codecCode, multicodecEncoding) // set prefix\n multicodecEncoding.set(b, prefixLength) // add the original bytes\n return u8a.toString(encode(base, multicodecEncoding), 'utf-8')\n }\n}\n\n/**\n * Converts a multibase string to the Uint8Array it represents.\n * This method will assume the byte array that is multibase encoded is a multicodec and will attempt to decode it.\n *\n * @param s - the string to be converted\n *\n * @throws if the string is not formatted correctly.\n *\n * @public\n */\nexport function multibaseToBytes(s: string): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n const bytes = decode(s)\n\n // look for known key lengths first\n // Ed25519/X25519, secp256k1/P256 compressed or not, BLS12-381 G1/G2 compressed\n if ([32, 33, 48, 64, 65, 96].includes(bytes.length)) {\n return { keyBytes: bytes }\n }\n\n // then assume multicodec, otherwise return the bytes\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [codec, length] = varint.decode(bytes)\n const possibleCodec: string | undefined = Object.entries(supportedCodecs).filter(([, code]) => code === codec)?.[0][0] ?? ''\n return { keyBytes: bytes.slice(length), keyType: CODEC_TO_KEY_TYPE[possibleCodec as KNOWN_CODECS] }\n } catch (e) {\n // not a multicodec, return the bytes\n return { keyBytes: bytes }\n }\n}\n\nexport function hexToBytes(s: string, minLength?: number): Uint8Array {\n let input = s.startsWith('0x') ? s.substring(2) : s\n\n if (input.length % 2 !== 0) {\n input = `0${input}`\n }\n\n if (minLength) {\n const paddedLength = Math.max(input.length, minLength * 2)\n input = input.padStart(paddedLength, '00')\n }\n\n return u8a.fromString(input.toLowerCase(), 'base16')\n}\n\nexport function encodeBase64url(s: string): string {\n return bytesToBase64url(u8a.fromString(s))\n}\n\nexport function decodeBase64url(s: string): string {\n return u8a.toString(base64ToBytes(s))\n}\n\nexport function bytesToHex(b: Uint8Array): string {\n return u8a.toString(b, 'base16')\n}\n\nexport function bytesToBigInt(b: Uint8Array): bigint {\n return BigInt(`0x` + u8a.toString(b, 'base16'))\n}\n\nexport function bigintToBytes(n: bigint, minLength?: number): Uint8Array {\n return hexToBytes(n.toString(16), minLength)\n}\n\nexport function stringToBytes(s: string): Uint8Array {\n return u8a.fromString(s, 'utf-8')\n}\n\nexport function toJose({ r, s, recoveryParam }: EcdsaSignature, recoverable?: boolean): string {\n const jose = new Uint8Array(recoverable ? 65 : 64)\n jose.set(u8a.fromString(r, 'base16'), 0)\n jose.set(u8a.fromString(s, 'base16'), 32)\n if (recoverable) {\n if (typeof recoveryParam === 'undefined') {\n throw new Error('Signer did not return a recoveryParam')\n }\n jose[64] = <number>recoveryParam\n }\n return bytesToBase64url(jose)\n}\n\nexport function fromJose(signature: string): { r: string; s: string; recoveryParam?: number } {\n const signatureBytes: Uint8Array = base64ToBytes(signature)\n if (signatureBytes.length < 64 || signatureBytes.length > 65) {\n throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`)\n }\n const r = bytesToHex(signatureBytes.slice(0, 32))\n const s = bytesToHex(signatureBytes.slice(32, 64))\n const recoveryParam = signatureBytes.length === 65 ? signatureBytes[64] : undefined\n return { r, s, recoveryParam }\n}\n\nexport function toSealed(ciphertext: string, tag?: string): Uint8Array {\n return u8a.concat([base64ToBytes(ciphertext), tag ? base64ToBytes(tag) : new Uint8Array(0)])\n}\n\nexport function leftpad(data: string, size = 64): string {\n if (data.length === size) return data\n return '0'.repeat(size - data.length) + data\n}\n\n/**\n * Generate random x25519 key pair.\n */\nexport function generateKeyPair(): { secretKey: Uint8Array; publicKey: Uint8Array } {\n const secretKey = x25519.utils.randomPrivateKey()\n const publicKey = x25519.getPublicKey(secretKey)\n return {\n secretKey: secretKey,\n publicKey: publicKey,\n }\n}\n\n/**\n * Generate private-public x25519 key pair from `seed`.\n */\nexport function generateKeyPairFromSeed(seed: Uint8Array): { secretKey: Uint8Array; publicKey: Uint8Array } {\n if (seed.length !== 32) {\n throw new Error(`x25519: seed must be ${32} bytes`)\n }\n return {\n publicKey: x25519.getPublicKey(seed),\n secretKey: seed,\n }\n}\n/*\n\nexport function genX25519EphemeralKeyPair(): EphemeralKeyPair {\n const epk = generateKeyPair()\n return {\n publicKeyJWK: { kty: 'OKP', crv: 'X25519', x: bytesToBase64url(epk.publicKey) },\n secretKey: epk.secretKey,\n }\n}\n*/\n\n/**\n * Checks if a variable is defined and not null.\n * After this check, typescript sees the variable as defined.\n *\n * @param arg - The input to be verified\n *\n * @returns true if the input variable is defined.\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n return arg !== null && typeof arg !== 'undefined'\n}\n","import type { Signer, SignerAlgorithm } from './JWT'\nimport { type EcdsaSignature, fromJose, toJose } from './util'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction instanceOfEcdsaSignature(object: any): object is EcdsaSignature {\n return typeof object === 'object' && 'r' in object && 's' in object\n}\n\nexport function ES256SignerAlg(): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (instanceOfEcdsaSignature(signature)) {\n return toJose(signature)\n } else {\n return signature\n }\n }\n}\n\nexport function ES256KSignerAlg(recoverable?: boolean): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (instanceOfEcdsaSignature(signature)) {\n return toJose(signature, recoverable)\n } else {\n if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') {\n throw new Error(`not_supported: ES256K-R not supported when signer doesn't provide a recovery param`)\n }\n return signature\n }\n }\n}\n\nexport function Ed25519SignerAlg(): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (!instanceOfEcdsaSignature(signature)) {\n return signature\n } else {\n throw new Error('invalid_config: expected a signer function that returns a string instead of signature object')\n }\n }\n}\n\ninterface SignerAlgorithms {\n [alg: string]: SignerAlgorithm\n}\n\nconst algorithms: SignerAlgorithms = {\n ES256: ES256SignerAlg(),\n ES256K: ES256KSignerAlg(),\n // This is a non-standard algorithm but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/146\n 'ES256K-R': ES256KSignerAlg(true),\n // This is actually incorrect but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/130\n Ed25519: Ed25519SignerAlg(),\n EdDSA: Ed25519SignerAlg(),\n}\n\nfunction SignerAlg(alg: string): SignerAlgorithm {\n const impl: SignerAlgorithm = algorithms[alg]\n if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n return impl\n}\n\nexport default SignerAlg\n","import { toEthereumAddress } from 'did-jwt'\nimport type { VerificationMethod } from 'did-resolver'\nimport { base64ToBytes, bytesToHex, type EcdsaSignature, type ECDSASignature, extractPublicKeyBytes, type KNOWN_JWA, stringToBytes } from './util'\n// @ts-ignore\n// import { verifyBlockchainAccountId } from 'did-jwt'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\nimport { ed25519 } from '@noble/curves/ed25519'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nimport { sha256 as hash } from '@noble/hashes/sha256'\n\nexport function sha256(payload: string | Uint8Array): Uint8Array {\n const data = typeof payload === 'string' ? u8a.fromString(payload) : payload\n return hash(data)\n}\n// converts a JOSE signature to it's components\nexport function toSignatureObject(signature: string, recoverable = false): EcdsaSignature {\n const rawSig: Uint8Array = base64ToBytes(signature)\n if (rawSig.length !== (recoverable ? 65 : 64)) {\n throw new Error('wrong signature length')\n }\n const r: string = bytesToHex(rawSig.slice(0, 32))\n const s: string = bytesToHex(rawSig.slice(32, 64))\n const sigObj: EcdsaSignature = { r, s }\n if (recoverable) {\n sigObj.recoveryParam = rawSig[64]\n }\n return sigObj\n}\n\nexport function toSignatureObject2(signature: string, recoverable = false): ECDSASignature {\n const bytes = base64ToBytes(signature)\n if (bytes.length !== (recoverable ? 65 : 64)) {\n throw new Error('wrong signature length')\n }\n return {\n compact: bytes.slice(0, 64),\n recovery: bytes[64],\n }\n}\n\nexport function verifyES256(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const hash = sha256(data)\n const sig = p256.Signature.fromCompact(toSignatureObject2(signature).compact)\n const fullPublicKeys = authenticators.filter((a: VerificationMethod) => !a.ethereumAddress && !a.blockchainAccountId)\n\n const signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n try {\n const { keyBytes } = extractPublicKeyBytes(pk)\n return p256.verify(sig, hash, keyBytes)\n } catch (err) {\n return false\n }\n })\n\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\nexport function verifyES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const hash = sha256(data)\n const signatureNormalized = secp256k1.Signature.fromCompact(base64ToBytes(signature)).normalizeS()\n const fullPublicKeys = authenticators.filter((a: VerificationMethod) => {\n return !a.ethereumAddress && !a.blockchainAccountId\n })\n const blockchainAddressKeys = authenticators.filter((a: VerificationMethod) => {\n return a.ethereumAddress || a.blockchainAccountId\n })\n\n let signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n try {\n const { keyBytes } = extractPublicKeyBytes(pk)\n return secp256k1.verify(signatureNormalized, hash, keyBytes)\n } catch (err) {\n return false\n }\n })\n\n if (!signer && blockchainAddressKeys.length > 0) {\n signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys)\n }\n\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\nexport function verifyRecoverableES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const signatures: ECDSASignature[] = []\n if (signature.length > 86) {\n signatures.push(toSignatureObject2(signature, true))\n } else {\n const so = toSignatureObject2(signature, false)\n signatures.push({ ...so, recovery: 0 })\n signatures.push({ ...so, recovery: 1 })\n }\n const hash = sha256(data)\n\n const checkSignatureAgainstSigner = (sigObj: ECDSASignature): VerificationMethod | undefined => {\n const signature = secp256k1.Signature.fromCompact(sigObj.compact).addRecoveryBit(sigObj.recovery || 0)\n const recoveredPublicKey = signature.recoverPublicKey(hash)\n const recoveredAddress = toEthereumAddress(recoveredPublicKey.toHex(false)).toLowerCase()\n const recoveredPublicKeyHex = recoveredPublicKey.toHex(false)\n const recoveredCompressedPublicKeyHex = recoveredPublicKey.toHex(true)\n\n return authenticators.find((a: VerificationMethod) => {\n const { keyBytes } = extractPublicKeyBytes(a)\n const keyHex = bytesToHex(keyBytes)\n return (\n keyHex === recoveredPublicKeyHex ||\n keyHex === recoveredCompressedPublicKeyHex ||\n a.ethereumAddress?.toLowerCase() === recoveredAddress ||\n a.blockchainAccountId?.split('@eip155')?.[0].toLowerCase() === recoveredAddress //|| // CAIP-2\n // verifyBlockchainAccountId(recoveredPublicKeyHex, a.blockchainAccountId) // CAIP-10\n )\n })\n }\n\n // Find first verification method\n for (const signature of signatures) {\n const verificationMethod = checkSignatureAgainstSigner(signature)\n if (verificationMethod) return verificationMethod\n }\n // If no one found matching\n throw new Error('invalid_signature: Signature invalid for JWT')\n}\n\nexport function verifyEd25519(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const clear = stringToBytes(data)\n const signatureBytes = base64ToBytes(signature)\n const signer = authenticators.find((a: VerificationMethod) => {\n const { keyBytes, keyType } = extractPublicKeyBytes(a)\n if (keyType === 'Ed25519') {\n return ed25519.verify(signatureBytes, clear, keyBytes)\n } else {\n return false\n }\n })\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\ntype Verifier = (data: string, signature: string, authenticators: VerificationMethod[]) => VerificationMethod\n\ntype Algorithms = Record<KNOWN_JWA, Verifier>\n\nconst algorithms: Algorithms = {\n ES256: verifyES256,\n ES256K: verifyES256K,\n // This is a non-standard algorithm but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/146\n 'ES256K-R': verifyRecoverableES256K,\n // This is actually incorrect but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/130\n Ed25519: verifyEd25519,\n EdDSA: verifyEd25519,\n}\n\nfunction VerifierAlgorithm(alg: string): Verifier {\n const impl: Verifier = algorithms[alg as KNOWN_JWA]\n if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n return impl\n}\n\nVerifierAlgorithm.toSignatureObject = toSignatureObject\n\nexport default VerifierAlgorithm\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;ACAA,yBAKO;AAEP,IAAAA,sBAA0C;AAC1C,qBAAiC;AACjC,IAAAC,kBAA+F;AAC/F,IAAAA,kBAaO;AACP,uBAA2G;AAa3G,mBAAkB;AAElB,IAAAC,kBAAqC;AAGrC,wBAAwG;;;AC1CxG,0BAA6B;AAC7B,0BAA4H;;;ACA5H,UAAqB;AAErB,qBAAuB;AAGvB,0BAAuB;AACvB,uBAAyC;AAEzC,uBAA0B;AAC1B,kBAAqB;AAwCd,SAASC,iBAAiBC,GAAa;AAC5C,SAAWC,aAASD,GAAG,WAAA;AACzB;AAFgBD;AAIT,SAASG,cAAcC,GAAS;AACrC,QAAMC,iBAAiBD,EAAEE,QAAQ,OAAO,GAAA,EAAKA,QAAQ,OAAO,GAAA,EAAKA,QAAQ,MAAM,EAAA;AAC/E,SAAWC,eAAWF,gBAAgB,WAAA;AACxC;AAHgBF;AAST,SAASK,cAAcC,GAAS;AACrC,SAAWC,eAAWD,GAAG,WAAA;AAC3B;AAFgBD;AAyFT,IAAMG,iBAAgF;EAC3FC,uCAAuC;EACvCC,8BAA8B;EAC9BC,mCAAmC;EACnCC,yBAAyB;EACzBC,kCAAkC;EAClCC,mCAAmC;EACnCC,4BAA4B;EAC5BC,4BAA4B;EAC5BC,8BAA8B;EAC9BC,2BAA2B;EAC3BC,2BAA2B;EAC3BC,sBAAsBC;EACtBC,gBAAgBD;EAChBE,UAAU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AACA,SAAOT;AAGT;AAjBSG;","names":["import_ssi_sdk_ext","import_ssi_sdk","import_did_jwt","bytesToBase64url","b","toString","base64ToBytes","s","inputBase64Url","replace","fromString","base58ToBytes","s","fromString","VM_TO_KEY_TYPE","Secp256k1SignatureVerificationKey2018","Secp256k1VerificationKey2018","EcdsaSecp256k1VerificationKey2019","EcdsaPublicKeySecp256k1","EcdsaSecp256k1RecoveryMethod2020","EcdsaSecp256r1VerificationKey2019","Ed25519VerificationKey2018","Ed25519VerificationKey2020","ED25519SignatureVerification","X25519KeyAgreementKey2019","X25519KeyAgreementKey2020","ConditionalProof2022","undefined","JsonWebKey2020","Multikey","supportedCodecs","CODEC_TO_KEY_TYPE","extractPublicKeyBytes","pk","publicKeyBase58","keyBytes","base58ToBytes","keyType","type","publicKeyBase64","base64ToBytes","publicKeyHex","hexToBytes","publicKeyJwk","crv","x","y","secp256k1","ProjectivePoint","fromAffine","bytesToBigInt","toRawBytes","p256","kty","includes","publicKeyMultibase","multibaseToBytes","Uint8Array","multibaseToBytes","s","bytes","decode","includes","length","keyBytes","codec","varint","possibleCodec","Object","entries","supportedCodecs","filter","code","slice","keyType","CODEC_TO_KEY_TYPE","e","hexToBytes","minLength","input","startsWith","substring","paddedLength","Math","max","padStart","fromString","toLowerCase","bytesToHex","b","toString","bytesToBigInt","BigInt","stringToBytes","s","fromString","toJose","r","recoveryParam","recoverable","jose","Uint8Array","set","Error","bytesToBase64url","fromJose","signature","signatureBytes","base64ToBytes","length","TypeError","bytesToHex","slice","undefined","instanceOfEcdsaSignature","object","ES256SignerAlg","sign","payload","signer","signature","toJose","ES256KSignerAlg","recoverable","fromJose","recoveryParam","Error","Ed25519SignerAlg","algorithms","ES256","ES256K","Ed25519","EdDSA","import_secp256k1","import_p256","import_ed25519","u8a","sha256","payload","data","fromString","hash","toSignatureObject","signature","recoverable","rawSig","base64ToBytes","length","Error","r","bytesToHex","slice","s","sigObj","recoveryParam","toSignatureObject2","bytes","compact","recovery","verifyES256","authenticators","sig","p256","Signature","fromCompact","fullPublicKeys","filter","a","ethereumAddress","blockchainAccountId","signer","find","pk","keyBytes","extractPublicKeyBytes","verify","err","verifyES256K","signatureNormalized","secp256k1","normalizeS","blockchainAddressKeys","verifyRecoverableES256K","signatures","push","so","checkSignatureAgainstSigner","addRecoveryBit","recoveredPublicKey","recoverPublicKey","recoveredAddress","toEthereumAddress","toHex","toLowerCase","recoveredPublicKeyHex","recoveredCompressedPublicKeyHex","keyHex","split","verificationMethod","verifyEd25519","clear","stringToBytes","signatureBytes","keyType","ed25519","algorithms","ES256","ES256K","Ed25519","EdDSA","VerifierAlgorithm","alg","impl","import_did_jwt","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","SELF_ISSUED_V0_1","import_ssi_sdk","debug","Debug","CredentialProviderVcdm2SdJwt","matchKeyForType","key","matchKeyForJWT","getTypeProofFormat","canIssueCredentialType","args","format","proofFormat","toLowerCase","canVerifyDocumentType","document","jwt","proof","payload","decodeJWT","split","isVcdm2Credential","createVerifiableCredential","context","keyRef","agent","assertContext","credential","issuer","preProcessCredentialPayload","Promise","reject","Error","contextHasPlugin","identifier","didManagerGet","did","e","managedIdentifier","identifierManagedGetByDid","kmsKeyRef","pickSigningKey","alg","signatureAlgorithmFromKey","id","result","createSdJwtVc","type","credentialPayload","resolution","disclosureFrame","opts","normalized","normalizeCredential","verifyCredential","policies","uniform","CredentialMapper","toUniformCredential","verificationResult","verified","asArray","verifySdJwtVc","results","log","valid","error","message","errorCode","name","nbf","issuanceDate","validFrom","iat","exp","expirationDate","validUntil","aud","audience","verifierSignature","createVerifiablePresentation","presentation","holder","preProcessPresentation","domain","challenge","header","kid","meta","verificationMethod","typ","cty","nonce","jwtCreateJwsCompactSignature","mode","protectedHeader","clientIdScheme","normalizePresentation","verifyPresentation","fetchRemoteContexts","otherOptions","resolver","resolve","didUrl","resolveDid","options","resolutionOptions","intendedAudience","managedDids","didManagerFind","filtered","filter","includes","length","verifyPresentationJWT","verifiablePresentation","intersect","algorithms","wrapSigner","algorithm","data","keyManagerSign","verifierContext","credIssuer","undefined","JWT_ERROR","INVALID_JWT","getIssuerFromSdJwt","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","credentialSubject","sub_jwk","sub","SELF_ISSUED_V0_1","scope","redirect_uri","client_id","indexOf","identifierExternalResolve","validFromError","Date","parse","getTime","expired","didOpts","method","jwtResult","jwtVerifyJwsSignature","jws","jwk","jwks","isDidIdentifier","errorMessage","didResolutionResult"]}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent/CredentialProviderVcdm2SdJwt.ts","../src/did-jwt/JWT.ts","../src/did-jwt/util.ts","../src/did-jwt/SignerAlgorithm.ts","../src/did-jwt/VerifierAlgorithm.ts"],"sourcesContent":["import {\n type ExternalIdentifierDidOpts,\n ExternalIdentifierResult,\n type IIdentifierResolution,\n isDidIdentifier,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport type { IJwtService, JwsHeader, JwsPayload } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { signatureAlgorithmFromKey } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { contextHasPlugin } from '@sphereon/ssi-sdk.agent-config'\nimport { asArray, intersect, type VerifiableCredentialSP, type VerifiablePresentationSP } from '@sphereon/ssi-sdk.core'\nimport {\n type ICanIssueCredentialTypeArgs,\n type ICanVerifyDocumentTypeArgs,\n type ICreateVerifiableCredentialLDArgs,\n type ICreateVerifiablePresentationLDArgs,\n type IVcdmCredentialProvider,\n type IVcdmIssuerAgentContext,\n IVcdmVerifierAgentContext,\n IVerifyCredentialVcdmArgs,\n IVerifyPresentationLDArgs,\n pickSigningKey,\n preProcessCredentialPayload,\n preProcessPresentation,\n} from '@sphereon/ssi-sdk.credential-vcdm'\nimport { CredentialMapper, isVcdm2Credential, type IVerifyResult, type OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport type {\n IAgentContext,\n IDIDManager,\n IIdentifier,\n IKey,\n IKeyManager,\n IResolver,\n VerifiableCredential,\n VerificationPolicies,\n VerifierAgentContext,\n} from '@veramo/core'\n\nimport Debug from 'debug'\n\nimport { decodeJWT, JWT_ERROR } from 'did-jwt'\n\n// @ts-ignore\nimport { normalizeCredential, normalizePresentation, verifyPresentation as verifyPresentationJWT } from 'did-jwt-vc'\n\nimport { type Resolvable } from 'did-resolver'\n\nimport { SELF_ISSUED_V0_1, SELF_ISSUED_V2, SELF_ISSUED_V2_VC_INTEROP } from '../did-jwt/JWT'\nimport { getIssuerFromSdJwt, ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\n// import {validateCredentialPayload} from \"did-jwt-vc/src\";\n\nconst debug = Debug('sphereon:ssi-sdk:credential-vcdm2-sdjwt')\n\n/**\n * A handler that implements the {@link IVcdmCredentialProvider} methods.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport class CredentialProviderVcdm2SdJwt implements IVcdmCredentialProvider {\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.matchKeyForType} */\n matchKeyForType(key: IKey): boolean {\n return this.matchKeyForJWT(key)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.getTypeProofFormat} */\n getTypeProofFormat(): string {\n return 'vc+sd-jwt'\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canIssueCredentialType} */\n canIssueCredentialType(args: ICanIssueCredentialTypeArgs): boolean {\n const format = args.proofFormat.toLowerCase()\n // TODO: Create type\n return format === 'vc+sd-jwt' || format === 'vcdm2_sdjwt'\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canVerifyDocumentType */\n canVerifyDocumentType(args: ICanVerifyDocumentTypeArgs): boolean {\n const { document } = args\n const jwt = typeof document === 'string' ? document : (<VerifiableCredential>document)?.proof?.jwt\n if (!jwt) {\n return false\n }\n const { payload } = decodeJWT(jwt.split('~')[0])\n return isVcdm2Credential(payload)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiableCredential} */\n async createVerifiableCredential(args: ICreateVerifiableCredentialLDArgs, context: IVcdmIssuerAgentContext): Promise<VerifiableCredentialSP> {\n const { keyRef } = args\n const agent = assertContext(context).agent\n const { credential, issuer } = preProcessCredentialPayload(args)\n if (!isVcdm2Credential(credential)) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential. Context: ' + credential['@context']))\n } else if (!contextHasPlugin<ISDJwtPlugin>(context, 'createSdJwtVc')) {\n return Promise.reject(\n new Error('invalid_argument: SD-JWT plugin not available. Please install @sphereon/ssi-sdk.sd-jwt and configure agent for VCDM2 SD-JWT'),\n )\n }\n let identifier: IIdentifier\n try {\n identifier = await agent.didManagerGet({ did: issuer })\n } catch (e) {\n return Promise.reject(new Error(`invalid_argument: ${credential.issuer} must be a DID managed by this agent. ${e}`))\n }\n const managedIdentifier = await agent.identifierManagedGetByDid({ identifier: identifier.did, kmsKeyRef: keyRef })\n const key = await pickSigningKey({ identifier, kmsKeyRef: keyRef }, context)\n\n // TODO: Probably wise to give control to caller as well, as some key types allow multiple signature algos\n const alg = (await signatureAlgorithmFromKey({ key })) as string\n debug('Signing VC with', identifier.did, alg)\n credential.issuer = { id: identifier.did }\n\n const result = await context.agent.createSdJwtVc({\n type: 'vc+sd-jwt',\n credentialPayload: credential,\n resolution: managedIdentifier,\n disclosureFrame: args.opts?.disclosureFrame,\n })\n\n const jwt = result.credential.split('~')[0]\n\n // debug(jwt)\n const normalized = normalizeCredential(jwt)\n normalized.proof.jwt = result.credential\n return normalized\n }\n\n /** {@inheritdoc ICredentialVerifier.verifyCredential} */\n async verifyCredential(args: IVerifyCredentialVcdmArgs, context: VerifierAgentContext): Promise<IVerifyResult> {\n let { credential, policies /*...otherOptions*/ } = args\n const uniform = CredentialMapper.toUniformCredential(credential as OriginalVerifiableCredential)\n // let verifiedCredential: VerifiableCredential\n if (!isVcdm2Credential(uniform)) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential. Context: ' + uniform['@context']))\n } else if (!contextHasPlugin<ISDJwtPlugin>(context, 'createSdJwtVc')) {\n return Promise.reject(\n new Error('invalid_argument: SD-JWT plugin not available. Please install @sphereon/ssi-sdk.sd-jwt and configure agent for VCDM2 SD-JWT'),\n )\n }\n let verificationResult: IVerifyResult = { verified: false }\n let jwt: string | undefined = typeof credential === 'string' ? credential : asArray(uniform.proof)?.[0]?.jwt\n if (!jwt) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential in JOSE format (string)'))\n }\n\n try {\n const result = await context.agent.verifySdJwtVc({ credential: jwt })\n if (result.payload) {\n verificationResult = {\n verified: true,\n results: [\n {\n credential: credential as OriginalVerifiableCredential,\n verified: true,\n log: [\n {\n id: 'valid_signature',\n valid: true,\n },\n {\n id: 'issuer_did_resolves',\n valid: true,\n },\n ],\n },\n ],\n }\n }\n } catch (e) {\n verificationResult = { verified: false, error: { message: e.message, errorCode: e.name } }\n }\n\n policies = {\n ...policies,\n nbf: policies?.nbf ?? policies?.issuanceDate ?? policies?.validFrom,\n iat: policies?.iat ?? policies?.issuanceDate ?? policies?.validFrom,\n exp: policies?.exp ?? policies?.expirationDate ?? policies?.validUntil,\n aud: policies?.aud ?? policies?.audience,\n }\n verificationResult = await verifierSignature({ jwt: jwt.split('~')[0], policies }, context)\n return verificationResult\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiablePresentation} */\n async createVerifiablePresentation(args: ICreateVerifiablePresentationLDArgs, context: IVcdmIssuerAgentContext): Promise<VerifiablePresentationSP> {\n const { presentation, holder } = preProcessPresentation(args)\n let { domain, challenge, keyRef /* removeOriginalFields, keyRef, now, ...otherOptions*/ } = args\n\n const agent = assertContext(context).agent\n\n const managedIdentifier = await agent.identifierManagedGetByDid({ identifier: holder, kmsKeyRef: keyRef })\n const identifier = managedIdentifier.identifier\n const key = await pickSigningKey(\n {\n identifier: managedIdentifier.identifier,\n kmsKeyRef: managedIdentifier.kmsKeyRef,\n },\n context,\n )\n\n debug('Signing VC with', identifier.did)\n let alg = 'ES256'\n if (key.type === 'Ed25519') {\n alg = 'EdDSA'\n } else if (key.type === 'Secp256k1') {\n alg = 'ES256K'\n }\n\n const header: JwsHeader = {\n kid: key.meta.verificationMethod.id ?? key.kid,\n alg,\n typ: 'vp+jwt',\n cty: 'vp',\n }\n const payload: JwsPayload = {\n ...presentation,\n ...(domain && { aud: domain }),\n ...(challenge && { nonce: challenge }),\n }\n\n const jwt = await agent.jwtCreateJwsCompactSignature({\n mode: 'did',\n issuer: managedIdentifier,\n payload,\n protectedHeader: header,\n clientIdScheme: 'did',\n })\n\n debug(jwt)\n return normalizePresentation(jwt.jwt)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.verifyPresentation} */\n async verifyPresentation(args: IVerifyPresentationLDArgs, context: VerifierAgentContext): Promise<IVerifyResult> {\n let { presentation, domain, challenge, fetchRemoteContexts, policies, ...otherOptions } = args\n let jwt: string\n if (typeof presentation === 'string') {\n jwt = presentation\n } else {\n jwt = asArray(presentation.proof)[0].jwt\n }\n const resolver = {\n resolve: (didUrl: string) =>\n context.agent.resolveDid({\n didUrl,\n options: otherOptions?.resolutionOptions,\n }),\n } as Resolvable\n\n let audience = domain\n if (!audience) {\n const { payload } = await decodeJWT(jwt)\n if (payload.aud) {\n // automatically add a managed DID as audience if one is found\n const intendedAudience = asArray(payload.aud)\n const managedDids = await context.agent.didManagerFind()\n const filtered = managedDids.filter((identifier) => intendedAudience.includes(identifier.did))\n if (filtered.length > 0) {\n audience = filtered[0].did\n }\n }\n }\n\n let message, errorCode\n try {\n const result = await verifyPresentationJWT(jwt, resolver, {\n challenge,\n domain,\n audience,\n policies: {\n ...policies,\n nbf: policies?.nbf ?? policies?.issuanceDate,\n iat: policies?.iat ?? policies?.issuanceDate,\n exp: policies?.exp ?? policies?.expirationDate,\n aud: policies?.aud ?? policies?.audience,\n },\n ...otherOptions,\n })\n if (result) {\n /**\n * {id: 'valid_signature', valid: true},\n * // {id: 'issuer_did_resolves', valid: true},\n * // {id: 'expiration', valid: true},\n * // {id: 'revocation_status', valid: true},\n * // {id: 'suspension_status', valid: true}\n */\n return {\n verified: true,\n results: [\n {\n verified: true,\n presentation: result.verifiablePresentation,\n log: [\n {\n id: 'valid_signature',\n valid: true,\n },\n ],\n },\n ],\n } satisfies IVerifyResult\n }\n } catch (e: any) {\n message = e.message\n errorCode = e.errorCode\n }\n return {\n verified: false,\n error: {\n message,\n errorCode: errorCode ? errorCode : message?.split(':')[0],\n },\n }\n }\n\n /**\n * Checks if a key is suitable for signing JWT payloads.\n * @param key - the key to check\n * @param context - the Veramo agent context, unused here\n *\n * @beta\n */\n matchKeyForJWT(key: IKey): boolean {\n switch (key.type) {\n case 'Ed25519':\n case 'Secp256r1':\n return true\n case 'Secp256k1':\n return intersect(key.meta?.algorithms ?? [], ['ES256K', 'ES256K-R']).length > 0\n default:\n return false\n }\n }\n\n wrapSigner(context: IAgentContext<Pick<IKeyManager, 'keyManagerSign'>>, key: IKey, algorithm?: string) {\n return async (data: string | Uint8Array): Promise<string> => {\n const result = await context.agent.keyManagerSign({ keyRef: key.kid, data: <string>data, algorithm })\n return result\n }\n }\n}\n\nexport async function verifierSignature(\n { jwt, policies }: { jwt: string; policies: VerificationPolicies /*resolver: Resolvable*/ },\n verifierContext: VerifierAgentContext,\n): Promise<IVerifyResult> {\n let credIssuer: string | undefined = undefined\n const context = assertContext(verifierContext)\n const agent = context.agent\n const { payload, header /*signature, data*/ } = decodeJWT(jwt)\n\n\n\n if (!payload.issuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n const issuer = getIssuerFromSdJwt(payload)\n if (issuer === SELF_ISSUED_V2 || issuer === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.credentialSubject.id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT credentialSubject.id is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n credIssuer = payload.sub\n } else {\n credIssuer = (header.kid || '').split('#')[0]\n }\n } else if (issuer === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n credIssuer = payload.did\n } else if (!issuer && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n credIssuer = payload.client_id\n } else if (issuer?.indexOf('did:') === 0) {\n credIssuer = issuer\n } else if (header.kid?.indexOf('did:') === 0) {\n // OID4VCI expects iss to be the client and kid, to be the DID VM\n credIssuer = (header.kid || '').split('#')[0]\n } else if (typeof payload.issuer === 'string') {\n credIssuer = payload.issuer\n } else if (payload.issuer?.id) {\n credIssuer = payload.issuer.id\n }\n\n if (!credIssuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n let resolution: ExternalIdentifierResult | undefined = undefined\n try {\n resolution = await agent.identifierExternalResolve({ identifier: credIssuer })\n } catch (e: any) {}\n const credential = CredentialMapper.toUniformCredential(jwt)\n\n const validFromError =\n policies.nbf !== false &&\n policies.iat !== false &&\n 'validFrom' in credential &&\n !!credential.validFrom &&\n Date.parse(credential.validFrom) > new Date().getTime()\n const expired =\n policies.exp !== false && 'validUntil' in credential && !!credential.validUntil && Date.parse(credential.validUntil) < new Date().getTime()\n\n const didOpts = { method: 'did', identifier: credIssuer } satisfies ExternalIdentifierDidOpts\n const jwtResult = await agent.jwtVerifyJwsSignature({\n jws: jwt,\n // @ts-ignore\n jwk: resolution?.jwks[0].jwk,\n opts: { ...(isDidIdentifier(credIssuer) && { did: didOpts }) },\n })\n const error = jwtResult.error || expired || !resolution\n const errorMessage = expired\n ? 'Credential is expired'\n : validFromError\n ? 'Credential is not valid yet'\n : !resolution\n ? `Issuer ${credIssuer} could not be resolved`\n : jwtResult.message\n\n if (error) {\n const log = [\n {\n id: 'valid_signature',\n valid: !jwtResult.error,\n },\n { id: 'issuer_did_resolves', valid: resolution != undefined },\n { id: 'validFrom', valid: policies.nbf !== false && !validFromError },\n { id: 'expiration', valid: policies.exp !== false && !expired },\n ]\n return {\n verified: false,\n error: { message: errorMessage, errorCode: jwtResult.name },\n log,\n results: [\n {\n verified: false,\n credential: jwt,\n log,\n error: { message: errorMessage, errorCode: jwtResult.name },\n },\n ],\n payload,\n didResolutionResult: resolution,\n jwt,\n } satisfies IVerifyResult\n }\n\n const log = [\n {\n id: 'valid_signature',\n valid: true,\n },\n {\n id: 'issuer_did_resolves',\n valid: true,\n },\n {\n id: 'validFrom',\n valid: true,\n },\n {\n id: 'expiration',\n valid: true,\n },\n ]\n return {\n verified: true,\n log,\n results: [\n {\n verified: true,\n credential,\n log,\n },\n ],\n payload,\n didResolutionResult: resolution,\n jwt,\n } satisfies IVerifyResult\n}\n\n/*\nexport async function verifyDIDJWT(\n jwt: string,\n options: JWTVerifyOptions = {\n resolver: undefined,\n auth: undefined,\n audience: undefined,\n callbackUrl: undefined,\n skewTime: undefined,\n proofPurpose: undefined,\n policies: {},\n },\n verifierContext: VerifierAgentContext,\n): Promise<JWTVerified> {\n const context = assertContext(verifierContext)\n const agent = context.agent\n if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n const { payload, header, signature, data }: JWTDecoded = decodeJWT(jwt)\n const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n ? options.auth\n ? 'authentication'\n : undefined\n : options.proofPurpose\n\n let credIssuer: string | undefined = undefined\n\n if (!payload.iss && !payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n\n if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.sub) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n credIssuer = payload.sub\n } else {\n credIssuer = (header.kid || '').split('#')[0]\n }\n } else if (payload.iss === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n credIssuer = payload.did\n } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n credIssuer = payload.client_id\n } else if (payload.iss?.indexOf('did:') === 0) {\n credIssuer = payload.iss\n } else if (header.kid?.indexOf('did:') === 0) {\n // OID4VCI expects iss to be the client and kid, to be the DID VM\n credIssuer = (header.kid || '').split('#')[0]\n } else if (payload.iss) {\n credIssuer = payload.iss\n }\n\n if (!credIssuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n\n const resolution = await agent.identifierExternalResolve({ identifier: credIssuer })\n\n const didOpts = { method: 'did', identifier: credIssuer } satisfies ExternalIdentifierDidOpts\n const jwtResult = await agent.jwtVerifyJwsSignature({\n jws: jwt,\n // @ts-ignore\n jwk: resolution.jwks[0],\n opts: { ...(isDidIdentifier(credIssuer) && { did: didOpts }) },\n })\n\n if (jwtResult.error) {\n return Promise.reject(Error(`Error validating credential: ${jwtResult.error}`))\n }\n const { didResolutionResult, authenticators, issuer }: DIDAuthenticator = await resolveAuthenticator(\n options.resolver,\n header.alg,\n credIssuer,\n proofPurpose,\n )\n const signer: VerificationMethod = verifyJWSDecoded({ header, data, signature } as JWSDecoded, authenticators)\n const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n if (signer) {\n const nowSkewed = now + skewTime\n if (options.policies?.nbf !== false && payload.nbf) {\n if (payload.nbf > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n }\n } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n }\n if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n }\n if (options.policies?.aud !== false && payload.aud) {\n if (!options.audience && !options.callbackUrl) {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`)\n }\n const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n const matchedAudience = audArray.find((item: any) => options.audience === item || options.callbackUrl === item)\n\n if (typeof matchedAudience === 'undefined') {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n }\n }\n return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n }\n throw new Error(\n `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`,\n )\n}\n\nfunction verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n return signer\n}\n\n\nexport function validateCredentialPayload(payload: CredentialPayload): void {\n validateContext(asArray(payload['@context']))\n validateVcType(payload.type)\n validateCredentialSubject(payload.credentialSubject)\n if (payload.validFrom) validateTimestamp(payload.validFrom)\n if (payload.validUntil) validateTimestamp(payload.validUntil)\n}\n\nexport function validateContext(value: string | string[]): void {\n const input = asArray(value)\n if (input.length < 1 || input.indexOf(VCDM_CREDENTIAL_CONTEXT_V2) === -1) {\n throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: @context is missing default context \"${VCDM_CREDENTIAL_CONTEXT_V2}\"`)\n }\n}\n*/\nfunction assertContext(\n context: IVcdmIssuerAgentContext | IVcdmVerifierAgentContext,\n): IAgentContext<\n IResolver & IDIDManager & Pick<IKeyManager, 'keyManagerGet' | 'keyManagerSign' | 'keyManagerVerify'> & IJwtService & IIdentifierResolution\n> {\n if (!contextHasPlugin<IJwtService>(context, 'jwtPrepareJws')) {\n throw Error(\n 'JwtService plugin not found, which is required for JWT signing in the VCDM2 SD-JWT credential provider. Please add the JwtService plugin to your agent configuration.',\n )\n } else if (!contextHasPlugin<IIdentifierResolution>(context, 'identifierManagedGet')) {\n throw Error(\n 'Identifier resolution plugin not found, which is required for JWT signing in the VCDM2 SD-JWT credential provider. Please add the JwtService plugin to your agent configuration.',\n )\n }\n return context as IAgentContext<\n IResolver & IDIDManager & Pick<IKeyManager, 'keyManagerGet' | 'keyManagerSign' | 'keyManagerVerify'> & IJwtService & IIdentifierResolution\n >\n}\n","import canonicalizeData from 'canonicalize'\nimport { type DIDDocument, type DIDResolutionResult, parse, type ParsedDID, type Resolvable, type VerificationMethod } from 'did-resolver'\nimport SignerAlg from './SignerAlgorithm'\nimport { decodeBase64url, type EcdsaSignature, encodeBase64url, type KNOWN_JWA, SUPPORTED_PUBLIC_KEY_TYPES } from './util'\nimport VerifierAlgorithm from './VerifierAlgorithm'\nimport { JWT_ERROR } from 'did-jwt'\n\nexport type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>\nexport type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>\n\nexport type ProofPurposeTypes =\n | 'assertionMethod'\n | 'authentication'\n // | 'keyAgreement' // keyAgreement VerificationMethod should not be used for signing\n | 'capabilityDelegation'\n | 'capabilityInvocation'\n\nexport interface JWTOptions {\n issuer: string\n signer: Signer\n /**\n * @deprecated Please use `header.alg` to specify the JWT algorithm.\n */\n alg?: string\n expiresIn?: number\n canonicalize?: boolean\n}\n\nexport interface JWTVerifyOptions {\n /** @deprecated Please use `proofPurpose: 'authentication' instead` */\n auth?: boolean\n audience?: string\n callbackUrl?: string\n resolver?: Resolvable\n skewTime?: number\n /** See https://www.w3.org/TR/did-spec-registries/#verification-relationships */\n proofPurpose?: ProofPurposeTypes\n policies?: JWTVerifyPolicies\n didAuthenticator?: DIDAuthenticator\n}\n\n/**\n * Overrides the different types of checks performed on the JWT besides the signature check\n */\nexport interface JWTVerifyPolicies {\n // overrides the timestamp against which the validity interval is checked\n now?: number\n // when set to false, the timestamp checks ignore the Not Before(`nbf`) property\n nbf?: boolean\n // when set to false, the timestamp checks ignore the Issued At(`iat`) property\n iat?: boolean\n // when set to false, the timestamp checks ignore the Expires At(`exp`) property\n exp?: boolean\n // when set to false, the JWT audience check is skipped\n aud?: boolean\n}\n\nexport interface JWSCreationOptions {\n canonicalize?: boolean\n}\n\nexport interface DIDAuthenticator {\n authenticators: VerificationMethod[]\n issuer: string\n didResolutionResult: DIDResolutionResult\n}\n\nexport interface JWTHeader {\n typ: 'JWT'\n alg: string\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any\n}\n\nexport interface JWTPayload {\n iss?: string\n sub?: string\n aud?: string | string[]\n iat?: number\n nbf?: number\n exp?: number\n rexp?: number\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any\n}\n\nexport interface JWTDecoded {\n header: JWTHeader\n payload: JWTPayload\n signature: string\n data: string\n}\n\nexport interface JWSDecoded {\n header: JWTHeader\n payload: string\n signature: string\n data: string\n}\n\n/**\n * Result object returned by {@link verifyJWT}\n */\nexport interface JWTVerified {\n /**\n * Set to true for a JWT that passes all the required checks minus any verification overrides.\n */\n verified: true\n\n /**\n * The decoded JWT payload\n */\n payload: Partial<JWTPayload>\n\n /**\n * The result of resolving the issuer DID\n */\n didResolutionResult: DIDResolutionResult\n\n /**\n * the issuer DID\n */\n issuer: string\n\n /**\n * The public key of the issuer that matches the JWT signature\n */\n signer: VerificationMethod\n\n /**\n * The original JWT that was verified\n */\n jwt: string\n\n /**\n * Any overrides that were used during verification\n */\n policies?: JWTVerifyPolicies\n}\n\nexport const SELF_ISSUED_V2 = 'https://self-issued.me/v2'\nexport const SELF_ISSUED_V2_VC_INTEROP = 'https://self-issued.me/v2/openid-vc' // https://identity.foundation/jwt-vc-presentation-profile/#id-token-validation\nexport const SELF_ISSUED_V0_1 = 'https://self-issued.me'\n\ntype LegacyVerificationMethod = { publicKey?: string }\n\nconst defaultAlg: KNOWN_JWA = 'ES256K'\nconst DID_JSON = 'application/did+json'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction encodeSection(data: any, shouldCanonicalize = false): string {\n if (shouldCanonicalize) {\n return encodeBase64url(<string>canonicalizeData(data))\n } else {\n return encodeBase64url(JSON.stringify(data))\n }\n}\n\nexport const NBF_SKEW = 300\n\nfunction decodeJWS(jws: string): JWSDecoded {\n const parts = jws.match(/^([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)$/)\n if (parts) {\n return {\n header: JSON.parse(decodeBase64url(parts[1])),\n payload: parts[2],\n signature: parts[3],\n data: `${parts[1]}.${parts[2]}`,\n }\n }\n throw new Error('invalid_argument: Incorrect format JWS')\n}\n\n/**\n * Decodes a JWT and returns an object representing the payload\n *\n * @example\n * decodeJWT('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJpYXQiOjE1...')\n *\n * @param {String} jwt a JSON Web Token to verify\n * @param {Object} [recurse] whether to recurse into the payload to decode any nested JWTs\n * @return {Object} a JS object representing the decoded JWT\n */\nexport function decodeJWT(jwt: string, recurse = true): JWTDecoded {\n if (!jwt) throw new Error('invalid_argument: no JWT passed into decodeJWT')\n try {\n const jws = decodeJWS(jwt)\n const decodedJwt: JWTDecoded = Object.assign(jws, { payload: JSON.parse(decodeBase64url(jws.payload)) })\n const iss = decodedJwt.payload.iss\n\n if (decodedJwt.header.cty === 'JWT' && recurse) {\n const innerDecodedJwt = decodeJWT(decodedJwt.payload.jwt)\n\n if (innerDecodedJwt.payload.iss !== iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n return innerDecodedJwt\n }\n return decodedJwt\n } catch (e) {\n throw new Error(`invalid_argument: ${JWT_ERROR.INVALID_JWT}: ${e}`)\n }\n}\n\n/**\n * Creates a signed JWS given a payload, a signer, and an optional header.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * const jws = await createJWS({ my: 'payload' }, signer)\n *\n * @param {Object} payload payload object\n * @param {Signer} signer a signer, see `ES256KSigner or `EdDSASigner`\n * @param {Object} header optional object to specify or customize the JWS header\n * @param {Object} options can be used to trigger automatic canonicalization of header and\n * payload properties\n * @return {Promise<string>} a Promise which resolves to a JWS string or rejects with an error\n */\nexport async function createJWS(\n payload: string | Partial<JWTPayload>,\n signer: Signer,\n header: Partial<JWTHeader> = {},\n options: JWSCreationOptions = {},\n): Promise<string> {\n if (!header.alg) header.alg = defaultAlg\n const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload, options.canonicalize)\n const signingInput: string = [encodeSection(header, options.canonicalize), encodedPayload].join('.')\n\n const jwtSigner: SignerAlgorithm = SignerAlg(header.alg)\n const signature: string = await jwtSigner(signingInput, signer)\n\n // JWS Compact Serialization\n // https://www.rfc-editor.org/rfc/rfc7515#section-7.1\n return [signingInput, signature].join('.')\n}\n\n/**\n * Creates a signed JWT given an address which becomes the issuer, a signer, and a payload for which the signature is\n * over.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n * ...\n * })\n *\n * @param {Object} payload payload object\n * @param {Object} [options] an unsigned credential object\n * @param {String} options.issuer The DID of the issuer (signer) of JWT\n * @param {String} options.alg [DEPRECATED] The JWT signing algorithm to use. Supports:\n * [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n * @param {Signer} options.signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n * @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing\n * @param {Object} header optional object to specify or customize the JWT header\n * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or\n * rejects with an error\n */\nexport async function createJWT(\n payload: Partial<JWTPayload>,\n { issuer, signer, alg, expiresIn, canonicalize }: JWTOptions,\n header: Partial<JWTHeader> = {},\n): Promise<string> {\n if (!signer) throw new Error('missing_signer: No Signer functionality has been configured')\n if (!issuer) throw new Error('missing_issuer: No issuing DID has been configured')\n if (!header.typ) header.typ = 'JWT'\n if (!header.alg) header.alg = alg\n const timestamps: Partial<JWTPayload> = {\n iat: Math.floor(Date.now() / 1000),\n exp: undefined,\n }\n if (expiresIn) {\n if (typeof expiresIn === 'number') {\n timestamps.exp = <number>(payload.nbf || timestamps.iat) + Math.floor(expiresIn)\n } else {\n throw new Error('invalid_argument: JWT expiresIn is not a number')\n }\n }\n const fullPayload = { ...timestamps, ...payload, iss: issuer }\n return createJWS(fullPayload, signer, header, { canonicalize })\n}\n\n/**\n * Creates a multi-signature signed JWT given multiple issuers and their corresponding signers, and a payload for\n * which the signature is over.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n * ...\n * })\n *\n * @param {Object} payload payload object\n * @param {Object} [options] an unsigned credential object\n * @param {boolean} options.expiresIn optional flag to denote the expiration time\n * @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing\n * @param {Object[]} issuers array of the issuers, their signers and algorithms\n * @param {string} issuers[].issuer The DID of the issuer (signer) of JWT\n * @param {Signer} issuers[].signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n * @param {String} issuers[].alg [DEPRECATED] The JWT signing algorithm to use. Supports:\n * [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or\n * rejects with an error\n */\nexport async function createMultisignatureJWT(\n payload: Partial<JWTPayload>,\n { expiresIn, canonicalize }: Partial<JWTOptions>,\n issuers: { issuer: string; signer: Signer; alg: string }[],\n): Promise<string> {\n if (issuers.length === 0) throw new Error('invalid_argument: must provide one or more issuers')\n\n let payloadResult: Partial<JWTPayload> = payload\n\n let jwt = ''\n for (let i = 0; i < issuers.length; i++) {\n const issuer = issuers[i]\n\n const header: Partial<JWTHeader> = {\n typ: 'JWT',\n alg: issuer.alg,\n }\n\n // Create nested JWT\n // See Point 5 of https://www.rfc-editor.org/rfc/rfc7519#section-7.1\n // After the first JWT is created (the first JWS), the next JWT is created by inputting the previous JWT as the\n // payload\n if (i !== 0) {\n header.cty = 'JWT'\n }\n\n jwt = await createJWT(payloadResult, { ...issuer, canonicalize, expiresIn }, header)\n\n payloadResult = { jwt }\n }\n return jwt\n}\n\nexport function verifyJWTDecoded(\n { header, payload, data, signature }: JWTDecoded,\n pubKeys: VerificationMethod | VerificationMethod[],\n): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n\n const iss = payload.iss\n let recurse = true\n do {\n if (iss !== payload.iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n\n try {\n const result = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n\n return result\n } catch (e) {\n if (!(e as Error).message.startsWith(JWT_ERROR.INVALID_SIGNATURE)) throw e\n }\n\n // TODO probably best to create copy objects than replace reference objects\n if (header.cty !== 'JWT') {\n recurse = false\n } else {\n ;({ payload, header, signature, data } = decodeJWT(payload.jwt, false))\n }\n } while (recurse)\n\n throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: no matching public key found`)\n}\n\nexport function verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n return signer\n}\n\n/**\n * Verifies given JWS. If the JWS is valid, returns the public key that was\n * used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.\n *\n * @example\n * const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })\n *\n * @param {String} jws A JWS string to verify\n * @param {Array<VerificationMethod> | VerificationMethod} pubKeys The public keys used to verify the JWS\n * @return {VerificationMethod} The public key used to sign the JWS\n */\nexport function verifyJWS(jws: string, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n const jwsDecoded: JWSDecoded = decodeJWS(jws)\n return verifyJWSDecoded(jwsDecoded, pubKeys)\n}\n\n/**\n * Verifies given JWT. If the JWT is valid, the promise returns an object including the JWT, the payload of the JWT,\n * and the DID document of the issuer of the JWT.\n *\n * @example\n * ```ts\n * verifyJWT(\n * 'did:uport:eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....',\n * {audience: '5A8bRWU3F7j3REx3vkJ...', callbackUrl: 'https://...'}\n * ).then(obj => {\n * const did = obj.did // DID of signer\n * const payload = obj.payload\n * const doc = obj.didResolutionResult.didDocument // DID Document of issuer\n * const jwt = obj.jwt\n * const signerKeyId = obj.signer.id // ID of key in DID document that signed JWT\n * ...\n * })\n * ```\n *\n * @param {String} jwt a JSON Web Token to verify\n * @param {Object} [options] an unsigned credential object\n * @param {Boolean} options.auth Require signer to be listed in the authentication section of the\n * DID document (for Authentication purposes)\n * @param {String} options.audience DID of the recipient of the JWT\n * @param {String} options.callbackUrl callback url in JWT\n * @return {Promise<Object, Error>} a promise which resolves with a response object or rejects with an\n * error\n */\nexport async function verifyJWT(\n jwt: string,\n options: JWTVerifyOptions = {\n resolver: undefined,\n auth: undefined,\n audience: undefined,\n callbackUrl: undefined,\n skewTime: undefined,\n proofPurpose: undefined,\n policies: {},\n didAuthenticator: undefined,\n },\n): Promise<JWTVerified> {\n if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n const { payload, header /*, signature, data*/ }: JWTDecoded = decodeJWT(jwt, false)\n const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n ? options.auth\n ? 'authentication'\n : undefined\n : options.proofPurpose\n\n let didUrl: string | undefined\n\n if (!payload.iss && !payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n\n if (options.didAuthenticator) {\n didUrl = options.didAuthenticator.issuer\n } else if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.sub) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n didUrl = payload.sub\n } else {\n didUrl = (header.kid || '').split('#')[0]\n }\n } else if (payload.iss === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n didUrl = payload.did\n } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n didUrl = payload.client_id\n } else {\n didUrl = payload.iss\n }\n\n if (!didUrl) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n\n let authenticators: VerificationMethod[]\n let issuer: string\n let didResolutionResult: DIDResolutionResult\n if (options.didAuthenticator) {\n ;({ didResolutionResult, authenticators, issuer } = options.didAuthenticator)\n } else {\n ;({ didResolutionResult, authenticators, issuer } = await resolveAuthenticator(options.resolver, header.alg, didUrl, proofPurpose))\n // Add to options object for recursive reference\n options.didAuthenticator = { didResolutionResult, authenticators, issuer }\n }\n\n const { did } = parse(didUrl) as ParsedDID\n\n let signer: VerificationMethod | null = null\n\n if (did !== didUrl) {\n const authenticator = authenticators.find((auth) => auth.id === didUrl)\n if (!authenticator) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No authenticator found for did URL ${didUrl}`)\n }\n\n // signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n } else {\n let i = 0\n while (!signer && i < authenticators.length) {\n // const authenticator = authenticators[i]\n try {\n // signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n } catch (e) {\n if (!(e as Error).message.includes(JWT_ERROR.INVALID_SIGNATURE) || i === authenticators.length - 1) throw e\n }\n\n i++\n }\n }\n\n if (signer) {\n const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n\n const nowSkewed = now + skewTime\n if (options.policies?.nbf !== false && payload.nbf) {\n if (payload.nbf > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n }\n } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n }\n if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n }\n if (options.policies?.aud !== false && payload.aud) {\n if (!options.audience && !options.callbackUrl) {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`)\n }\n const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n const matchedAudience = audArray.find((item) => options.audience === item || options.callbackUrl === item)\n\n if (typeof matchedAudience === 'undefined') {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n }\n }\n\n return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n }\n throw new Error(\n `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`,\n )\n}\n\n/**\n * Resolves relevant public keys or other authenticating material used to verify signature from the DID document of\n * provided DID\n *\n * @example\n * ```ts\n * resolveAuthenticator(resolver, 'ES256K', 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX').then(obj => {\n * const payload = obj.payload\n * const profile = obj.profile\n * const jwt = obj.jwt\n * // ...\n * })\n * ```\n *\n * @param resolver - {Resolvable} a DID resolver function that can obtain the `DIDDocument` for the `issuer`\n * @param alg - {String} a JWT algorithm\n * @param issuer - {String} a Decentralized Identifier (DID) to lookup\n * @param proofPurpose - {ProofPurposeTypes} *Optional* Use the verificationMethod linked in that section of the\n * issuer DID document\n * @return {Promise<DIDAuthenticator>} a promise which resolves with an object containing an array of authenticators\n * or rejects with an error if none exist\n */\nexport async function resolveAuthenticator(\n resolver: Resolvable,\n alg: string,\n issuer: string,\n proofPurpose?: ProofPurposeTypes,\n): Promise<DIDAuthenticator> {\n const types: string[] = SUPPORTED_PUBLIC_KEY_TYPES[alg as KNOWN_JWA]\n if (!types || types.length === 0) {\n throw new Error(`${JWT_ERROR.NOT_SUPPORTED}: No supported signature types for algorithm ${alg}`)\n }\n let didResult: DIDResolutionResult\n\n const result = (await resolver.resolve(issuer, { accept: DID_JSON })) as unknown\n // support legacy resolvers that do not produce DIDResolutionResult\n if (Object.getOwnPropertyNames(result).indexOf('didDocument') === -1) {\n didResult = {\n didDocument: result as DIDDocument,\n didDocumentMetadata: {},\n didResolutionMetadata: { contentType: DID_JSON },\n }\n } else {\n didResult = result as DIDResolutionResult\n }\n\n if (didResult.didResolutionMetadata?.error || didResult.didDocument == null) {\n const { error, message } = didResult.didResolutionMetadata\n throw new Error(`${JWT_ERROR.RESOLVER_ERROR}: Unable to resolve DID document for ${issuer}: ${error}, ${message || ''}`)\n }\n\n const getPublicKeyById = (verificationMethods: VerificationMethod[], pubid?: string): VerificationMethod | null => {\n const filtered = verificationMethods.filter(({ id }) => pubid === id)\n return filtered.length > 0 ? filtered[0] : null\n }\n\n let publicKeysToCheck: VerificationMethod[] = [...(didResult?.didDocument?.verificationMethod || []), ...(didResult?.didDocument?.publicKey || [])]\n if (typeof proofPurpose === 'string') {\n // support legacy DID Documents that do not list assertionMethod\n if (proofPurpose.startsWith('assertion') && !Object.getOwnPropertyNames(didResult?.didDocument).includes('assertionMethod')) {\n didResult.didDocument = { ...(<DIDDocument>didResult.didDocument) }\n didResult.didDocument.assertionMethod = [...publicKeysToCheck.map((pk) => pk.id)]\n }\n\n publicKeysToCheck = (didResult.didDocument[proofPurpose] || [])\n .map((verificationMethod) => {\n if (typeof verificationMethod === 'string') {\n return getPublicKeyById(publicKeysToCheck, verificationMethod)\n } else if (typeof (<LegacyVerificationMethod>verificationMethod).publicKey === 'string') {\n // this is a legacy format\n return getPublicKeyById(publicKeysToCheck, (<LegacyVerificationMethod>verificationMethod).publicKey)\n } else {\n return <VerificationMethod>verificationMethod\n }\n })\n .filter((key) => key != null) as VerificationMethod[]\n }\n\n const authenticators: VerificationMethod[] = publicKeysToCheck.filter(({ type }) => types.find((supported) => supported === type))\n\n if (typeof proofPurpose === 'string' && (!authenticators || authenticators.length === 0)) {\n throw new Error(\n `${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys suitable for ${alg} with ${proofPurpose} purpose`,\n )\n }\n if (!authenticators || authenticators.length === 0) {\n throw new Error(`${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys for ${alg}`)\n }\n return { authenticators, issuer, didResolutionResult: didResult }\n}\n","// @ts-ignore\nimport * as u8a from 'uint8arrays'\n// const { concat, fromString, toString } = u8a\nimport { x25519 } from '@noble/curves/ed25519'\n\n// @ts-ignore\nimport { varint } from 'multiformats'\nimport { BaseName, decode, encode } from 'multibase'\nimport type { VerificationMethod } from 'did-resolver'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\n\n// const u8a = { toString, fromString, concat }\n\nexport interface EphemeralPublicKey {\n kty?: string\n //ECC\n crv?: string\n x?: string\n y?: string\n //RSA\n n?: string\n e?: string\n}\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport interface EcdsaSignature {\n r: string\n s: string\n recoveryParam?: number\n}\n\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport type ECDSASignature = {\n compact: Uint8Array\n recovery?: number\n}\n\nexport type JsonWebKey = {\n crv: string\n kty: string\n x?: string\n y?: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n}\n\nexport function bytesToBase64url(b: Uint8Array): string {\n return u8a.toString(b, 'base64url')\n}\n\nexport function base64ToBytes(s: string): Uint8Array {\n const inputBase64Url = s.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n return u8a.fromString(inputBase64Url, 'base64url')\n}\n\nexport function bytesToBase64(b: Uint8Array): string {\n return u8a.toString(b, 'base64pad')\n}\n\nexport function base58ToBytes(s: string): Uint8Array {\n return u8a.fromString(s, 'base58btc')\n}\n\nexport function bytesToBase58(b: Uint8Array): string {\n return u8a.toString(b, 'base58btc')\n}\n\nexport type KNOWN_JWA = 'ES256' | 'ES256K' | 'ES256K-R' | 'Ed25519' | 'EdDSA'\n\nexport type KNOWN_VERIFICATION_METHOD =\n | 'JsonWebKey2020'\n | 'Multikey'\n | 'Secp256k1SignatureVerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'Secp256k1VerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'EcdsaSecp256k1VerificationKey2019' // ES256K / ES256K-R\n | 'EcdsaPublicKeySecp256k1' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'EcdsaSecp256k1RecoveryMethod2020' // ES256K-R (ES256K also supported with 1 less bit of security)\n | 'EcdsaSecp256r1VerificationKey2019' // ES256 / P-256\n | 'Ed25519VerificationKey2018'\n | 'Ed25519VerificationKey2020'\n | 'ED25519SignatureVerification' // deprecated\n | 'ConditionalProof2022'\n | 'X25519KeyAgreementKey2019' // deprecated\n | 'X25519KeyAgreementKey2020'\n\nexport type KNOWN_KEY_TYPE = 'Secp256k1' | 'Ed25519' | 'X25519' | 'Bls12381G1' | 'Bls12381G2' | 'P-256'\n\nexport type PublicKeyTypes = Record<KNOWN_JWA, KNOWN_VERIFICATION_METHOD[]>\n\nexport const SUPPORTED_PUBLIC_KEY_TYPES: PublicKeyTypes = {\n ES256: ['JsonWebKey2020', 'Multikey', 'EcdsaSecp256r1VerificationKey2019'],\n ES256K: [\n 'EcdsaSecp256k1VerificationKey2019',\n /**\n * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n */\n 'EcdsaSecp256k1RecoveryMethod2020',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1VerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1SignatureVerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'EcdsaPublicKeySecp256k1',\n /**\n * TODO - support R1 key as well\n * 'ConditionalProof2022',\n */\n 'JsonWebKey2020',\n 'Multikey',\n ],\n 'ES256K-R': [\n 'EcdsaSecp256k1VerificationKey2019',\n /**\n * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n */\n 'EcdsaSecp256k1RecoveryMethod2020',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1VerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1SignatureVerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'EcdsaPublicKeySecp256k1',\n 'ConditionalProof2022',\n 'JsonWebKey2020',\n 'Multikey',\n ],\n Ed25519: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'JsonWebKey2020', 'Multikey'],\n EdDSA: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'JsonWebKey2020', 'Multikey'],\n}\n\nexport const VM_TO_KEY_TYPE: Record<KNOWN_VERIFICATION_METHOD, KNOWN_KEY_TYPE | undefined> = {\n Secp256k1SignatureVerificationKey2018: 'Secp256k1',\n Secp256k1VerificationKey2018: 'Secp256k1',\n EcdsaSecp256k1VerificationKey2019: 'Secp256k1',\n EcdsaPublicKeySecp256k1: 'Secp256k1',\n EcdsaSecp256k1RecoveryMethod2020: 'Secp256k1',\n EcdsaSecp256r1VerificationKey2019: 'P-256',\n Ed25519VerificationKey2018: 'Ed25519',\n Ed25519VerificationKey2020: 'Ed25519',\n ED25519SignatureVerification: 'Ed25519',\n X25519KeyAgreementKey2019: 'X25519',\n X25519KeyAgreementKey2020: 'X25519',\n ConditionalProof2022: undefined,\n JsonWebKey2020: undefined, // key type must be specified in the JWK\n Multikey: undefined, // key type must be extracted from the multicodec\n}\n\nexport type KNOWN_CODECS = 'ed25519-pub' | 'x25519-pub' | 'secp256k1-pub' | 'bls12_381-g1-pub' | 'bls12_381-g2-pub' | 'p256-pub'\n\n// this is from the multicodec table https://github.com/multiformats/multicodec/blob/master/table.csv\nexport const supportedCodecs: Record<KNOWN_CODECS, number> = {\n 'ed25519-pub': 0xed,\n 'x25519-pub': 0xec,\n 'secp256k1-pub': 0xe7,\n 'bls12_381-g1-pub': 0xea,\n 'bls12_381-g2-pub': 0xeb,\n 'p256-pub': 0x1200,\n}\n\nexport const CODEC_TO_KEY_TYPE: Record<KNOWN_CODECS, KNOWN_KEY_TYPE> = {\n 'bls12_381-g1-pub': 'Bls12381G1',\n 'bls12_381-g2-pub': 'Bls12381G2',\n 'ed25519-pub': 'Ed25519',\n 'p256-pub': 'P-256',\n 'secp256k1-pub': 'Secp256k1',\n 'x25519-pub': 'X25519',\n}\n\n/**\n * Extracts the raw byte representation of a public key from a VerificationMethod along with an inferred key type\n * @param pk a VerificationMethod entry from a DIDDocument\n * @return an object containing the `keyBytes` of the public key and an inferred `keyType`\n */\nexport function extractPublicKeyBytes(pk: VerificationMethod): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n if (pk.publicKeyBase58) {\n return {\n keyBytes: base58ToBytes(pk.publicKeyBase58),\n keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n }\n } else if (pk.publicKeyBase64) {\n return {\n keyBytes: base64ToBytes(pk.publicKeyBase64),\n keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n }\n } else if (pk.publicKeyHex) {\n return { keyBytes: hexToBytes(pk.publicKeyHex), keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return {\n keyBytes: secp256k1.ProjectivePoint.fromAffine({\n x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n }).toRawBytes(false),\n keyType: 'Secp256k1',\n }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return {\n keyBytes: p256.ProjectivePoint.fromAffine({\n x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n }).toRawBytes(false),\n keyType: 'P-256',\n }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === 'OKP' && ['Ed25519', 'X25519'].includes(pk.publicKeyJwk.crv ?? '') && pk.publicKeyJwk.x) {\n return { keyBytes: base64ToBytes(pk.publicKeyJwk.x), keyType: pk.publicKeyJwk.crv as KNOWN_KEY_TYPE }\n } else if (pk.publicKeyMultibase) {\n const { keyBytes, keyType } = multibaseToBytes(pk.publicKeyMultibase)\n return { keyBytes, keyType: keyType ?? VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n }\n return { keyBytes: new Uint8Array() }\n}\n\n/**\n * Encodes the given byte array to a multibase string (defaulting to base58btc).\n * If a codec is provided, the corresponding multicodec prefix will be added.\n *\n * @param b - the Uint8Array to be encoded\n * @param base - the base to use for encoding (defaults to base58btc)\n * @param codec - the codec to use for encoding (defaults to no codec)\n *\n * @returns the multibase encoded string\n *\n * @public\n */\nexport function bytesToMultibase(b: Uint8Array, base: BaseName = 'base58btc', codec?: keyof typeof supportedCodecs | number): string {\n if (!codec) {\n return u8a.toString(encode(base, b), 'utf-8')\n } else {\n const codecCode = typeof codec === 'string' ? supportedCodecs[codec] : codec\n const prefixLength = varint.encodingLength(codecCode)\n const multicodecEncoding = new Uint8Array(prefixLength + b.length)\n varint.encodeTo(codecCode, multicodecEncoding) // set prefix\n multicodecEncoding.set(b, prefixLength) // add the original bytes\n return u8a.toString(encode(base, multicodecEncoding), 'utf-8')\n }\n}\n\n/**\n * Converts a multibase string to the Uint8Array it represents.\n * This method will assume the byte array that is multibase encoded is a multicodec and will attempt to decode it.\n *\n * @param s - the string to be converted\n *\n * @throws if the string is not formatted correctly.\n *\n * @public\n */\nexport function multibaseToBytes(s: string): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n const bytes = decode(s)\n\n // look for known key lengths first\n // Ed25519/X25519, secp256k1/P256 compressed or not, BLS12-381 G1/G2 compressed\n if ([32, 33, 48, 64, 65, 96].includes(bytes.length)) {\n return { keyBytes: bytes }\n }\n\n // then assume multicodec, otherwise return the bytes\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [codec, length] = varint.decode(bytes)\n const possibleCodec: string | undefined = Object.entries(supportedCodecs).filter(([, code]) => code === codec)?.[0][0] ?? ''\n return { keyBytes: bytes.slice(length), keyType: CODEC_TO_KEY_TYPE[possibleCodec as KNOWN_CODECS] }\n } catch (e) {\n // not a multicodec, return the bytes\n return { keyBytes: bytes }\n }\n}\n\nexport function hexToBytes(s: string, minLength?: number): Uint8Array {\n let input = s.startsWith('0x') ? s.substring(2) : s\n\n if (input.length % 2 !== 0) {\n input = `0${input}`\n }\n\n if (minLength) {\n const paddedLength = Math.max(input.length, minLength * 2)\n input = input.padStart(paddedLength, '00')\n }\n\n return u8a.fromString(input.toLowerCase(), 'base16')\n}\n\nexport function encodeBase64url(s: string): string {\n return bytesToBase64url(u8a.fromString(s))\n}\n\nexport function decodeBase64url(s: string): string {\n return u8a.toString(base64ToBytes(s))\n}\n\nexport function bytesToHex(b: Uint8Array): string {\n return u8a.toString(b, 'base16')\n}\n\nexport function bytesToBigInt(b: Uint8Array): bigint {\n return BigInt(`0x` + u8a.toString(b, 'base16'))\n}\n\nexport function bigintToBytes(n: bigint, minLength?: number): Uint8Array {\n return hexToBytes(n.toString(16), minLength)\n}\n\nexport function stringToBytes(s: string): Uint8Array {\n return u8a.fromString(s, 'utf-8')\n}\n\nexport function toJose({ r, s, recoveryParam }: EcdsaSignature, recoverable?: boolean): string {\n const jose = new Uint8Array(recoverable ? 65 : 64)\n jose.set(u8a.fromString(r, 'base16'), 0)\n jose.set(u8a.fromString(s, 'base16'), 32)\n if (recoverable) {\n if (typeof recoveryParam === 'undefined') {\n throw new Error('Signer did not return a recoveryParam')\n }\n jose[64] = <number>recoveryParam\n }\n return bytesToBase64url(jose)\n}\n\nexport function fromJose(signature: string): { r: string; s: string; recoveryParam?: number } {\n const signatureBytes: Uint8Array = base64ToBytes(signature)\n if (signatureBytes.length < 64 || signatureBytes.length > 65) {\n throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`)\n }\n const r = bytesToHex(signatureBytes.slice(0, 32))\n const s = bytesToHex(signatureBytes.slice(32, 64))\n const recoveryParam = signatureBytes.length === 65 ? signatureBytes[64] : undefined\n return { r, s, recoveryParam }\n}\n\nexport function toSealed(ciphertext: string, tag?: string): Uint8Array {\n return u8a.concat([base64ToBytes(ciphertext), tag ? base64ToBytes(tag) : new Uint8Array(0)])\n}\n\nexport function leftpad(data: string, size = 64): string {\n if (data.length === size) return data\n return '0'.repeat(size - data.length) + data\n}\n\n/**\n * Generate random x25519 key pair.\n */\nexport function generateKeyPair(): { secretKey: Uint8Array; publicKey: Uint8Array } {\n const secretKey = x25519.utils.randomPrivateKey()\n const publicKey = x25519.getPublicKey(secretKey)\n return {\n secretKey: secretKey,\n publicKey: publicKey,\n }\n}\n\n/**\n * Generate private-public x25519 key pair from `seed`.\n */\nexport function generateKeyPairFromSeed(seed: Uint8Array): { secretKey: Uint8Array; publicKey: Uint8Array } {\n if (seed.length !== 32) {\n throw new Error(`x25519: seed must be ${32} bytes`)\n }\n return {\n publicKey: x25519.getPublicKey(seed),\n secretKey: seed,\n }\n}\n/*\n\nexport function genX25519EphemeralKeyPair(): EphemeralKeyPair {\n const epk = generateKeyPair()\n return {\n publicKeyJWK: { kty: 'OKP', crv: 'X25519', x: bytesToBase64url(epk.publicKey) },\n secretKey: epk.secretKey,\n }\n}\n*/\n\n/**\n * Checks if a variable is defined and not null.\n * After this check, typescript sees the variable as defined.\n *\n * @param arg - The input to be verified\n *\n * @returns true if the input variable is defined.\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n return arg !== null && typeof arg !== 'undefined'\n}\n","import type { Signer, SignerAlgorithm } from './JWT'\nimport { type EcdsaSignature, fromJose, toJose } from './util'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction instanceOfEcdsaSignature(object: any): object is EcdsaSignature {\n return typeof object === 'object' && 'r' in object && 's' in object\n}\n\nexport function ES256SignerAlg(): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (instanceOfEcdsaSignature(signature)) {\n return toJose(signature)\n } else {\n return signature\n }\n }\n}\n\nexport function ES256KSignerAlg(recoverable?: boolean): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (instanceOfEcdsaSignature(signature)) {\n return toJose(signature, recoverable)\n } else {\n if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') {\n throw new Error(`not_supported: ES256K-R not supported when signer doesn't provide a recovery param`)\n }\n return signature\n }\n }\n}\n\nexport function Ed25519SignerAlg(): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (!instanceOfEcdsaSignature(signature)) {\n return signature\n } else {\n throw new Error('invalid_config: expected a signer function that returns a string instead of signature object')\n }\n }\n}\n\ninterface SignerAlgorithms {\n [alg: string]: SignerAlgorithm\n}\n\nconst algorithms: SignerAlgorithms = {\n ES256: ES256SignerAlg(),\n ES256K: ES256KSignerAlg(),\n // This is a non-standard algorithm but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/146\n 'ES256K-R': ES256KSignerAlg(true),\n // This is actually incorrect but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/130\n Ed25519: Ed25519SignerAlg(),\n EdDSA: Ed25519SignerAlg(),\n}\n\nfunction SignerAlg(alg: string): SignerAlgorithm {\n const impl: SignerAlgorithm = algorithms[alg]\n if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n return impl\n}\n\nexport default SignerAlg\n","import { toEthereumAddress } from 'did-jwt'\nimport type { VerificationMethod } from 'did-resolver'\nimport { base64ToBytes, bytesToHex, type EcdsaSignature, type ECDSASignature, extractPublicKeyBytes, type KNOWN_JWA, stringToBytes } from './util'\n// @ts-ignore\n// import { verifyBlockchainAccountId } from 'did-jwt'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\nimport { ed25519 } from '@noble/curves/ed25519'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nimport { sha256 as hash } from '@noble/hashes/sha256'\n\nexport function sha256(payload: string | Uint8Array): Uint8Array {\n const data = typeof payload === 'string' ? u8a.fromString(payload) : payload\n return hash(data)\n}\n// converts a JOSE signature to it's components\nexport function toSignatureObject(signature: string, recoverable = false): EcdsaSignature {\n const rawSig: Uint8Array = base64ToBytes(signature)\n if (rawSig.length !== (recoverable ? 65 : 64)) {\n throw new Error('wrong signature length')\n }\n const r: string = bytesToHex(rawSig.slice(0, 32))\n const s: string = bytesToHex(rawSig.slice(32, 64))\n const sigObj: EcdsaSignature = { r, s }\n if (recoverable) {\n sigObj.recoveryParam = rawSig[64]\n }\n return sigObj\n}\n\nexport function toSignatureObject2(signature: string, recoverable = false): ECDSASignature {\n const bytes = base64ToBytes(signature)\n if (bytes.length !== (recoverable ? 65 : 64)) {\n throw new Error('wrong signature length')\n }\n return {\n compact: bytes.slice(0, 64),\n recovery: bytes[64],\n }\n}\n\nexport function verifyES256(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const hash = sha256(data)\n const sig = p256.Signature.fromCompact(toSignatureObject2(signature).compact)\n const fullPublicKeys = authenticators.filter((a: VerificationMethod) => !a.ethereumAddress && !a.blockchainAccountId)\n\n const signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n try {\n const { keyBytes } = extractPublicKeyBytes(pk)\n return p256.verify(sig, hash, keyBytes)\n } catch (err) {\n return false\n }\n })\n\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\nexport function verifyES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const hash = sha256(data)\n const signatureNormalized = secp256k1.Signature.fromCompact(base64ToBytes(signature)).normalizeS()\n const fullPublicKeys = authenticators.filter((a: VerificationMethod) => {\n return !a.ethereumAddress && !a.blockchainAccountId\n })\n const blockchainAddressKeys = authenticators.filter((a: VerificationMethod) => {\n return a.ethereumAddress || a.blockchainAccountId\n })\n\n let signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n try {\n const { keyBytes } = extractPublicKeyBytes(pk)\n return secp256k1.verify(signatureNormalized, hash, keyBytes)\n } catch (err) {\n return false\n }\n })\n\n if (!signer && blockchainAddressKeys.length > 0) {\n signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys)\n }\n\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\nexport function verifyRecoverableES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const signatures: ECDSASignature[] = []\n if (signature.length > 86) {\n signatures.push(toSignatureObject2(signature, true))\n } else {\n const so = toSignatureObject2(signature, false)\n signatures.push({ ...so, recovery: 0 })\n signatures.push({ ...so, recovery: 1 })\n }\n const hash = sha256(data)\n\n const checkSignatureAgainstSigner = (sigObj: ECDSASignature): VerificationMethod | undefined => {\n const signature = secp256k1.Signature.fromCompact(sigObj.compact).addRecoveryBit(sigObj.recovery || 0)\n const recoveredPublicKey = signature.recoverPublicKey(hash)\n const recoveredAddress = toEthereumAddress(recoveredPublicKey.toHex(false)).toLowerCase()\n const recoveredPublicKeyHex = recoveredPublicKey.toHex(false)\n const recoveredCompressedPublicKeyHex = recoveredPublicKey.toHex(true)\n\n return authenticators.find((a: VerificationMethod) => {\n const { keyBytes } = extractPublicKeyBytes(a)\n const keyHex = bytesToHex(keyBytes)\n return (\n keyHex === recoveredPublicKeyHex ||\n keyHex === recoveredCompressedPublicKeyHex ||\n a.ethereumAddress?.toLowerCase() === recoveredAddress ||\n a.blockchainAccountId?.split('@eip155')?.[0].toLowerCase() === recoveredAddress //|| // CAIP-2\n // verifyBlockchainAccountId(recoveredPublicKeyHex, a.blockchainAccountId) // CAIP-10\n )\n })\n }\n\n // Find first verification method\n for (const signature of signatures) {\n const verificationMethod = checkSignatureAgainstSigner(signature)\n if (verificationMethod) return verificationMethod\n }\n // If no one found matching\n throw new Error('invalid_signature: Signature invalid for JWT')\n}\n\nexport function verifyEd25519(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const clear = stringToBytes(data)\n const signatureBytes = base64ToBytes(signature)\n const signer = authenticators.find((a: VerificationMethod) => {\n const { keyBytes, keyType } = extractPublicKeyBytes(a)\n if (keyType === 'Ed25519') {\n return ed25519.verify(signatureBytes, clear, keyBytes)\n } else {\n return false\n }\n })\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\ntype Verifier = (data: string, signature: string, authenticators: VerificationMethod[]) => VerificationMethod\n\ntype Algorithms = Record<KNOWN_JWA, Verifier>\n\nconst algorithms: Algorithms = {\n ES256: verifyES256,\n ES256K: verifyES256K,\n // This is a non-standard algorithm but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/146\n 'ES256K-R': verifyRecoverableES256K,\n // This is actually incorrect but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/130\n Ed25519: verifyEd25519,\n EdDSA: verifyEd25519,\n}\n\nfunction VerifierAlgorithm(alg: string): Verifier {\n const impl: Verifier = algorithms[alg as KNOWN_JWA]\n if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n return impl\n}\n\nVerifierAlgorithm.toSignatureObject = toSignatureObject\n\nexport default VerifierAlgorithm\n"],"mappings":";;;;AAAA,SAIEA,uBACK;AAEP,SAASC,iCAAiC;AAC1C,SAASC,wBAAwB;AACjC,SAASC,SAASC,iBAA6E;AAC/F,SAUEC,gBACAC,6BACAC,8BACK;AACP,SAASC,kBAAkBC,yBAAgF;AAa3G,OAAOC,WAAW;AAElB,SAASC,WAAWC,aAAAA,kBAAiB;AAGrC,SAASC,qBAAqBC,uBAAuBC,sBAAs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U;MACVM,OAAO;QAAEC,SAASqF;QAAcpF,WAAW8E,UAAU7E;MAAK;MAC1DL,KAAAA;MACAD,SAAS;QACP;UACEH,UAAU;UACVjC,YAAYX;UACZgD,KAAAA;UACAE,OAAO;YAAEC,SAASqF;YAAcpF,WAAW8E,UAAU7E;UAAK;QAC5D;;MAEFnD;MACAuI,qBAAqBxG;MACrBjC;IACF;EACF;AAEA,QAAMgD,MAAM;IACV;MACEpB,IAAI;MACJqB,OAAO;IACT;IACA;MACErB,IAAI;MACJqB,OAAO;IACT;IACA;MACErB,IAAI;MACJqB,OAAO;IACT;IACA;MACErB,IAAI;MACJqB,OAAO;IACT;;AAEF,SAAO;IACLL,UAAU;IACVI;IACAD,SAAS;MACP;QACEH,UAAU;QACVjC;QACAqC;MACF;;IAEF9C;IACAuI,qBAAqBxG;IACrBjC;EACF;AACF;AA7IsB+D;AAyRtB,SAASrD,cACPH,SAA4D;AAI5D,MAAI,CAACU,iBAA8BV,SAAS,eAAA,GAAkB;AAC5D,UAAMS,MACJ,uKAAA;EAEJ,WAAW,CAACC,iBAAwCV,SAAS,sBAAA,GAAyB;AACpF,UAAMS,MACJ,kLAAA;EAEJ;AACA,SAAOT;AAGT;AAjBSG;","names":["isDidIdentifier","signatureAlgorithmFromKey","contextHasPlugin","asArray","intersect","pickSigningKey","preProcessCredentialPayload","preProcessPresentation","CredentialMapper","isVcdm2Credential","Debug","decodeJWT","JWT_ERROR","normalizeCredential","normalizePresentation","verifyPresentation","verifyPresentationJWT","canonicalizeData","parse","u8a","x25519","varint","decode","encode","secp256k1","p256","bytesToBase64url","b","toString","base64ToBytes","s","inputBase64Url","replace","fromString","base58ToBytes","s","fromString","VM_TO_KEY_TYPE","Secp256k1SignatureVerificationKey2018","Secp256k1VerificationKey2018","EcdsaSecp256k1VerificationKey2019","EcdsaPublicKeySecp256k1","EcdsaSecp256k1RecoveryMethod2020","EcdsaSecp256r1VerificationKey2019","Ed25519VerificationKey2018","Ed25519VerificationKey2020","ED25519SignatureVerification","X25519KeyAgreementKey2019","X25519KeyAgreementKey2020","ConditionalProof2022","undefined","JsonWebKey2020","Multikey","supportedCodecs","CODEC_TO_KEY_TYPE","extractPublicKeyBytes","pk","publicKeyBase58","keyBytes","base58ToBytes","keyType","type","publicKeyBase64","base64ToBytes","publicKeyHex","hexToBytes","publicKeyJwk","crv","x","y","secp256k1","ProjectivePoint","fromAffine","bytesToBigInt","toRawBytes","p256","kty","includes","publicKeyMultibase","multibaseToBytes","Uint8Array","multibaseToBytes","s","bytes","decode","includes","length","keyBytes","codec","varint","possibleCodec","Object","entries","supportedCodecs","filter","code","slice","keyType","CODEC_TO_KEY_TYPE","e","hexToBytes","minLength","input","startsWith","substring","paddedLength","Math","max","padStart","fromString","toLowerCase","bytesToHex","b","toString","bytesToBigInt","BigInt","stringToBytes","s","fromString","toJose","r","recoveryParam","recoverable","jose","Uint8Array","set","Error","bytesToBase64url","fromJose","signature","signatureBytes","base64ToBytes","length","TypeError","bytesToHex","slice","undefined","instanceOfEcdsaSignature","object","ES256SignerAlg","sign","payload","signer","signature","toJose","ES256KSignerAlg","recoverable","fromJose","recoveryParam","Error","Ed25519SignerAlg","algorithms","ES256","ES256K","Ed25519","EdDSA","toEthereumAddress","secp256k1","p256","ed25519","u8a","sha256","hash","sha256","payload","data","fromString","hash","toSignatureObject","signature","recoverable","rawSig","base64ToBytes","length","Error","r","bytesToHex","slice","s","sigObj","recoveryParam","toSignatureObject2","bytes","compact","recovery","verifyES256","authenticators","sig","p256","Signature","fromCompact","fullPublicKeys","filter","a","ethereumAddress","blockchainAccountId","signer","find","pk","keyBytes","extractPublicKeyBytes","verify","err","verifyES256K","signatureNormalized","secp256k1","normalizeS","blockchainAddressKeys","verifyRecoverableES256K","signatures","push","so","checkSignatureAgainstSigner","addRecoveryBit","recoveredPublicKey","recoverPublicKey","recoveredAddress","toEthereumAddress","toHex","toLowerCase","recoveredPublicKeyHex","recoveredCompressedPublicKeyHex","keyHex","split","verificationMethod","verifyEd25519","clear","stringToBytes","signatureBytes","keyType","ed25519","algorithms","ES256","ES256K","Ed25519","EdDSA","VerifierAlgorithm","alg","impl","JWT_ERROR","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","SELF_ISSUED_V0_1","getIssuerFromSdJwt","debug","Debug","CredentialProviderVcdm2SdJwt","matchKeyForType","key","matchKeyForJWT","getTypeProofFormat","canIssueCredentialType","args","format","proofFormat","toLowerCase","canVerifyDocumentType","document","jwt","proof","payload","decodeJWT","split","isVcdm2Credential","createVerifiableCredential","context","keyRef","agent","assertContext","credential","issuer","preProcessCredentialPayload","Promise","reject","Error","contextHasPlugin","identifier","didManagerGet","did","e","managedIdentifier","identifierManagedGetByDid","kmsKeyRef","pickSigningKey","alg","signatureAlgorithmFromKey","id","result","createSdJwtVc","type","credentialPayload","resolution","disclosureFrame","opts","normalized","normalizeCredential","verifyCredential","policies","uniform","CredentialMapper","toUniformCredential","verificationResult","verified","asArray","verifySdJwtVc","results","log","valid","error","message","errorCode","name","nbf","issuanceDate","validFrom","iat","exp","expirationDate","validUntil","aud","audience","verifierSignature","createVerifiablePresentation","presentation","holder","preProcessPresentation","domain","challenge","header","kid","meta","verificationMethod","typ","cty","nonce","jwtCreateJwsCompactSignature","mode","protectedHeader","clientIdScheme","normalizePresentation","verifyPresentation","fetchRemoteContexts","otherOptions","resolver","resolve","didUrl","resolveDid","options","resolutionOptions","intendedAudience","managedDids","didManagerFind","filtered","filter","includes","length","verifyPresentationJWT","verifiablePresentation","intersect","algorithms","wrapSigner","algorithm","data","keyManagerSign","verifierContext","credIssuer","undefined","JWT_ERROR","INVALID_JWT","getIssuerFromSdJwt","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","credentialSubject","sub_jwk","sub","SELF_ISSUED_V0_1","scope","redirect_uri","client_id","indexOf","identifierExternalResolve","validFromError","Date","parse","getTime","expired","didOpts","method","jwtResult","jwtVerifyJwsSignature","jws","jwk","jwks","isDidIdentifier","errorMessage","didResolutionResult"]}
1
+ {"version":3,"sources":["../src/agent/CredentialProviderVcdm2SdJwt.ts","../src/did-jwt/JWT.ts","../src/did-jwt/util.ts","../src/did-jwt/SignerAlgorithm.ts","../src/did-jwt/VerifierAlgorithm.ts"],"sourcesContent":["import {\n type ExternalIdentifierDidOpts,\n ExternalIdentifierResult,\n type IIdentifierResolution,\n isDidIdentifier,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport type { IJwtService, JwsHeader, JwsPayload } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { signatureAlgorithmFromKey } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { contextHasPlugin } from '@sphereon/ssi-sdk.agent-config'\nimport { asArray, intersect, type VerifiableCredentialSP, type VerifiablePresentationSP } from '@sphereon/ssi-sdk.core'\nimport {\n type ICanIssueCredentialTypeArgs,\n type ICanVerifyDocumentTypeArgs,\n type ICreateVerifiableCredentialLDArgs,\n type ICreateVerifiablePresentationLDArgs,\n type IVcdmCredentialProvider,\n type IVcdmIssuerAgentContext,\n IVcdmVerifierAgentContext,\n IVerifyCredentialVcdmArgs,\n IVerifyPresentationLDArgs,\n pickSigningKey,\n preProcessCredentialPayload,\n preProcessPresentation,\n} from '@sphereon/ssi-sdk.credential-vcdm'\nimport { CredentialMapper, isVcdm2Credential, type IVerifyResult, type OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport type {\n IAgentContext,\n IDIDManager,\n IIdentifier,\n IKey,\n IKeyManager,\n IResolver,\n VerifiableCredential,\n VerificationPolicies,\n VerifierAgentContext,\n} from '@veramo/core'\n\nimport Debug from 'debug'\n\nimport { decodeJWT, JWT_ERROR } from 'did-jwt'\n\n// @ts-ignore\nimport { normalizeCredential, normalizePresentation, verifyPresentation as verifyPresentationJWT } from 'did-jwt-vc'\n\nimport { type Resolvable } from 'did-resolver'\n\nimport { SELF_ISSUED_V0_1, SELF_ISSUED_V2, SELF_ISSUED_V2_VC_INTEROP } from '../did-jwt/JWT'\nimport { getIssuerFromSdJwt, ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\n// import {validateCredentialPayload} from \"did-jwt-vc/src\";\n\nconst debug = Debug('sphereon:ssi-sdk:credential-vcdm2-sdjwt')\n\n/**\n * A handler that implements the {@link IVcdmCredentialProvider} methods.\n *\n * @beta This API may change without a BREAKING CHANGE notice.\n */\nexport class CredentialProviderVcdm2SdJwt implements IVcdmCredentialProvider {\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.matchKeyForType} */\n matchKeyForType(key: IKey): boolean {\n return this.matchKeyForJWT(key)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.getTypeProofFormat} */\n getTypeProofFormat(): string {\n return 'vc+sd-jwt'\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canIssueCredentialType} */\n canIssueCredentialType(args: ICanIssueCredentialTypeArgs): boolean {\n const format = args.proofFormat.toLowerCase()\n // TODO: Create type\n return format === 'vc+sd-jwt' || format === 'vcdm2_sdjwt'\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canVerifyDocumentType */\n canVerifyDocumentType(args: ICanVerifyDocumentTypeArgs): boolean {\n const { document } = args\n const jwt = typeof document === 'string' ? document : (<VerifiableCredential>document)?.proof?.jwt\n if (!jwt) {\n return false\n }\n const { payload } = decodeJWT(jwt.split('~')[0])\n return isVcdm2Credential(payload)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiableCredential} */\n async createVerifiableCredential(args: ICreateVerifiableCredentialLDArgs, context: IVcdmIssuerAgentContext): Promise<VerifiableCredentialSP> {\n const { keyRef } = args\n const agent = assertContext(context).agent\n const { credential, issuer } = preProcessCredentialPayload(args)\n if (!isVcdm2Credential(credential)) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential. Context: ' + credential['@context']))\n } else if (!contextHasPlugin<ISDJwtPlugin>(context, 'createSdJwtVc')) {\n return Promise.reject(\n new Error('invalid_argument: SD-JWT plugin not available. Please install @sphereon/ssi-sdk.sd-jwt and configure agent for VCDM2 SD-JWT'),\n )\n }\n let identifier: IIdentifier\n try {\n identifier = await agent.didManagerGet({ did: issuer })\n } catch (e) {\n return Promise.reject(new Error(`invalid_argument: ${credential.issuer} must be a DID managed by this agent. ${e}`))\n }\n const managedIdentifier = await agent.identifierManagedGetByDid({ identifier: identifier.did, kmsKeyRef: keyRef })\n const key = await pickSigningKey({ identifier, kmsKeyRef: keyRef }, context)\n\n // TODO: Probably wise to give control to caller as well, as some key types allow multiple signature algos\n const alg = (await signatureAlgorithmFromKey({ key })) as string\n debug('Signing VC with', identifier.did, alg)\n credential.issuer = { id: identifier.did }\n\n const result = await context.agent.createSdJwtVc({\n type: 'vc+sd-jwt',\n credentialPayload: credential,\n resolution: managedIdentifier,\n disclosureFrame: args.opts?.disclosureFrame,\n })\n\n const jwt = result.credential.split('~')[0]\n\n // debug(jwt)\n const normalized = normalizeCredential(jwt)\n normalized.proof.jwt = result.credential\n return normalized\n }\n\n /** {@inheritdoc ICredentialVerifier.verifyCredential} */\n async verifyCredential(args: IVerifyCredentialVcdmArgs, context: VerifierAgentContext): Promise<IVerifyResult> {\n let { credential, policies /*...otherOptions*/ } = args\n const uniform = CredentialMapper.toUniformCredential(credential as OriginalVerifiableCredential)\n // let verifiedCredential: VerifiableCredential\n if (!isVcdm2Credential(uniform)) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential. Context: ' + uniform['@context']))\n } else if (!contextHasPlugin<ISDJwtPlugin>(context, 'createSdJwtVc')) {\n return Promise.reject(\n new Error('invalid_argument: SD-JWT plugin not available. Please install @sphereon/ssi-sdk.sd-jwt and configure agent for VCDM2 SD-JWT'),\n )\n }\n let verificationResult: IVerifyResult = { verified: false }\n let jwt: string | undefined = typeof credential === 'string' ? credential : asArray(uniform.proof)?.[0]?.jwt\n if (!jwt) {\n return Promise.reject(new Error('invalid_argument: credential must be a VCDM2 credential in JOSE format (string)'))\n }\n\n try {\n const result = await context.agent.verifySdJwtVc({ credential: jwt })\n if (result.payload) {\n verificationResult = {\n verified: true,\n results: [\n {\n credential: credential as OriginalVerifiableCredential,\n verified: true,\n log: [\n {\n id: 'valid_signature',\n valid: true,\n },\n {\n id: 'issuer_did_resolves',\n valid: true,\n },\n ],\n },\n ],\n }\n }\n } catch (e) {\n verificationResult = { verified: false, error: { message: e.message, errorCode: e.name } }\n }\n\n policies = {\n ...policies,\n nbf: policies?.nbf ?? policies?.issuanceDate ?? policies?.validFrom,\n iat: policies?.iat ?? policies?.issuanceDate ?? policies?.validFrom,\n exp: policies?.exp ?? policies?.expirationDate ?? policies?.validUntil,\n aud: policies?.aud ?? policies?.audience,\n }\n verificationResult = await verifierSignature({ jwt: jwt.split('~')[0], policies }, context)\n return verificationResult\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiablePresentation} */\n async createVerifiablePresentation(args: ICreateVerifiablePresentationLDArgs, context: IVcdmIssuerAgentContext): Promise<VerifiablePresentationSP> {\n const { presentation, holder } = preProcessPresentation(args)\n let { domain, challenge, keyRef /* removeOriginalFields, keyRef, now, ...otherOptions*/ } = args\n\n const agent = assertContext(context).agent\n\n const managedIdentifier = await agent.identifierManagedGetByDid({ identifier: holder, kmsKeyRef: keyRef })\n const identifier = managedIdentifier.identifier\n const key = await pickSigningKey(\n {\n identifier: managedIdentifier.identifier,\n kmsKeyRef: managedIdentifier.kmsKeyRef,\n },\n context,\n )\n\n debug('Signing VC with', identifier.did)\n let alg = 'ES256'\n if (key.type === 'Ed25519') {\n alg = 'EdDSA'\n } else if (key.type === 'Secp256k1') {\n alg = 'ES256K'\n }\n\n const header: JwsHeader = {\n kid: key.meta.verificationMethod.id ?? key.kid,\n alg,\n typ: 'vp+jwt',\n cty: 'vp',\n }\n const payload: JwsPayload = {\n ...presentation,\n ...(domain && { aud: domain }),\n ...(challenge && { nonce: challenge }),\n }\n\n const jwt = await agent.jwtCreateJwsCompactSignature({\n mode: 'did',\n issuer: managedIdentifier,\n payload,\n protectedHeader: header,\n clientIdScheme: 'did',\n })\n\n debug(jwt)\n return normalizePresentation(jwt.jwt)\n }\n\n /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.verifyPresentation} */\n async verifyPresentation(args: IVerifyPresentationLDArgs, context: VerifierAgentContext): Promise<IVerifyResult> {\n let { presentation, domain, challenge, fetchRemoteContexts, policies, ...otherOptions } = args\n let jwt: string\n if (typeof presentation === 'string') {\n jwt = presentation\n } else {\n jwt = asArray(presentation.proof)[0].jwt\n }\n const resolver = {\n resolve: (didUrl: string) =>\n context.agent.resolveDid({\n didUrl,\n options: otherOptions?.resolutionOptions,\n }),\n } as Resolvable\n\n let audience = domain\n if (!audience) {\n const { payload } = await decodeJWT(jwt)\n if (payload.aud) {\n // automatically add a managed DID as audience if one is found\n const intendedAudience = asArray(payload.aud)\n const managedDids = await context.agent.didManagerFind()\n const filtered = managedDids.filter((identifier) => intendedAudience.includes(identifier.did))\n if (filtered.length > 0) {\n audience = filtered[0].did\n }\n }\n }\n\n let message, errorCode\n try {\n const result = await verifyPresentationJWT(jwt, resolver, {\n challenge,\n domain,\n audience,\n policies: {\n ...policies,\n nbf: policies?.nbf ?? policies?.issuanceDate,\n iat: policies?.iat ?? policies?.issuanceDate,\n exp: policies?.exp ?? policies?.expirationDate,\n aud: policies?.aud ?? policies?.audience,\n },\n ...otherOptions,\n })\n if (result) {\n /**\n * {id: 'valid_signature', valid: true},\n * // {id: 'issuer_did_resolves', valid: true},\n * // {id: 'expiration', valid: true},\n * // {id: 'revocation_status', valid: true},\n * // {id: 'suspension_status', valid: true}\n */\n return {\n verified: true,\n results: [\n {\n verified: true,\n presentation: result.verifiablePresentation,\n log: [\n {\n id: 'valid_signature',\n valid: true,\n },\n ],\n },\n ],\n } satisfies IVerifyResult\n }\n } catch (e: any) {\n message = e.message\n errorCode = e.errorCode\n }\n return {\n verified: false,\n error: {\n message,\n errorCode: errorCode ? errorCode : message?.split(':')[0],\n },\n }\n }\n\n /**\n * Checks if a key is suitable for signing JWT payloads.\n * @param key - the key to check\n * @param context - the Veramo agent context, unused here\n *\n * @beta\n */\n matchKeyForJWT(key: IKey): boolean {\n switch (key.type) {\n case 'Ed25519':\n case 'Secp256r1':\n return true\n case 'Secp256k1':\n return intersect(key.meta?.algorithms ?? [], ['ES256K', 'ES256K-R']).length > 0\n default:\n return false\n }\n }\n\n wrapSigner(context: IAgentContext<Pick<IKeyManager, 'keyManagerSign'>>, key: IKey, algorithm?: string) {\n return async (data: string | Uint8Array): Promise<string> => {\n const result = await context.agent.keyManagerSign({ keyRef: key.kid, data: <string>data, algorithm })\n return result\n }\n }\n}\n\nexport async function verifierSignature(\n { jwt, policies }: { jwt: string; policies: VerificationPolicies /*resolver: Resolvable*/ },\n verifierContext: VerifierAgentContext,\n): Promise<IVerifyResult> {\n let credIssuer: string | undefined = undefined\n const context = assertContext(verifierContext)\n const agent = context.agent\n const { payload, header /*signature, data*/ } = decodeJWT(jwt)\n\n if (!payload.issuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n const issuer = getIssuerFromSdJwt(payload)\n if (issuer === SELF_ISSUED_V2 || issuer === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.credentialSubject.id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT credentialSubject.id is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n credIssuer = payload.sub\n } else {\n credIssuer = (header.kid || '').split('#')[0]\n }\n } else if (issuer === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n credIssuer = payload.did\n } else if (!issuer && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n credIssuer = payload.client_id\n } else if (issuer?.indexOf('did:') === 0) {\n credIssuer = issuer\n } else if (header.kid?.indexOf('did:') === 0) {\n // OID4VCI expects iss to be the client and kid, to be the DID VM\n credIssuer = (header.kid || '').split('#')[0]\n } else if (typeof payload.issuer === 'string') {\n credIssuer = payload.issuer\n } else if (payload.issuer?.id) {\n credIssuer = payload.issuer.id\n }\n\n if (!credIssuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n let resolution: ExternalIdentifierResult | undefined = undefined\n try {\n resolution = await agent.identifierExternalResolve({ identifier: credIssuer })\n } catch (e: any) {}\n const credential = CredentialMapper.toUniformCredential(jwt)\n\n const validFromError =\n policies.nbf !== false &&\n policies.iat !== false &&\n 'validFrom' in credential &&\n !!credential.validFrom &&\n Date.parse(credential.validFrom) > new Date().getTime()\n const expired =\n policies.exp !== false && 'validUntil' in credential && !!credential.validUntil && Date.parse(credential.validUntil) < new Date().getTime()\n\n const didOpts = { method: 'did', identifier: credIssuer } satisfies ExternalIdentifierDidOpts\n const jwtResult = await agent.jwtVerifyJwsSignature({\n jws: jwt,\n // @ts-ignore\n jwk: resolution?.jwks[0].jwk,\n opts: { ...(isDidIdentifier(credIssuer) && { did: didOpts }) },\n })\n const error = jwtResult.error || expired || !resolution\n const errorMessage = expired\n ? 'Credential is expired'\n : validFromError\n ? 'Credential is not valid yet'\n : !resolution\n ? `Issuer ${credIssuer} could not be resolved`\n : jwtResult.message\n\n if (error) {\n const log = [\n {\n id: 'valid_signature',\n valid: !jwtResult.error,\n },\n { id: 'issuer_did_resolves', valid: resolution != undefined },\n { id: 'validFrom', valid: policies.nbf !== false && !validFromError },\n { id: 'expiration', valid: policies.exp !== false && !expired },\n ]\n return {\n verified: false,\n error: { message: errorMessage, errorCode: jwtResult.name },\n log,\n results: [\n {\n verified: false,\n credential: jwt,\n log,\n error: { message: errorMessage, errorCode: jwtResult.name },\n },\n ],\n payload,\n didResolutionResult: resolution,\n jwt,\n } satisfies IVerifyResult\n }\n\n const log = [\n {\n id: 'valid_signature',\n valid: true,\n },\n {\n id: 'issuer_did_resolves',\n valid: true,\n },\n {\n id: 'validFrom',\n valid: true,\n },\n {\n id: 'expiration',\n valid: true,\n },\n ]\n return {\n verified: true,\n log,\n results: [\n {\n verified: true,\n credential,\n log,\n },\n ],\n payload,\n didResolutionResult: resolution,\n jwt,\n } satisfies IVerifyResult\n}\n\n/*\nexport async function verifyDIDJWT(\n jwt: string,\n options: JWTVerifyOptions = {\n resolver: undefined,\n auth: undefined,\n audience: undefined,\n callbackUrl: undefined,\n skewTime: undefined,\n proofPurpose: undefined,\n policies: {},\n },\n verifierContext: VerifierAgentContext,\n): Promise<JWTVerified> {\n const context = assertContext(verifierContext)\n const agent = context.agent\n if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n const { payload, header, signature, data }: JWTDecoded = decodeJWT(jwt)\n const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n ? options.auth\n ? 'authentication'\n : undefined\n : options.proofPurpose\n\n let credIssuer: string | undefined = undefined\n\n if (!payload.iss && !payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n\n if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.sub) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n credIssuer = payload.sub\n } else {\n credIssuer = (header.kid || '').split('#')[0]\n }\n } else if (payload.iss === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n credIssuer = payload.did\n } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n credIssuer = payload.client_id\n } else if (payload.iss?.indexOf('did:') === 0) {\n credIssuer = payload.iss\n } else if (header.kid?.indexOf('did:') === 0) {\n // OID4VCI expects iss to be the client and kid, to be the DID VM\n credIssuer = (header.kid || '').split('#')[0]\n } else if (payload.iss) {\n credIssuer = payload.iss\n }\n\n if (!credIssuer) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n\n const resolution = await agent.identifierExternalResolve({ identifier: credIssuer })\n\n const didOpts = { method: 'did', identifier: credIssuer } satisfies ExternalIdentifierDidOpts\n const jwtResult = await agent.jwtVerifyJwsSignature({\n jws: jwt,\n // @ts-ignore\n jwk: resolution.jwks[0],\n opts: { ...(isDidIdentifier(credIssuer) && { did: didOpts }) },\n })\n\n if (jwtResult.error) {\n return Promise.reject(Error(`Error validating credential: ${jwtResult.error}`))\n }\n const { didResolutionResult, authenticators, issuer }: DIDAuthenticator = await resolveAuthenticator(\n options.resolver,\n header.alg,\n credIssuer,\n proofPurpose,\n )\n const signer: VerificationMethod = verifyJWSDecoded({ header, data, signature } as JWSDecoded, authenticators)\n const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n if (signer) {\n const nowSkewed = now + skewTime\n if (options.policies?.nbf !== false && payload.nbf) {\n if (payload.nbf > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n }\n } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n }\n if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n }\n if (options.policies?.aud !== false && payload.aud) {\n if (!options.audience && !options.callbackUrl) {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`)\n }\n const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n const matchedAudience = audArray.find((item: any) => options.audience === item || options.callbackUrl === item)\n\n if (typeof matchedAudience === 'undefined') {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n }\n }\n return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n }\n throw new Error(\n `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`,\n )\n}\n\nfunction verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n return signer\n}\n\n\nexport function validateCredentialPayload(payload: CredentialPayload): void {\n validateContext(asArray(payload['@context']))\n validateVcType(payload.type)\n validateCredentialSubject(payload.credentialSubject)\n if (payload.validFrom) validateTimestamp(payload.validFrom)\n if (payload.validUntil) validateTimestamp(payload.validUntil)\n}\n\nexport function validateContext(value: string | string[]): void {\n const input = asArray(value)\n if (input.length < 1 || input.indexOf(VCDM_CREDENTIAL_CONTEXT_V2) === -1) {\n throw new TypeError(`${VC_ERROR.SCHEMA_ERROR}: @context is missing default context \"${VCDM_CREDENTIAL_CONTEXT_V2}\"`)\n }\n}\n*/\nfunction assertContext(\n context: IVcdmIssuerAgentContext | IVcdmVerifierAgentContext,\n): IAgentContext<\n IResolver & IDIDManager & Pick<IKeyManager, 'keyManagerGet' | 'keyManagerSign' | 'keyManagerVerify'> & IJwtService & IIdentifierResolution\n> {\n if (!contextHasPlugin<IJwtService>(context, 'jwtPrepareJws')) {\n throw Error(\n 'JwtService plugin not found, which is required for JWT signing in the VCDM2 SD-JWT credential provider. Please add the JwtService plugin to your agent configuration.',\n )\n } else if (!contextHasPlugin<IIdentifierResolution>(context, 'identifierManagedGet')) {\n throw Error(\n 'Identifier resolution plugin not found, which is required for JWT signing in the VCDM2 SD-JWT credential provider. Please add the JwtService plugin to your agent configuration.',\n )\n }\n return context as IAgentContext<\n IResolver & IDIDManager & Pick<IKeyManager, 'keyManagerGet' | 'keyManagerSign' | 'keyManagerVerify'> & IJwtService & IIdentifierResolution\n >\n}\n","import canonicalizeData from 'canonicalize'\nimport { type DIDDocument, type DIDResolutionResult, parse, type ParsedDID, type Resolvable, type VerificationMethod } from 'did-resolver'\nimport SignerAlg from './SignerAlgorithm'\nimport { decodeBase64url, type EcdsaSignature, encodeBase64url, type KNOWN_JWA, SUPPORTED_PUBLIC_KEY_TYPES } from './util'\nimport VerifierAlgorithm from './VerifierAlgorithm'\nimport { JWT_ERROR } from 'did-jwt'\n\nexport type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>\nexport type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>\n\nexport type ProofPurposeTypes =\n | 'assertionMethod'\n | 'authentication'\n // | 'keyAgreement' // keyAgreement VerificationMethod should not be used for signing\n | 'capabilityDelegation'\n | 'capabilityInvocation'\n\nexport interface JWTOptions {\n issuer: string\n signer: Signer\n /**\n * @deprecated Please use `header.alg` to specify the JWT algorithm.\n */\n alg?: string\n expiresIn?: number\n canonicalize?: boolean\n}\n\nexport interface JWTVerifyOptions {\n /** @deprecated Please use `proofPurpose: 'authentication' instead` */\n auth?: boolean\n audience?: string\n callbackUrl?: string\n resolver?: Resolvable\n skewTime?: number\n /** See https://www.w3.org/TR/did-spec-registries/#verification-relationships */\n proofPurpose?: ProofPurposeTypes\n policies?: JWTVerifyPolicies\n didAuthenticator?: DIDAuthenticator\n}\n\n/**\n * Overrides the different types of checks performed on the JWT besides the signature check\n */\nexport interface JWTVerifyPolicies {\n // overrides the timestamp against which the validity interval is checked\n now?: number\n // when set to false, the timestamp checks ignore the Not Before(`nbf`) property\n nbf?: boolean\n // when set to false, the timestamp checks ignore the Issued At(`iat`) property\n iat?: boolean\n // when set to false, the timestamp checks ignore the Expires At(`exp`) property\n exp?: boolean\n // when set to false, the JWT audience check is skipped\n aud?: boolean\n}\n\nexport interface JWSCreationOptions {\n canonicalize?: boolean\n}\n\nexport interface DIDAuthenticator {\n authenticators: VerificationMethod[]\n issuer: string\n didResolutionResult: DIDResolutionResult\n}\n\nexport interface JWTHeader {\n typ: 'JWT'\n alg: string\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any\n}\n\nexport interface JWTPayload {\n iss?: string\n sub?: string\n aud?: string | string[]\n iat?: number\n nbf?: number\n exp?: number\n rexp?: number\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any\n}\n\nexport interface JWTDecoded {\n header: JWTHeader\n payload: JWTPayload\n signature: string\n data: string\n}\n\nexport interface JWSDecoded {\n header: JWTHeader\n payload: string\n signature: string\n data: string\n}\n\n/**\n * Result object returned by {@link verifyJWT}\n */\nexport interface JWTVerified {\n /**\n * Set to true for a JWT that passes all the required checks minus any verification overrides.\n */\n verified: true\n\n /**\n * The decoded JWT payload\n */\n payload: Partial<JWTPayload>\n\n /**\n * The result of resolving the issuer DID\n */\n didResolutionResult: DIDResolutionResult\n\n /**\n * the issuer DID\n */\n issuer: string\n\n /**\n * The public key of the issuer that matches the JWT signature\n */\n signer: VerificationMethod\n\n /**\n * The original JWT that was verified\n */\n jwt: string\n\n /**\n * Any overrides that were used during verification\n */\n policies?: JWTVerifyPolicies\n}\n\nexport const SELF_ISSUED_V2 = 'https://self-issued.me/v2'\nexport const SELF_ISSUED_V2_VC_INTEROP = 'https://self-issued.me/v2/openid-vc' // https://identity.foundation/jwt-vc-presentation-profile/#id-token-validation\nexport const SELF_ISSUED_V0_1 = 'https://self-issued.me'\n\ntype LegacyVerificationMethod = { publicKey?: string }\n\nconst defaultAlg: KNOWN_JWA = 'ES256K'\nconst DID_JSON = 'application/did+json'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction encodeSection(data: any, shouldCanonicalize = false): string {\n if (shouldCanonicalize) {\n return encodeBase64url(<string>canonicalizeData(data))\n } else {\n return encodeBase64url(JSON.stringify(data))\n }\n}\n\nexport const NBF_SKEW = 300\n\nfunction decodeJWS(jws: string): JWSDecoded {\n const parts = jws.match(/^([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)$/)\n if (parts) {\n return {\n header: JSON.parse(decodeBase64url(parts[1])),\n payload: parts[2],\n signature: parts[3],\n data: `${parts[1]}.${parts[2]}`,\n }\n }\n throw new Error('invalid_argument: Incorrect format JWS')\n}\n\n/**\n * Decodes a JWT and returns an object representing the payload\n *\n * @example\n * decodeJWT('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJpYXQiOjE1...')\n *\n * @param {String} jwt a JSON Web Token to verify\n * @param {Object} [recurse] whether to recurse into the payload to decode any nested JWTs\n * @return {Object} a JS object representing the decoded JWT\n */\nexport function decodeJWT(jwt: string, recurse = true): JWTDecoded {\n if (!jwt) throw new Error('invalid_argument: no JWT passed into decodeJWT')\n try {\n const jws = decodeJWS(jwt)\n const decodedJwt: JWTDecoded = Object.assign(jws, { payload: JSON.parse(decodeBase64url(jws.payload)) })\n const iss = decodedJwt.payload.iss\n\n if (decodedJwt.header.cty === 'JWT' && recurse) {\n const innerDecodedJwt = decodeJWT(decodedJwt.payload.jwt)\n\n if (innerDecodedJwt.payload.iss !== iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n return innerDecodedJwt\n }\n return decodedJwt\n } catch (e) {\n throw new Error(`invalid_argument: ${JWT_ERROR.INVALID_JWT}: ${e}`)\n }\n}\n\n/**\n * Creates a signed JWS given a payload, a signer, and an optional header.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * const jws = await createJWS({ my: 'payload' }, signer)\n *\n * @param {Object} payload payload object\n * @param {Signer} signer a signer, see `ES256KSigner or `EdDSASigner`\n * @param {Object} header optional object to specify or customize the JWS header\n * @param {Object} options can be used to trigger automatic canonicalization of header and\n * payload properties\n * @return {Promise<string>} a Promise which resolves to a JWS string or rejects with an error\n */\nexport async function createJWS(\n payload: string | Partial<JWTPayload>,\n signer: Signer,\n header: Partial<JWTHeader> = {},\n options: JWSCreationOptions = {},\n): Promise<string> {\n if (!header.alg) header.alg = defaultAlg\n const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload, options.canonicalize)\n const signingInput: string = [encodeSection(header, options.canonicalize), encodedPayload].join('.')\n\n const jwtSigner: SignerAlgorithm = SignerAlg(header.alg)\n const signature: string = await jwtSigner(signingInput, signer)\n\n // JWS Compact Serialization\n // https://www.rfc-editor.org/rfc/rfc7515#section-7.1\n return [signingInput, signature].join('.')\n}\n\n/**\n * Creates a signed JWT given an address which becomes the issuer, a signer, and a payload for which the signature is\n * over.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n * ...\n * })\n *\n * @param {Object} payload payload object\n * @param {Object} [options] an unsigned credential object\n * @param {String} options.issuer The DID of the issuer (signer) of JWT\n * @param {String} options.alg [DEPRECATED] The JWT signing algorithm to use. Supports:\n * [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n * @param {Signer} options.signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n * @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing\n * @param {Object} header optional object to specify or customize the JWT header\n * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or\n * rejects with an error\n */\nexport async function createJWT(\n payload: Partial<JWTPayload>,\n { issuer, signer, alg, expiresIn, canonicalize }: JWTOptions,\n header: Partial<JWTHeader> = {},\n): Promise<string> {\n if (!signer) throw new Error('missing_signer: No Signer functionality has been configured')\n if (!issuer) throw new Error('missing_issuer: No issuing DID has been configured')\n if (!header.typ) header.typ = 'JWT'\n if (!header.alg) header.alg = alg\n const timestamps: Partial<JWTPayload> = {\n iat: Math.floor(Date.now() / 1000),\n exp: undefined,\n }\n if (expiresIn) {\n if (typeof expiresIn === 'number') {\n timestamps.exp = <number>(payload.nbf || timestamps.iat) + Math.floor(expiresIn)\n } else {\n throw new Error('invalid_argument: JWT expiresIn is not a number')\n }\n }\n const fullPayload = { ...timestamps, ...payload, iss: issuer }\n return createJWS(fullPayload, signer, header, { canonicalize })\n}\n\n/**\n * Creates a multi-signature signed JWT given multiple issuers and their corresponding signers, and a payload for\n * which the signature is over.\n *\n * @example\n * const signer = ES256KSigner(process.env.PRIVATE_KEY)\n * createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n * ...\n * })\n *\n * @param {Object} payload payload object\n * @param {Object} [options] an unsigned credential object\n * @param {boolean} options.expiresIn optional flag to denote the expiration time\n * @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing\n * @param {Object[]} issuers array of the issuers, their signers and algorithms\n * @param {string} issuers[].issuer The DID of the issuer (signer) of JWT\n * @param {Signer} issuers[].signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n * @param {String} issuers[].alg [DEPRECATED] The JWT signing algorithm to use. Supports:\n * [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or\n * rejects with an error\n */\nexport async function createMultisignatureJWT(\n payload: Partial<JWTPayload>,\n { expiresIn, canonicalize }: Partial<JWTOptions>,\n issuers: { issuer: string; signer: Signer; alg: string }[],\n): Promise<string> {\n if (issuers.length === 0) throw new Error('invalid_argument: must provide one or more issuers')\n\n let payloadResult: Partial<JWTPayload> = payload\n\n let jwt = ''\n for (let i = 0; i < issuers.length; i++) {\n const issuer = issuers[i]\n\n const header: Partial<JWTHeader> = {\n typ: 'JWT',\n alg: issuer.alg,\n }\n\n // Create nested JWT\n // See Point 5 of https://www.rfc-editor.org/rfc/rfc7519#section-7.1\n // After the first JWT is created (the first JWS), the next JWT is created by inputting the previous JWT as the\n // payload\n if (i !== 0) {\n header.cty = 'JWT'\n }\n\n jwt = await createJWT(payloadResult, { ...issuer, canonicalize, expiresIn }, header)\n\n payloadResult = { jwt }\n }\n return jwt\n}\n\nexport function verifyJWTDecoded(\n { header, payload, data, signature }: JWTDecoded,\n pubKeys: VerificationMethod | VerificationMethod[],\n): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n\n const iss = payload.iss\n let recurse = true\n do {\n if (iss !== payload.iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n\n try {\n const result = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n\n return result\n } catch (e) {\n if (!(e as Error).message.startsWith(JWT_ERROR.INVALID_SIGNATURE)) throw e\n }\n\n // TODO probably best to create copy objects than replace reference objects\n if (header.cty !== 'JWT') {\n recurse = false\n } else {\n ;({ payload, header, signature, data } = decodeJWT(payload.jwt, false))\n }\n } while (recurse)\n\n throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: no matching public key found`)\n}\n\nexport function verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n return signer\n}\n\n/**\n * Verifies given JWS. If the JWS is valid, returns the public key that was\n * used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.\n *\n * @example\n * const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })\n *\n * @param {String} jws A JWS string to verify\n * @param {Array<VerificationMethod> | VerificationMethod} pubKeys The public keys used to verify the JWS\n * @return {VerificationMethod} The public key used to sign the JWS\n */\nexport function verifyJWS(jws: string, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n const jwsDecoded: JWSDecoded = decodeJWS(jws)\n return verifyJWSDecoded(jwsDecoded, pubKeys)\n}\n\n/**\n * Verifies given JWT. If the JWT is valid, the promise returns an object including the JWT, the payload of the JWT,\n * and the DID document of the issuer of the JWT.\n *\n * @example\n * ```ts\n * verifyJWT(\n * 'did:uport:eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....',\n * {audience: '5A8bRWU3F7j3REx3vkJ...', callbackUrl: 'https://...'}\n * ).then(obj => {\n * const did = obj.did // DID of signer\n * const payload = obj.payload\n * const doc = obj.didResolutionResult.didDocument // DID Document of issuer\n * const jwt = obj.jwt\n * const signerKeyId = obj.signer.id // ID of key in DID document that signed JWT\n * ...\n * })\n * ```\n *\n * @param {String} jwt a JSON Web Token to verify\n * @param {Object} [options] an unsigned credential object\n * @param {Boolean} options.auth Require signer to be listed in the authentication section of the\n * DID document (for Authentication purposes)\n * @param {String} options.audience DID of the recipient of the JWT\n * @param {String} options.callbackUrl callback url in JWT\n * @return {Promise<Object, Error>} a promise which resolves with a response object or rejects with an\n * error\n */\nexport async function verifyJWT(\n jwt: string,\n options: JWTVerifyOptions = {\n resolver: undefined,\n auth: undefined,\n audience: undefined,\n callbackUrl: undefined,\n skewTime: undefined,\n proofPurpose: undefined,\n policies: {},\n didAuthenticator: undefined,\n },\n): Promise<JWTVerified> {\n if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n const { payload, header /*, signature, data*/ }: JWTDecoded = decodeJWT(jwt, false)\n const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n ? options.auth\n ? 'authentication'\n : undefined\n : options.proofPurpose\n\n let didUrl: string | undefined\n\n if (!payload.iss && !payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n }\n\n if (options.didAuthenticator) {\n didUrl = options.didAuthenticator.issuer\n } else if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n if (!payload.sub) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n }\n if (typeof payload.sub_jwk === 'undefined') {\n didUrl = payload.sub\n } else {\n didUrl = (header.kid || '').split('#')[0]\n }\n } else if (payload.iss === SELF_ISSUED_V0_1) {\n if (!payload.did) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n }\n didUrl = payload.did\n } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n // SIOP Request payload\n // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n if (!payload.client_id) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n }\n didUrl = payload.client_id\n } else {\n didUrl = payload.iss\n }\n\n if (!didUrl) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n }\n\n let authenticators: VerificationMethod[]\n let issuer: string\n let didResolutionResult: DIDResolutionResult\n if (options.didAuthenticator) {\n ;({ didResolutionResult, authenticators, issuer } = options.didAuthenticator)\n } else {\n ;({ didResolutionResult, authenticators, issuer } = await resolveAuthenticator(options.resolver, header.alg, didUrl, proofPurpose))\n // Add to options object for recursive reference\n options.didAuthenticator = { didResolutionResult, authenticators, issuer }\n }\n\n const { did } = parse(didUrl) as ParsedDID\n\n let signer: VerificationMethod | null = null\n\n if (did !== didUrl) {\n const authenticator = authenticators.find((auth) => auth.id === didUrl)\n if (!authenticator) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: No authenticator found for did URL ${didUrl}`)\n }\n\n // signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n } else {\n let i = 0\n while (!signer && i < authenticators.length) {\n // const authenticator = authenticators[i]\n try {\n // signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n } catch (e) {\n if (!(e as Error).message.includes(JWT_ERROR.INVALID_SIGNATURE) || i === authenticators.length - 1) throw e\n }\n\n i++\n }\n }\n\n if (signer) {\n const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n\n const nowSkewed = now + skewTime\n if (options.policies?.nbf !== false && payload.nbf) {\n if (payload.nbf > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n }\n } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n }\n if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n }\n if (options.policies?.aud !== false && payload.aud) {\n if (!options.audience && !options.callbackUrl) {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`)\n }\n const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n const matchedAudience = audArray.find((item) => options.audience === item || options.callbackUrl === item)\n\n if (typeof matchedAudience === 'undefined') {\n throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n }\n }\n\n return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n }\n throw new Error(\n `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`,\n )\n}\n\n/**\n * Resolves relevant public keys or other authenticating material used to verify signature from the DID document of\n * provided DID\n *\n * @example\n * ```ts\n * resolveAuthenticator(resolver, 'ES256K', 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX').then(obj => {\n * const payload = obj.payload\n * const profile = obj.profile\n * const jwt = obj.jwt\n * // ...\n * })\n * ```\n *\n * @param resolver - {Resolvable} a DID resolver function that can obtain the `DIDDocument` for the `issuer`\n * @param alg - {String} a JWT algorithm\n * @param issuer - {String} a Decentralized Identifier (DID) to lookup\n * @param proofPurpose - {ProofPurposeTypes} *Optional* Use the verificationMethod linked in that section of the\n * issuer DID document\n * @return {Promise<DIDAuthenticator>} a promise which resolves with an object containing an array of authenticators\n * or rejects with an error if none exist\n */\nexport async function resolveAuthenticator(\n resolver: Resolvable,\n alg: string,\n issuer: string,\n proofPurpose?: ProofPurposeTypes,\n): Promise<DIDAuthenticator> {\n const types: string[] = SUPPORTED_PUBLIC_KEY_TYPES[alg as KNOWN_JWA]\n if (!types || types.length === 0) {\n throw new Error(`${JWT_ERROR.NOT_SUPPORTED}: No supported signature types for algorithm ${alg}`)\n }\n let didResult: DIDResolutionResult\n\n const result = (await resolver.resolve(issuer, { accept: DID_JSON })) as unknown\n // support legacy resolvers that do not produce DIDResolutionResult\n if (Object.getOwnPropertyNames(result).indexOf('didDocument') === -1) {\n didResult = {\n didDocument: result as DIDDocument,\n didDocumentMetadata: {},\n didResolutionMetadata: { contentType: DID_JSON },\n }\n } else {\n didResult = result as DIDResolutionResult\n }\n\n if (didResult.didResolutionMetadata?.error || didResult.didDocument == null) {\n const { error, message } = didResult.didResolutionMetadata\n throw new Error(`${JWT_ERROR.RESOLVER_ERROR}: Unable to resolve DID document for ${issuer}: ${error}, ${message || ''}`)\n }\n\n const getPublicKeyById = (verificationMethods: VerificationMethod[], pubid?: string): VerificationMethod | null => {\n const filtered = verificationMethods.filter(({ id }) => pubid === id)\n return filtered.length > 0 ? filtered[0] : null\n }\n\n let publicKeysToCheck: VerificationMethod[] = [...(didResult?.didDocument?.verificationMethod || []), ...(didResult?.didDocument?.publicKey || [])]\n if (typeof proofPurpose === 'string') {\n // support legacy DID Documents that do not list assertionMethod\n if (proofPurpose.startsWith('assertion') && !Object.getOwnPropertyNames(didResult?.didDocument).includes('assertionMethod')) {\n didResult.didDocument = { ...(<DIDDocument>didResult.didDocument) }\n didResult.didDocument.assertionMethod = [...publicKeysToCheck.map((pk) => pk.id)]\n }\n\n publicKeysToCheck = (didResult.didDocument[proofPurpose] || [])\n .map((verificationMethod) => {\n if (typeof verificationMethod === 'string') {\n return getPublicKeyById(publicKeysToCheck, verificationMethod)\n } else if (typeof (<LegacyVerificationMethod>verificationMethod).publicKey === 'string') {\n // this is a legacy format\n return getPublicKeyById(publicKeysToCheck, (<LegacyVerificationMethod>verificationMethod).publicKey)\n } else {\n return <VerificationMethod>verificationMethod\n }\n })\n .filter((key) => key != null) as VerificationMethod[]\n }\n\n const authenticators: VerificationMethod[] = publicKeysToCheck.filter(({ type }) => types.find((supported) => supported === type))\n\n if (typeof proofPurpose === 'string' && (!authenticators || authenticators.length === 0)) {\n throw new Error(\n `${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys suitable for ${alg} with ${proofPurpose} purpose`,\n )\n }\n if (!authenticators || authenticators.length === 0) {\n throw new Error(`${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys for ${alg}`)\n }\n return { authenticators, issuer, didResolutionResult: didResult }\n}\n","// @ts-ignore\nimport * as u8a from 'uint8arrays'\n// const { concat, fromString, toString } = u8a\nimport { x25519 } from '@noble/curves/ed25519'\n\n// @ts-ignore\nimport { varint } from 'multiformats'\nimport { BaseName, decode, encode } from 'multibase'\nimport type { VerificationMethod } from 'did-resolver'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\n\n// const u8a = { toString, fromString, concat }\n\nexport interface EphemeralPublicKey {\n kty?: string\n //ECC\n crv?: string\n x?: string\n y?: string\n //RSA\n n?: string\n e?: string\n}\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport interface EcdsaSignature {\n r: string\n s: string\n recoveryParam?: number\n}\n\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport type ECDSASignature = {\n compact: Uint8Array\n recovery?: number\n}\n\nexport type JsonWebKey = {\n crv: string\n kty: string\n x?: string\n y?: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n}\n\nexport function bytesToBase64url(b: Uint8Array): string {\n return u8a.toString(b, 'base64url')\n}\n\nexport function base64ToBytes(s: string): Uint8Array {\n const inputBase64Url = s.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n return u8a.fromString(inputBase64Url, 'base64url')\n}\n\nexport function bytesToBase64(b: Uint8Array): string {\n return u8a.toString(b, 'base64pad')\n}\n\nexport function base58ToBytes(s: string): Uint8Array {\n return u8a.fromString(s, 'base58btc')\n}\n\nexport function bytesToBase58(b: Uint8Array): string {\n return u8a.toString(b, 'base58btc')\n}\n\nexport type KNOWN_JWA = 'ES256' | 'ES256K' | 'ES256K-R' | 'Ed25519' | 'EdDSA'\n\nexport type KNOWN_VERIFICATION_METHOD =\n | 'JsonWebKey2020'\n | 'Multikey'\n | 'Secp256k1SignatureVerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'Secp256k1VerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'EcdsaSecp256k1VerificationKey2019' // ES256K / ES256K-R\n | 'EcdsaPublicKeySecp256k1' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n | 'EcdsaSecp256k1RecoveryMethod2020' // ES256K-R (ES256K also supported with 1 less bit of security)\n | 'EcdsaSecp256r1VerificationKey2019' // ES256 / P-256\n | 'Ed25519VerificationKey2018'\n | 'Ed25519VerificationKey2020'\n | 'ED25519SignatureVerification' // deprecated\n | 'ConditionalProof2022'\n | 'X25519KeyAgreementKey2019' // deprecated\n | 'X25519KeyAgreementKey2020'\n\nexport type KNOWN_KEY_TYPE = 'Secp256k1' | 'Ed25519' | 'X25519' | 'Bls12381G1' | 'Bls12381G2' | 'P-256'\n\nexport type PublicKeyTypes = Record<KNOWN_JWA, KNOWN_VERIFICATION_METHOD[]>\n\nexport const SUPPORTED_PUBLIC_KEY_TYPES: PublicKeyTypes = {\n ES256: ['JsonWebKey2020', 'Multikey', 'EcdsaSecp256r1VerificationKey2019'],\n ES256K: [\n 'EcdsaSecp256k1VerificationKey2019',\n /**\n * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n */\n 'EcdsaSecp256k1RecoveryMethod2020',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1VerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1SignatureVerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'EcdsaPublicKeySecp256k1',\n /**\n * TODO - support R1 key as well\n * 'ConditionalProof2022',\n */\n 'JsonWebKey2020',\n 'Multikey',\n ],\n 'ES256K-R': [\n 'EcdsaSecp256k1VerificationKey2019',\n /**\n * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n */\n 'EcdsaSecp256k1RecoveryMethod2020',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1VerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'Secp256k1SignatureVerificationKey2018',\n /**\n * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n * not an ethereumAddress\n */\n 'EcdsaPublicKeySecp256k1',\n 'ConditionalProof2022',\n 'JsonWebKey2020',\n 'Multikey',\n ],\n Ed25519: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'JsonWebKey2020', 'Multikey'],\n EdDSA: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018', 'Ed25519VerificationKey2020', 'JsonWebKey2020', 'Multikey'],\n}\n\nexport const VM_TO_KEY_TYPE: Record<KNOWN_VERIFICATION_METHOD, KNOWN_KEY_TYPE | undefined> = {\n Secp256k1SignatureVerificationKey2018: 'Secp256k1',\n Secp256k1VerificationKey2018: 'Secp256k1',\n EcdsaSecp256k1VerificationKey2019: 'Secp256k1',\n EcdsaPublicKeySecp256k1: 'Secp256k1',\n EcdsaSecp256k1RecoveryMethod2020: 'Secp256k1',\n EcdsaSecp256r1VerificationKey2019: 'P-256',\n Ed25519VerificationKey2018: 'Ed25519',\n Ed25519VerificationKey2020: 'Ed25519',\n ED25519SignatureVerification: 'Ed25519',\n X25519KeyAgreementKey2019: 'X25519',\n X25519KeyAgreementKey2020: 'X25519',\n ConditionalProof2022: undefined,\n JsonWebKey2020: undefined, // key type must be specified in the JWK\n Multikey: undefined, // key type must be extracted from the multicodec\n}\n\nexport type KNOWN_CODECS = 'ed25519-pub' | 'x25519-pub' | 'secp256k1-pub' | 'bls12_381-g1-pub' | 'bls12_381-g2-pub' | 'p256-pub'\n\n// this is from the multicodec table https://github.com/multiformats/multicodec/blob/master/table.csv\nexport const supportedCodecs: Record<KNOWN_CODECS, number> = {\n 'ed25519-pub': 0xed,\n 'x25519-pub': 0xec,\n 'secp256k1-pub': 0xe7,\n 'bls12_381-g1-pub': 0xea,\n 'bls12_381-g2-pub': 0xeb,\n 'p256-pub': 0x1200,\n}\n\nexport const CODEC_TO_KEY_TYPE: Record<KNOWN_CODECS, KNOWN_KEY_TYPE> = {\n 'bls12_381-g1-pub': 'Bls12381G1',\n 'bls12_381-g2-pub': 'Bls12381G2',\n 'ed25519-pub': 'Ed25519',\n 'p256-pub': 'P-256',\n 'secp256k1-pub': 'Secp256k1',\n 'x25519-pub': 'X25519',\n}\n\n/**\n * Extracts the raw byte representation of a public key from a VerificationMethod along with an inferred key type\n * @param pk a VerificationMethod entry from a DIDDocument\n * @return an object containing the `keyBytes` of the public key and an inferred `keyType`\n */\nexport function extractPublicKeyBytes(pk: VerificationMethod): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n if (pk.publicKeyBase58) {\n return {\n keyBytes: base58ToBytes(pk.publicKeyBase58),\n keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n }\n } else if (pk.publicKeyBase64) {\n return {\n keyBytes: base64ToBytes(pk.publicKeyBase64),\n keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n }\n } else if (pk.publicKeyHex) {\n return { keyBytes: hexToBytes(pk.publicKeyHex), keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return {\n keyBytes: secp256k1.ProjectivePoint.fromAffine({\n x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n }).toRawBytes(false),\n keyType: 'Secp256k1',\n }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n return {\n keyBytes: p256.ProjectivePoint.fromAffine({\n x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n }).toRawBytes(false),\n keyType: 'P-256',\n }\n } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === 'OKP' && ['Ed25519', 'X25519'].includes(pk.publicKeyJwk.crv ?? '') && pk.publicKeyJwk.x) {\n return { keyBytes: base64ToBytes(pk.publicKeyJwk.x), keyType: pk.publicKeyJwk.crv as KNOWN_KEY_TYPE }\n } else if (pk.publicKeyMultibase) {\n const { keyBytes, keyType } = multibaseToBytes(pk.publicKeyMultibase)\n return { keyBytes, keyType: keyType ?? VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n }\n return { keyBytes: new Uint8Array() }\n}\n\n/**\n * Encodes the given byte array to a multibase string (defaulting to base58btc).\n * If a codec is provided, the corresponding multicodec prefix will be added.\n *\n * @param b - the Uint8Array to be encoded\n * @param base - the base to use for encoding (defaults to base58btc)\n * @param codec - the codec to use for encoding (defaults to no codec)\n *\n * @returns the multibase encoded string\n *\n * @public\n */\nexport function bytesToMultibase(b: Uint8Array, base: BaseName = 'base58btc', codec?: keyof typeof supportedCodecs | number): string {\n if (!codec) {\n return u8a.toString(encode(base, b), 'utf-8')\n } else {\n const codecCode = typeof codec === 'string' ? supportedCodecs[codec] : codec\n const prefixLength = varint.encodingLength(codecCode)\n const multicodecEncoding = new Uint8Array(prefixLength + b.length)\n varint.encodeTo(codecCode, multicodecEncoding) // set prefix\n multicodecEncoding.set(b, prefixLength) // add the original bytes\n return u8a.toString(encode(base, multicodecEncoding), 'utf-8')\n }\n}\n\n/**\n * Converts a multibase string to the Uint8Array it represents.\n * This method will assume the byte array that is multibase encoded is a multicodec and will attempt to decode it.\n *\n * @param s - the string to be converted\n *\n * @throws if the string is not formatted correctly.\n *\n * @public\n */\nexport function multibaseToBytes(s: string): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n const bytes = decode(s)\n\n // look for known key lengths first\n // Ed25519/X25519, secp256k1/P256 compressed or not, BLS12-381 G1/G2 compressed\n if ([32, 33, 48, 64, 65, 96].includes(bytes.length)) {\n return { keyBytes: bytes }\n }\n\n // then assume multicodec, otherwise return the bytes\n try {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [codec, length] = varint.decode(bytes)\n const possibleCodec: string | undefined = Object.entries(supportedCodecs).filter(([, code]) => code === codec)?.[0][0] ?? ''\n return { keyBytes: bytes.slice(length), keyType: CODEC_TO_KEY_TYPE[possibleCodec as KNOWN_CODECS] }\n } catch (e) {\n // not a multicodec, return the bytes\n return { keyBytes: bytes }\n }\n}\n\nexport function hexToBytes(s: string, minLength?: number): Uint8Array {\n let input = s.startsWith('0x') ? s.substring(2) : s\n\n if (input.length % 2 !== 0) {\n input = `0${input}`\n }\n\n if (minLength) {\n const paddedLength = Math.max(input.length, minLength * 2)\n input = input.padStart(paddedLength, '00')\n }\n\n return u8a.fromString(input.toLowerCase(), 'base16')\n}\n\nexport function encodeBase64url(s: string): string {\n return bytesToBase64url(u8a.fromString(s))\n}\n\nexport function decodeBase64url(s: string): string {\n return u8a.toString(base64ToBytes(s))\n}\n\nexport function bytesToHex(b: Uint8Array): string {\n return u8a.toString(b, 'base16')\n}\n\nexport function bytesToBigInt(b: Uint8Array): bigint {\n return BigInt(`0x` + u8a.toString(b, 'base16'))\n}\n\nexport function bigintToBytes(n: bigint, minLength?: number): Uint8Array {\n return hexToBytes(n.toString(16), minLength)\n}\n\nexport function stringToBytes(s: string): Uint8Array {\n return u8a.fromString(s, 'utf-8')\n}\n\nexport function toJose({ r, s, recoveryParam }: EcdsaSignature, recoverable?: boolean): string {\n const jose = new Uint8Array(recoverable ? 65 : 64)\n jose.set(u8a.fromString(r, 'base16'), 0)\n jose.set(u8a.fromString(s, 'base16'), 32)\n if (recoverable) {\n if (typeof recoveryParam === 'undefined') {\n throw new Error('Signer did not return a recoveryParam')\n }\n jose[64] = <number>recoveryParam\n }\n return bytesToBase64url(jose)\n}\n\nexport function fromJose(signature: string): { r: string; s: string; recoveryParam?: number } {\n const signatureBytes: Uint8Array = base64ToBytes(signature)\n if (signatureBytes.length < 64 || signatureBytes.length > 65) {\n throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`)\n }\n const r = bytesToHex(signatureBytes.slice(0, 32))\n const s = bytesToHex(signatureBytes.slice(32, 64))\n const recoveryParam = signatureBytes.length === 65 ? signatureBytes[64] : undefined\n return { r, s, recoveryParam }\n}\n\nexport function toSealed(ciphertext: string, tag?: string): Uint8Array {\n return u8a.concat([base64ToBytes(ciphertext), tag ? base64ToBytes(tag) : new Uint8Array(0)])\n}\n\nexport function leftpad(data: string, size = 64): string {\n if (data.length === size) return data\n return '0'.repeat(size - data.length) + data\n}\n\n/**\n * Generate random x25519 key pair.\n */\nexport function generateKeyPair(): { secretKey: Uint8Array; publicKey: Uint8Array } {\n const secretKey = x25519.utils.randomPrivateKey()\n const publicKey = x25519.getPublicKey(secretKey)\n return {\n secretKey: secretKey,\n publicKey: publicKey,\n }\n}\n\n/**\n * Generate private-public x25519 key pair from `seed`.\n */\nexport function generateKeyPairFromSeed(seed: Uint8Array): { secretKey: Uint8Array; publicKey: Uint8Array } {\n if (seed.length !== 32) {\n throw new Error(`x25519: seed must be ${32} bytes`)\n }\n return {\n publicKey: x25519.getPublicKey(seed),\n secretKey: seed,\n }\n}\n/*\n\nexport function genX25519EphemeralKeyPair(): EphemeralKeyPair {\n const epk = generateKeyPair()\n return {\n publicKeyJWK: { kty: 'OKP', crv: 'X25519', x: bytesToBase64url(epk.publicKey) },\n secretKey: epk.secretKey,\n }\n}\n*/\n\n/**\n * Checks if a variable is defined and not null.\n * After this check, typescript sees the variable as defined.\n *\n * @param arg - The input to be verified\n *\n * @returns true if the input variable is defined.\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n return arg !== null && typeof arg !== 'undefined'\n}\n","import type { Signer, SignerAlgorithm } from './JWT'\nimport { type EcdsaSignature, fromJose, toJose } from './util'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction instanceOfEcdsaSignature(object: any): object is EcdsaSignature {\n return typeof object === 'object' && 'r' in object && 's' in object\n}\n\nexport function ES256SignerAlg(): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (instanceOfEcdsaSignature(signature)) {\n return toJose(signature)\n } else {\n return signature\n }\n }\n}\n\nexport function ES256KSignerAlg(recoverable?: boolean): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (instanceOfEcdsaSignature(signature)) {\n return toJose(signature, recoverable)\n } else {\n if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') {\n throw new Error(`not_supported: ES256K-R not supported when signer doesn't provide a recovery param`)\n }\n return signature\n }\n }\n}\n\nexport function Ed25519SignerAlg(): SignerAlgorithm {\n return async function sign(payload: string, signer: Signer): Promise<string> {\n const signature: EcdsaSignature | string = await signer(payload)\n if (!instanceOfEcdsaSignature(signature)) {\n return signature\n } else {\n throw new Error('invalid_config: expected a signer function that returns a string instead of signature object')\n }\n }\n}\n\ninterface SignerAlgorithms {\n [alg: string]: SignerAlgorithm\n}\n\nconst algorithms: SignerAlgorithms = {\n ES256: ES256SignerAlg(),\n ES256K: ES256KSignerAlg(),\n // This is a non-standard algorithm but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/146\n 'ES256K-R': ES256KSignerAlg(true),\n // This is actually incorrect but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/130\n Ed25519: Ed25519SignerAlg(),\n EdDSA: Ed25519SignerAlg(),\n}\n\nfunction SignerAlg(alg: string): SignerAlgorithm {\n const impl: SignerAlgorithm = algorithms[alg]\n if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n return impl\n}\n\nexport default SignerAlg\n","import { toEthereumAddress } from 'did-jwt'\nimport type { VerificationMethod } from 'did-resolver'\nimport { base64ToBytes, bytesToHex, type EcdsaSignature, type ECDSASignature, extractPublicKeyBytes, type KNOWN_JWA, stringToBytes } from './util'\n// @ts-ignore\n// import { verifyBlockchainAccountId } from 'did-jwt'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\nimport { ed25519 } from '@noble/curves/ed25519'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nimport { sha256 as hash } from '@noble/hashes/sha256'\n\nexport function sha256(payload: string | Uint8Array): Uint8Array {\n const data = typeof payload === 'string' ? u8a.fromString(payload) : payload\n return hash(data)\n}\n// converts a JOSE signature to it's components\nexport function toSignatureObject(signature: string, recoverable = false): EcdsaSignature {\n const rawSig: Uint8Array = base64ToBytes(signature)\n if (rawSig.length !== (recoverable ? 65 : 64)) {\n throw new Error('wrong signature length')\n }\n const r: string = bytesToHex(rawSig.slice(0, 32))\n const s: string = bytesToHex(rawSig.slice(32, 64))\n const sigObj: EcdsaSignature = { r, s }\n if (recoverable) {\n sigObj.recoveryParam = rawSig[64]\n }\n return sigObj\n}\n\nexport function toSignatureObject2(signature: string, recoverable = false): ECDSASignature {\n const bytes = base64ToBytes(signature)\n if (bytes.length !== (recoverable ? 65 : 64)) {\n throw new Error('wrong signature length')\n }\n return {\n compact: bytes.slice(0, 64),\n recovery: bytes[64],\n }\n}\n\nexport function verifyES256(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const hash = sha256(data)\n const sig = p256.Signature.fromCompact(toSignatureObject2(signature).compact)\n const fullPublicKeys = authenticators.filter((a: VerificationMethod) => !a.ethereumAddress && !a.blockchainAccountId)\n\n const signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n try {\n const { keyBytes } = extractPublicKeyBytes(pk)\n return p256.verify(sig, hash, keyBytes)\n } catch (err) {\n return false\n }\n })\n\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\nexport function verifyES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const hash = sha256(data)\n const signatureNormalized = secp256k1.Signature.fromCompact(base64ToBytes(signature)).normalizeS()\n const fullPublicKeys = authenticators.filter((a: VerificationMethod) => {\n return !a.ethereumAddress && !a.blockchainAccountId\n })\n const blockchainAddressKeys = authenticators.filter((a: VerificationMethod) => {\n return a.ethereumAddress || a.blockchainAccountId\n })\n\n let signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n try {\n const { keyBytes } = extractPublicKeyBytes(pk)\n return secp256k1.verify(signatureNormalized, hash, keyBytes)\n } catch (err) {\n return false\n }\n })\n\n if (!signer && blockchainAddressKeys.length > 0) {\n signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys)\n }\n\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\nexport function verifyRecoverableES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const signatures: ECDSASignature[] = []\n if (signature.length > 86) {\n signatures.push(toSignatureObject2(signature, true))\n } else {\n const so = toSignatureObject2(signature, false)\n signatures.push({ ...so, recovery: 0 })\n signatures.push({ ...so, recovery: 1 })\n }\n const hash = sha256(data)\n\n const checkSignatureAgainstSigner = (sigObj: ECDSASignature): VerificationMethod | undefined => {\n const signature = secp256k1.Signature.fromCompact(sigObj.compact).addRecoveryBit(sigObj.recovery || 0)\n const recoveredPublicKey = signature.recoverPublicKey(hash)\n const recoveredAddress = toEthereumAddress(recoveredPublicKey.toHex(false)).toLowerCase()\n const recoveredPublicKeyHex = recoveredPublicKey.toHex(false)\n const recoveredCompressedPublicKeyHex = recoveredPublicKey.toHex(true)\n\n return authenticators.find((a: VerificationMethod) => {\n const { keyBytes } = extractPublicKeyBytes(a)\n const keyHex = bytesToHex(keyBytes)\n return (\n keyHex === recoveredPublicKeyHex ||\n keyHex === recoveredCompressedPublicKeyHex ||\n a.ethereumAddress?.toLowerCase() === recoveredAddress ||\n a.blockchainAccountId?.split('@eip155')?.[0].toLowerCase() === recoveredAddress //|| // CAIP-2\n // verifyBlockchainAccountId(recoveredPublicKeyHex, a.blockchainAccountId) // CAIP-10\n )\n })\n }\n\n // Find first verification method\n for (const signature of signatures) {\n const verificationMethod = checkSignatureAgainstSigner(signature)\n if (verificationMethod) return verificationMethod\n }\n // If no one found matching\n throw new Error('invalid_signature: Signature invalid for JWT')\n}\n\nexport function verifyEd25519(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n const clear = stringToBytes(data)\n const signatureBytes = base64ToBytes(signature)\n const signer = authenticators.find((a: VerificationMethod) => {\n const { keyBytes, keyType } = extractPublicKeyBytes(a)\n if (keyType === 'Ed25519') {\n return ed25519.verify(signatureBytes, clear, keyBytes)\n } else {\n return false\n }\n })\n if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n return signer\n}\n\ntype Verifier = (data: string, signature: string, authenticators: VerificationMethod[]) => VerificationMethod\n\ntype Algorithms = Record<KNOWN_JWA, Verifier>\n\nconst algorithms: Algorithms = {\n ES256: verifyES256,\n ES256K: verifyES256K,\n // This is a non-standard algorithm but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/146\n 'ES256K-R': verifyRecoverableES256K,\n // This is actually incorrect but retained for backwards compatibility\n // see https://github.com/decentralized-identity/did-jwt/issues/130\n Ed25519: verifyEd25519,\n EdDSA: verifyEd25519,\n}\n\nfunction VerifierAlgorithm(alg: string): Verifier {\n const impl: Verifier = algorithms[alg as KNOWN_JWA]\n if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n return impl\n}\n\nVerifierAlgorithm.toSignatureObject = toSignatureObject\n\nexport default VerifierAlgorithm\n"],"mappings":";;;;AAAA,SAIEA,uBACK;AAEP,SAASC,iCAAiC;AAC1C,SAASC,wBAAwB;AACjC,SAASC,SAASC,iBAA6E;AAC/F,SAUEC,gBACAC,6BACAC,8BACK;AACP,SAASC,kBAAkBC,yBAAgF;AAa3G,OAAOC,WAAW;AAElB,SAASC,WAAWC,aAAAA,kBAAiB;AAGrC,SAASC,qBAAqBC,uBAAuBC,sBAAsBC,6BAA6B;;;AC1CxG,OAAOC,sBAAsB;AAC7B,SAAqDC,aAAuE;;;ACA5H,YAAYC,SAAS;AAErB,SAASC,cAAc;AAGvB,SAASC,cAAc;AACvB,SAAmBC,QAAQC,cAAc;AAEzC,SAASC,iBAAiB;AAC1B,SAASC,YAAY;AAwCd,SAASC,iBAAiBC,GAAa;AAC5C,SAAWC,aAASD,GAAG,WAAA;AACzB;AAFgBD;AAIT,SAASG,cAAcC,GAAS;AACrC,QAAMC,iBAAiBD,EAAEE,QAAQ,OAAO,GAAA,EAAK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,IAAI;MACJqB,OAAO;IACT;IACA;MACErB,IAAI;MACJqB,OAAO;IACT;;AAEF,SAAO;IACLL,UAAU;IACVI;IACAD,SAAS;MACP;QACEH,UAAU;QACVjC;QACAqC;MACF;;IAEF9C;IACAuI,qBAAqBxG;IACrBjC;EACF;AACF;AA3IsB+D;AAuRtB,SAASrD,cACPH,SAA4D;AAI5D,MAAI,CAACU,iBAA8BV,SAAS,eAAA,GAAkB;AAC5D,UAAMS,MACJ,uKAAA;EAEJ,WAAW,CAACC,iBAAwCV,SAAS,sBAAA,GAAyB;AACpF,UAAMS,MACJ,kLAAA;EAEJ;AACA,SAAOT;AAGT;AAjBSG;","names":["isDidIdentifier","signatureAlgorithmFromKey","contextHasPlugin","asArray","intersect","pickSigningKey","preProcessCredentialPayload","preProcessPresentation","CredentialMapper","isVcdm2Credential","Debug","decodeJWT","JWT_ERROR","normalizeCredential","normalizePresentation","verifyPresentation","verifyPresentationJWT","canonicalizeData","parse","u8a","x25519","varint","decode","encode","secp256k1","p256","bytesToBase64url","b","toString","base64ToBytes","s","inputBase64Url","replace","fromString","base58ToBytes","s","fromString","VM_TO_KEY_TYPE","Secp256k1SignatureVerificationKey2018","Secp256k1VerificationKey2018","EcdsaSecp256k1VerificationKey2019","EcdsaPublicKeySecp256k1","EcdsaSecp256k1RecoveryMethod2020","EcdsaSecp256r1VerificationKey2019","Ed25519VerificationKey2018","Ed25519VerificationKey2020","ED25519SignatureVerification","X25519KeyAgreementKey2019","X25519KeyAgreementKey2020","ConditionalProof2022","undefined","JsonWebKey2020","Multikey","supportedCodecs","CODEC_TO_KEY_TYPE","extractPublicKeyBytes","pk","publicKeyBase58","keyBytes","base58ToBytes","keyType","type","publicKeyBase64","base64ToBytes","publicKeyHex","hexToBytes","publicKeyJwk","crv","x","y","secp256k1","ProjectivePoint","fromAffine","bytesToBigInt","toRawBytes","p256","kty","includes","publicKeyMultibase","multibaseToBytes","Uint8Array","multibaseToBytes","s","bytes","decode","includes","length","keyBytes","codec","varint","possibleCodec","Object","entries","supportedCodecs","filter","code","slice","keyType","CODEC_TO_KEY_TYPE","e","hexToBytes","minLength","input","startsWith","substring","paddedLength","Math","max","padStart","fromString","toLowerCase","bytesToHex","b","toString","bytesToBigInt","BigInt","stringToBytes","s","fromString","toJose","r","recoveryParam","recoverable","jose","Uint8Array","set","Error","bytesToBase64url","fromJose","signature","signatureBytes","base64ToBytes","length","TypeError","bytesToHex","slice","undefined","instanceOfEcdsaSignature","object","ES256SignerAlg","sign","payload","signer","signature","toJose","ES256KSignerAlg","recoverable","fromJose","recoveryParam","Error","Ed25519SignerAlg","algorithms","ES256","ES256K","Ed25519","EdDSA","toEthereumAddress","secp256k1","p256","ed25519","u8a","sha256","hash","sha256","payload","data","fromString","hash","toSignatureObject","signature","recoverable","rawSig","base64ToBytes","length","Error","r","bytesToHex","slice","s","sigObj","recoveryParam","toSignatureObject2","bytes","compact","recovery","verifyES256","authenticators","sig","p256","Signature","fromCompact","fullPublicKeys","filter","a","ethereumAddress","blockchainAccountId","signer","find","pk","keyBytes","extractPublicKeyBytes","verify","err","verifyES256K","signatureNormalized","secp256k1","normalizeS","blockchainAddressKeys","verifyRecoverableES256K","signatures","push","so","checkSignatureAgainstSigner","addRecoveryBit","recoveredPublicKey","recoverPublicKey","recoveredAddress","toEthereumAddress","toHex","toLowerCase","recoveredPublicKeyHex","recoveredCompressedPublicKeyHex","keyHex","split","verificationMethod","verifyEd25519","clear","stringToBytes","signatureBytes","keyType","ed25519","algorithms","ES256","ES256K","Ed25519","EdDSA","VerifierAlgorithm","alg","impl","JWT_ERROR","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","SELF_ISSUED_V0_1","getIssuerFromSdJwt","debug","Debug","CredentialProviderVcdm2SdJwt","matchKeyForType","key","matchKeyForJWT","getTypeProofFormat","canIssueCredentialType","args","format","proofFormat","toLowerCase","canVerifyDocumentType","document","jwt","proof","payload","decodeJWT","split","isVcdm2Credential","createVerifiableCredential","context","keyRef","agent","assertContext","credential","issuer","preProcessCredentialPayload","Promise","reject","Error","contextHasPlugin","identifier","didManagerGet","did","e","managedIdentifier","identifierManagedGetByDid","kmsKeyRef","pickSigningKey","alg","signatureAlgorithmFromKey","id","result","createSdJwtVc","type","credentialPayload","resolution","disclosureFrame","opts","normalized","normalizeCredential","verifyCredential","policies","uniform","CredentialMapper","toUniformCredential","verificationResult","verified","asArray","verifySdJwtVc","results","log","valid","error","message","errorCode","name","nbf","issuanceDate","validFrom","iat","exp","expirationDate","validUntil","aud","audience","verifierSignature","createVerifiablePresentation","presentation","holder","preProcessPresentation","domain","challenge","header","kid","meta","verificationMethod","typ","cty","nonce","jwtCreateJwsCompactSignature","mode","protectedHeader","clientIdScheme","normalizePresentation","verifyPresentation","fetchRemoteContexts","otherOptions","resolver","resolve","didUrl","resolveDid","options","resolutionOptions","intendedAudience","managedDids","didManagerFind","filtered","filter","includes","length","verifyPresentationJWT","verifiablePresentation","intersect","algorithms","wrapSigner","algorithm","data","keyManagerSign","verifierContext","credIssuer","undefined","JWT_ERROR","INVALID_JWT","getIssuerFromSdJwt","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","credentialSubject","sub_jwk","sub","SELF_ISSUED_V0_1","scope","redirect_uri","client_id","indexOf","identifierExternalResolve","validFromError","Date","parse","getTime","expired","didOpts","method","jwtResult","jwtVerifyJwsSignature","jws","jwk","jwks","isDidIdentifier","errorMessage","didResolutionResult"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sphereon/ssi-sdk.credential-vcdm2-sdjwt-provider",
3
3
  "description": "Plugin for working with W3C Verifiable Credentials DataModel 2 JOSE Credentials & Presentations.",
4
- "version": "0.34.1-next.88+7d5f01ed",
4
+ "version": "0.36.0",
5
5
  "source": "src/index.ts",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",
@@ -28,17 +28,17 @@
28
28
  "@scure/base": "^1.1.3",
29
29
  "@sd-jwt/core": "^0.15.0",
30
30
  "@sd-jwt/decode": "^0.15.0",
31
- "@sd-jwt/sd-jwt-vc": "^0.15.0",
31
+ "@sd-jwt/sd-jwt-vc": "^0.15.1",
32
32
  "@sd-jwt/types": "^0.15.0",
33
33
  "@sd-jwt/utils": "^0.15.0",
34
- "@sphereon/ssi-sdk-ext.did-utils": "0.34.1-next.88+7d5f01ed",
35
- "@sphereon/ssi-sdk-ext.identifier-resolution": "0.34.1-next.88+7d5f01ed",
36
- "@sphereon/ssi-sdk-ext.jwt-service": "0.34.1-next.88+7d5f01ed",
37
- "@sphereon/ssi-sdk-ext.key-utils": "0.34.1-next.88+7d5f01ed",
38
- "@sphereon/ssi-sdk.core": "0.34.1-next.88+7d5f01ed",
39
- "@sphereon/ssi-sdk.credential-vcdm": "0.34.1-next.88+7d5f01ed",
40
- "@sphereon/ssi-sdk.sd-jwt": "0.34.1-next.88+7d5f01ed",
41
- "@sphereon/ssi-types": "0.34.1-next.88+7d5f01ed",
34
+ "@sphereon/ssi-sdk-ext.did-utils": "0.36.0",
35
+ "@sphereon/ssi-sdk-ext.identifier-resolution": "0.36.0",
36
+ "@sphereon/ssi-sdk-ext.jwt-service": "0.36.0",
37
+ "@sphereon/ssi-sdk-ext.key-utils": "0.36.0",
38
+ "@sphereon/ssi-sdk.core": "0.36.0",
39
+ "@sphereon/ssi-sdk.credential-vcdm": "0.36.0",
40
+ "@sphereon/ssi-sdk.sd-jwt": "0.36.0",
41
+ "@sphereon/ssi-types": "0.36.0",
42
42
  "@veramo/core": "4.2.0",
43
43
  "@veramo/utils": "4.2.0",
44
44
  "canonicalize": "^2.0.0",
@@ -50,10 +50,10 @@
50
50
  "uint8arrays": "3.1.1"
51
51
  },
52
52
  "devDependencies": {
53
- "@sphereon/ssi-sdk-ext.did-provider-key": "0.34.1-next.88+7d5f01ed",
54
- "@sphereon/ssi-sdk-ext.key-manager": "0.34.1-next.88+7d5f01ed",
55
- "@sphereon/ssi-sdk-ext.kms-local": "0.34.1-next.88+7d5f01ed",
56
- "@sphereon/ssi-sdk.agent-config": "0.34.1-next.88+7d5f01ed",
53
+ "@sphereon/ssi-sdk-ext.did-provider-key": "0.36.0",
54
+ "@sphereon/ssi-sdk-ext.key-manager": "0.36.0",
55
+ "@sphereon/ssi-sdk-ext.kms-local": "0.36.0",
56
+ "@sphereon/ssi-sdk.agent-config": "0.36.0",
57
57
  "@types/debug": "4.1.8",
58
58
  "@veramo/did-manager": "4.2.0",
59
59
  "@veramo/did-provider-ethr": "4.2.0",
@@ -90,5 +90,5 @@
90
90
  "node_modules",
91
91
  "src"
92
92
  ],
93
- "gitHead": "7d5f01eddab106d7ef084dcef21191ab8dd5f20f"
93
+ "gitHead": "f713d3a83948ef69aaa7d435700b16d5655ac863"
94
94
  }
@@ -10,18 +10,13 @@ import { EthrDIDProvider } from '@veramo/did-provider-ethr'
10
10
  import { Resolver } from 'did-resolver'
11
11
  import { getResolver as ethrDidResolver } from 'ethr-did-resolver'
12
12
 
13
- import 'cross-fetch/polyfill'
13
+ import fetch from 'cross-fetch'
14
14
  import { CredentialProviderVcdm2SdJwt } from '../agent/CredentialProviderVcdm2SdJwt'
15
15
  import { type ISphereonKeyManager, MemoryKeyStore, MemoryPrivateKeyStore, SphereonKeyManager } from '@sphereon/ssi-sdk-ext.key-manager'
16
16
  import { SphereonKeyManagementSystem } from '@sphereon/ssi-sdk-ext.kms-local'
17
17
  import { IdentifierResolution, IIdentifierResolution } from '@sphereon/ssi-sdk-ext.identifier-resolution'
18
18
  import { IJwtService, JwtService } from '@sphereon/ssi-sdk-ext.jwt-service'
19
- import {
20
- CredentialMapper,
21
- JwtDecodedVerifiableCredential,
22
- OriginalVerifiableCredential,
23
- VCDM_CREDENTIAL_CONTEXT_V2
24
- } from '@sphereon/ssi-types'
19
+ import { CredentialMapper, JwtDecodedVerifiableCredential, OriginalVerifiableCredential, VCDM_CREDENTIAL_CONTEXT_V2 } from '@sphereon/ssi-types'
25
20
  import { SDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'
26
21
 
27
22
  const infuraProjectId = '3586660d179141e3801c3895de1c2eba'
@@ -349,8 +349,6 @@ export async function verifierSignature(
349
349
  const agent = context.agent
350
350
  const { payload, header /*signature, data*/ } = decodeJWT(jwt)
351
351
 
352
-
353
-
354
352
  if (!payload.issuer) {
355
353
  throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)
356
354
  }