{"version":3,"file":"SdJwtVcService.mjs","names":[],"sources":["../../../src/modules/sd-jwt-vc/SdJwtVcService.ts"],"sourcesContent":["import type { NonEmptyArray } from '@animo-id/pex'\nimport type { DisclosureFrame, PresentationFrame, SDJwt, Verifier } from '@sd-jwt/core'\nimport { type SDJWTVCConfig, SDJwtVcInstance, type VCTFetcher } from '@sd-jwt/sd-jwt-vc'\nimport { AgentContext } from '../../agent'\nimport { TrustedIssuerContext } from '../../agent/TrustedIssuerContext'\nimport type { TrustedIssuer } from '../../agent/TrustedIssuersForVerification'\nimport { JwtPayload } from '../../crypto'\nimport { CredoError } from '../../error'\nimport { injectable } from '../../plugins'\nimport type { Query, QueryOptions } from '../../storage/StorageService'\nimport type { JsonObject } from '../../types'\nimport { dateToSeconds, IntegrityVerifier, JsonEncoder, nowInSeconds, TypedArrayEncoder } from '../../utils'\nimport { getDomainFromUrl } from '../../utils/domain'\nimport { fetchWithTimeout } from '../../utils/fetch'\nimport { getPublicJwkFromVerificationMethod, parseDid } from '../dids'\nimport { KeyManagementApi, PublicJwk } from '../kms'\nimport { ClaimFormat } from '../vc/index'\nimport { X509Certificate, X509ModuleConfig, X509Service } from '../x509'\nimport { legacyTrustedCertificatesToTrustedIssuers } from '../x509/utils/convertLegacyTrustedCertificates'\nimport { decodeSdJwtVc, sdJwtVcHasher } from './decodeSdJwtVc'\nimport { applyDisclosuresForPaths, applyDisclosuresForPayload, type ClaimPath } from './disclosureFrame'\nimport { SdJwtVcRecord, SdJwtVcRepository } from './repository'\nimport { SdJwtVcError } from './SdJwtVcError'\nimport { SdJwtVcModuleConfig } from './SdJwtVcModuleConfig'\nimport type {\n  SdJwtVcHeader,\n  SdJwtVcHolderBinding,\n  SdJwtVcIssuer,\n  SdJwtVcPayload,\n  SdJwtVcPresentOptions,\n  SdJwtVcSignOptions,\n  SdJwtVcStoreOptions,\n  SdJwtVcVerifyOptions,\n} from './SdJwtVcOptions'\nimport type { SdJwtVcTypeMetadata } from './typeMetadata'\nimport {\n  extractKeyFromHolderBinding,\n  getSdJwtHashingAlgorithm,\n  getSdJwtSigner,\n  getSdJwtVerifier,\n  parseHolderBindingFromCredential,\n  parseIssuerFromCredential,\n  resolveDidUrl,\n  resolveSigningPublicJwkFromDidUrl,\n  setJwkAlgFromJwtHeader,\n} from './utils'\n\nexport interface SdJwtVc<\n  Header extends SdJwtVcHeader = SdJwtVcHeader,\n  Payload extends SdJwtVcPayload = SdJwtVcPayload,\n> {\n  /**\n   * claim format is convenience method added to all credential instances\n   */\n  claimFormat: ClaimFormat.SdJwtDc\n  /**\n   * encoded is convenience method added to all credential instances\n   */\n  encoded: string\n  compact: string\n  header: Header\n\n  /**\n   * The issuer of the credential\n   */\n  issuer: SdJwtVcIssuer\n\n  /**\n   * The holder of the credential\n   */\n  holder?: SdJwtVcHolderBinding\n\n  // TODO: payload type here is a lie, as it is the signed payload (so fields replaced with _sd)\n  payload: Payload\n  prettyClaims: Payload\n\n  kbJwt?: {\n    header: Record<string, unknown>\n    payload: Record<string, unknown>\n  }\n\n  /**\n   * The key id in the KMS bound to this SD-JWT VC, used for presentations.\n   *\n   * This will only be set on the holder side if defined on the SdJwtVcRecord\n   */\n  kmsKeyId?: string\n\n  /**\n   * The merged/resolved type metadata of the SD-JWT VC.\n   */\n  typeMetadata?: SdJwtVcTypeMetadata\n}\n\nexport interface VerificationResult {\n  isValid: boolean\n  isValidJwtPayload?: boolean\n  isSignatureValid?: boolean\n  isStatusValid?: boolean\n  isNotBeforeValid?: boolean\n  isExpiryTimeValid?: boolean\n  areRequiredClaimsIncluded?: boolean\n  isKeyBindingValid?: boolean\n  containsExpectedKeyBinding?: boolean\n  containsRequiredVcProperties?: boolean\n}\n\n/**\n * @internal\n */\n@injectable()\nexport class SdJwtVcService {\n  public constructor(private sdJwtVcRepository: SdJwtVcRepository) {}\n\n  public async sign<Payload extends SdJwtVcPayload>(\n    agentContext: AgentContext,\n    options: SdJwtVcSignOptions<Payload>\n  ): Promise<SdJwtVc> {\n    const { payload, disclosureFrame, hashingAlgorithm } = options\n\n    const issuer = await this.extractKeyFromIssuer(agentContext, options.issuer, true)\n\n    // holer binding is optional\n    const holderBinding = options.holder ? await extractKeyFromHolderBinding(agentContext, options.holder) : undefined\n\n    const header = {\n      alg: issuer.alg,\n      typ: options.headerType ?? 'dc+sd-jwt',\n      kid: issuer.kid,\n      x5c: issuer.x5c?.map((cert) => cert.toString('base64')),\n    } as const\n\n    issuer.publicJwk.alg = issuer.alg\n\n    const sdJwt = new SDJwtVcInstance({\n      ...this.getBaseSdJwtConfig(agentContext),\n      signer: getSdJwtSigner(agentContext, issuer.publicJwk),\n      hashAlg: getSdJwtHashingAlgorithm(hashingAlgorithm),\n      signAlg: issuer.alg,\n    })\n\n    if (!payload.vct || typeof payload.vct !== 'string') {\n      throw new SdJwtVcError(\"Missing required parameter 'vct'\")\n    }\n\n    const { iat: payloadIat, ...payloadWithoutIat } = payload\n    const compact = await sdJwt.issue(\n      {\n        ...payloadWithoutIat,\n        cnf: holderBinding?.cnf,\n        iss: issuer.iss,\n        ...(payloadIat === null ? {} : { iat: payloadIat ?? nowInSeconds() }),\n        vct: payload.vct,\n      } as unknown as Payload,\n      disclosureFrame as DisclosureFrame<Payload>,\n      { header }\n    )\n\n    const prettyClaims = (await sdJwt.getClaims(compact)) as Payload\n    const decoded = await sdJwt.decode(compact)\n    const sdJwtPayload = decoded.jwt?.payload as Payload | undefined\n    if (!sdJwtPayload) {\n      throw new SdJwtVcError('Invalid sd-jwt-vc state.')\n    }\n\n    return {\n      compact,\n      prettyClaims,\n      header: header,\n      issuer: options.issuer,\n      holder: options.holder,\n      payload: sdJwtPayload,\n      claimFormat: ClaimFormat.SdJwtDc,\n      encoded: compact,\n    } satisfies SdJwtVc<typeof header, Payload>\n  }\n\n  public fromCompact<Header extends SdJwtVcHeader = SdJwtVcHeader, Payload extends SdJwtVcPayload = SdJwtVcPayload>(\n    compactSdJwtVc: string,\n    typeMetadata?: SdJwtVcTypeMetadata\n  ): SdJwtVc<Header, Payload> {\n    return decodeSdJwtVc(compactSdJwtVc, typeMetadata)\n  }\n\n  /**\n   * @deprecated use `applyDisclosuresForPaths` instead\n   */\n  public applyDisclosuresForPayload(compactSdJwtVc: string, requestedPayload: JsonObject): SdJwtVc {\n    const sdJwt = applyDisclosuresForPayload(compactSdJwtVc, requestedPayload)\n    const disclosedDecoded = decodeSdJwtVc(sdJwt)\n    return disclosedDecoded\n  }\n\n  public applyDisclosuresForPaths(compactSdJwtVc: string, disclosedPaths: ClaimPath[]): SdJwtVc {\n    const { compact } = applyDisclosuresForPaths(compactSdJwtVc, disclosedPaths)\n    const disclosedDecoded = decodeSdJwtVc(compact)\n    return disclosedDecoded\n  }\n\n  public async present<Payload extends SdJwtVcPayload = SdJwtVcPayload>(\n    agentContext: AgentContext,\n    { sdJwtVc, presentationFrame, verifierMetadata, additionalPayload }: SdJwtVcPresentOptions<Payload>\n  ): Promise<string> {\n    const sdjwt = new SDJwtVcInstance(this.getBaseSdJwtConfig(agentContext))\n    const compactSdJwtVc = typeof sdJwtVc === 'string' ? sdJwtVc : sdJwtVc.compact\n    const sdJwtVcInstance = await sdjwt.decode(compactSdJwtVc)\n\n    const holderBinding = parseHolderBindingFromCredential(sdJwtVcInstance.jwt?.payload)\n    if (!holderBinding && verifierMetadata) {\n      throw new SdJwtVcError(\"Verifier metadata provided, but credential has no 'cnf' claim to create a KB-JWT from\")\n    }\n\n    const holder = holderBinding\n      ? await extractKeyFromHolderBinding(agentContext, holderBinding, {\n          forSigning: true,\n          jwkKeyId: typeof sdJwtVc !== 'string' ? sdJwtVc.kmsKeyId : undefined,\n        })\n      : undefined\n    if (holder) {\n      holder.publicJwk.alg = holder.alg\n    }\n    sdjwt.config({\n      kbSigner: holder ? getSdJwtSigner(agentContext, holder.publicJwk) : undefined,\n      kbSignAlg: holder?.alg,\n    })\n\n    const compactDerivedSdJwtVc = await sdjwt.present(compactSdJwtVc, presentationFrame as PresentationFrame<Payload>, {\n      kb: verifierMetadata\n        ? {\n            payload: {\n              iat: verifierMetadata.issuedAt,\n              nonce: verifierMetadata.nonce,\n              aud: verifierMetadata.audience,\n              ...additionalPayload,\n            },\n          }\n        : undefined,\n    })\n\n    return compactDerivedSdJwtVc\n  }\n\n  private assertValidX5cJwtIssuer(\n    agentContext: AgentContext,\n    iss: string | undefined,\n    leafCertificate: X509Certificate\n  ) {\n    // No 'iss' is allowed for X509\n    if (!iss) return\n\n    // If iss is present it MUST be an HTTPS url\n    if (!iss.startsWith('https://') && !(iss.startsWith('http://') && agentContext.config.allowInsecureHttpUrls)) {\n      throw new SdJwtVcError('The X509 certificate issuer must be a HTTPS URI.')\n    }\n\n    if (!leafCertificate.sanUriNames?.includes(iss) && !leafCertificate.sanDnsNames?.includes(getDomainFromUrl(iss))) {\n      throw new SdJwtVcError(\n        `The 'iss' claim in the payload does not match a 'SAN-URI' name and the domain extracted from the HTTPS URI does not match a 'SAN-DNS' name in the x5c certificate. Either remove the 'iss' claim or make it match with at least one SAN-URI or DNS-URI entry`\n      )\n    }\n  }\n\n  public async verify<Header extends SdJwtVcHeader = SdJwtVcHeader, Payload extends SdJwtVcPayload = SdJwtVcPayload>(\n    agentContext: AgentContext,\n    {\n      compactSdJwtVc,\n      keyBinding,\n      requiredClaimKeys,\n      fetchTypeMetadata,\n      trustedCertificates,\n      trustedIssuers: _trustedIssuers,\n      disableStatusValidation,\n      verifyCredentialStatus,\n      now,\n    }: SdJwtVcVerifyOptions\n  ): Promise<\n    | {\n        isValid: true\n        sdJwtVc: SdJwtVc<Header, Payload>\n        /**\n         * The full type metadata chain, can be used for further processing the type metadata.\n         *\n         * Only populated if `fetchTypeMetadata` is set to true, and the resolver returned a type\n         * metadata document.\n         */\n        typeMetadataChain?: NonEmptyArray<SdJwtVcTypeMetadata>\n      }\n    | { isValid: false; sdJwtVc?: SdJwtVc<Header, Payload>; error: Error }\n  > {\n    const sdjwt = new SDJwtVcInstance({\n      ...this.getBaseSdJwtConfig(agentContext),\n      // We manually fetch later\n      loadTypeMetadataFormat: false,\n    })\n    let sdJwtVc: SDJwt<Header, Payload>\n    let holderBinding: SdJwtVcHolderBinding | undefined\n    let issuer: SdJwtVcIssuer\n\n    let trustedIssuers = _trustedIssuers\n    if (trustedCertificates) {\n      trustedIssuers = [...(trustedIssuers ?? []), ...legacyTrustedCertificatesToTrustedIssuers(trustedCertificates)]\n    }\n\n    try {\n      sdJwtVc = (await sdjwt.decode(compactSdJwtVc)) as SDJwt<Header, Payload>\n      if (!sdJwtVc.jwt) throw new CredoError('Invalid sd-jwt-vc')\n      holderBinding = parseHolderBindingFromCredential(sdJwtVc.jwt.payload) ?? undefined\n      issuer = parseIssuerFromCredential(sdJwtVc.jwt.header, sdJwtVc.jwt.payload)\n    } catch (error) {\n      return {\n        isValid: false,\n        error,\n      }\n    }\n\n    const returnSdJwtVc: SdJwtVc<Header, Payload> = {\n      payload: sdJwtVc.jwt.payload as Payload,\n      header: sdJwtVc.jwt.header as Header,\n      compact: compactSdJwtVc,\n      prettyClaims: await sdJwtVc.getClaims(sdJwtVcHasher),\n      holder: holderBinding,\n      issuer,\n      kbJwt: sdJwtVc.kbJwt\n        ? {\n            payload: sdJwtVc.kbJwt.payload as Record<string, unknown>,\n            header: sdJwtVc.kbJwt.header as Record<string, unknown>,\n          }\n        : undefined,\n      claimFormat: ClaimFormat.SdJwtDc,\n      encoded: compactSdJwtVc,\n    } satisfies SdJwtVc<Header, Payload>\n\n    let typeMetadataChain: NonEmptyArray<SdJwtVcTypeMetadata> | undefined\n    try {\n      const { trustedIssuer } = await this.verifyIssuer(agentContext, returnSdJwtVc, trustedIssuers)\n      const issuerWithKey = await this.extractKeyFromIssuer(agentContext, issuer)\n      const holder = returnSdJwtVc.holder\n        ? await extractKeyFromHolderBinding(agentContext, returnSdJwtVc.holder)\n        : undefined\n\n      const statusValidationDisabled = disableStatusValidation === true || verifyCredentialStatus === false\n\n      setJwkAlgFromJwtHeader(issuerWithKey.publicJwk, sdJwtVc.jwt.header?.alg)\n      if (holder && sdJwtVc.kbJwt) setJwkAlgFromJwtHeader(holder.publicJwk, sdJwtVc.kbJwt.header?.alg)\n\n      sdjwt.config({\n        verifier: getSdJwtVerifier(agentContext, issuerWithKey.publicJwk),\n        kbVerifier: holder ? getSdJwtVerifier(agentContext, holder.publicJwk) : undefined,\n        statusVerifier: this.getStatusVerifier(agentContext, {\n          matchedTrustedIssuer: trustedIssuer,\n          credentialIssuerKey: issuerWithKey.publicJwk,\n          credentialIssuerCertificateChain: issuer.method === 'x5c' ? issuer.x5c : undefined,\n        }),\n      })\n\n      try {\n        await sdjwt.verify(compactSdJwtVc, {\n          requiredClaimKeys: requiredClaimKeys ? [...requiredClaimKeys, 'vct'] : ['vct'],\n          keyBindingNonce: keyBinding?.nonce,\n          currentDate: dateToSeconds(now ?? new Date()),\n          skewSeconds: agentContext.config.validitySkewSeconds,\n          disableStatusVerification: statusValidationDisabled,\n        })\n      } catch (error) {\n        return {\n          error,\n          isValid: false,\n          sdJwtVc: returnSdJwtVc,\n        }\n      }\n\n      if (sdJwtVc.jwt.header?.typ !== 'vc+sd-jwt' && sdJwtVc.jwt.header?.typ !== 'dc+sd-jwt') {\n        return {\n          error: new SdJwtVcError(`SD-JWT VC header 'typ' must be 'dc+sd-jwt' or 'vc+sd-jwt'`),\n          isValid: false,\n          sdJwtVc: returnSdJwtVc,\n        }\n      }\n\n      try {\n        JwtPayload.fromJson(returnSdJwtVc.payload).validate({\n          now: dateToSeconds(now ?? new Date()),\n          skewSeconds: agentContext.config.validitySkewSeconds,\n        })\n      } catch (error) {\n        return {\n          error,\n          isValid: false,\n          sdJwtVc: returnSdJwtVc,\n        }\n      }\n\n      // If keyBinding is present, verify the key binding\n      try {\n        if (keyBinding) {\n          if (!sdJwtVc.kbJwt?.payload) {\n            throw new SdJwtVcError('Keybinding is required for verification of the sd-jwt-vc')\n          }\n\n          // Assert `aud` and `nonce` claims\n          if (sdJwtVc.kbJwt.payload.aud !== keyBinding.audience) {\n            throw new SdJwtVcError('The key binding JWT does not contain the expected audience')\n          }\n\n          if (sdJwtVc.kbJwt.payload.nonce !== keyBinding.nonce) {\n            throw new SdJwtVcError('The key binding JWT does not contain the expected nonce')\n          }\n        }\n      } catch (error) {\n        return {\n          error,\n          isValid: false,\n          sdJwtVc: returnSdJwtVc,\n        }\n      }\n\n      if (fetchTypeMetadata) {\n        // We allow vct without type metadata for now (and don't fail if the retrieval fails)\n        // Integrity check must pass though.\n        const resolvedTypeMetadata = await this.fetchTypeMetadata(agentContext, returnSdJwtVc, {\n          throwErrorOnFetchError: false,\n          throwErrorOnUnsupportedVctValue: false,\n        })\n\n        returnSdJwtVc.typeMetadata = resolvedTypeMetadata?.mergedTypeMetadata\n        typeMetadataChain = resolvedTypeMetadata?.typeMetadataChain\n      }\n    } catch (error) {\n      return {\n        isValid: false,\n        error,\n        sdJwtVc: returnSdJwtVc,\n      }\n    }\n\n    return {\n      isValid: true,\n      sdJwtVc: returnSdJwtVc,\n      typeMetadataChain,\n    }\n  }\n\n  /**\n   * Resolve the type metadata for an SD-JWT instance.\n   *\n   * This method resolves the `vct` value, and any `extends` values.\n   */\n  public async fetchTypeMetadata(\n    agentContext: AgentContext,\n    sdJwtVc: SdJwtVc,\n    {\n      throwErrorOnFetchError = true,\n      throwErrorOnUnsupportedVctValue = true,\n    }: { throwErrorOnFetchError?: boolean; throwErrorOnUnsupportedVctValue?: boolean } = {}\n  ) {\n    const sdjwt = new SDJwtVcInstance({\n      ...this.getBaseSdJwtConfig(agentContext),\n      vctFetcher: this.getVctFetcher(agentContext, {\n        baseVct: sdJwtVc.payload.vct,\n        throwErrorOnFetchError,\n        throwErrorOnUnsupportedVctValue,\n      }),\n    })\n\n    const typeMetadata = await sdjwt.getVct(sdJwtVc.compact)\n    return typeMetadata\n  }\n\n  public async store(agentContext: AgentContext, options: SdJwtVcStoreOptions) {\n    await this.sdJwtVcRepository.save(agentContext, options.record)\n    return options.record\n  }\n\n  public async getById(agentContext: AgentContext, id: string): Promise<SdJwtVcRecord> {\n    return await this.sdJwtVcRepository.getById(agentContext, id)\n  }\n\n  public async getAll(agentContext: AgentContext): Promise<Array<SdJwtVcRecord>> {\n    return await this.sdJwtVcRepository.getAll(agentContext)\n  }\n\n  public async findByQuery(\n    agentContext: AgentContext,\n    query: Query<SdJwtVcRecord>,\n    queryOptions?: QueryOptions\n  ): Promise<Array<SdJwtVcRecord>> {\n    return await this.sdJwtVcRepository.findByQuery(agentContext, query, queryOptions)\n  }\n\n  public async deleteById(agentContext: AgentContext, id: string) {\n    await this.sdJwtVcRepository.deleteById(agentContext, id)\n  }\n\n  public async update(agentContext: AgentContext, sdJwtVcRecord: SdJwtVcRecord) {\n    await this.sdJwtVcRepository.update(agentContext, sdJwtVcRecord)\n  }\n\n  private async extractKeyFromIssuer(agentContext: AgentContext, issuer: SdJwtVcIssuer, forSigning = false) {\n    if (issuer.method === 'did') {\n      const parsedDid = parseDid(issuer.didUrl)\n      if (!parsedDid.fragment) {\n        throw new SdJwtVcError(\n          `didUrl '${issuer.didUrl}' does not contain a '#'. Unable to derive key from did document`\n        )\n      }\n\n      let publicJwk: PublicJwk\n      if (forSigning) {\n        publicJwk = await resolveSigningPublicJwkFromDidUrl(agentContext, issuer.didUrl)\n      } else {\n        const { verificationMethod } = await resolveDidUrl(agentContext, issuer.didUrl)\n        publicJwk = getPublicJwkFromVerificationMethod(verificationMethod)\n      }\n\n      const supportedSignatureAlgorithms = publicJwk.supportedSignatureAlgorithms\n      if (supportedSignatureAlgorithms.length === 0) {\n        throw new SdJwtVcError(\n          `No supported JWA signature algorithms found for key ${publicJwk.jwkTypeHumanDescription}`\n        )\n      }\n      const alg = supportedSignatureAlgorithms[0]\n\n      return {\n        alg,\n        publicJwk,\n        iss: parsedDid.did,\n        kid: `#${parsedDid.fragment}`,\n      }\n    }\n\n    if (issuer.method === 'x5c') {\n      const leafCertificate = issuer.x5c[0]\n      if (!leafCertificate) {\n        throw new SdJwtVcError(\"Empty 'x5c' array provided\")\n      }\n\n      if (forSigning && !leafCertificate.publicJwk.hasKeyId) {\n        throw new SdJwtVcError(\"Expected leaf certificate in 'x5c' array to have a key id configured.\")\n      }\n\n      const publicJwk = leafCertificate.publicJwk\n      const supportedSignatureAlgorithms = publicJwk.supportedSignatureAlgorithms\n      if (supportedSignatureAlgorithms.length === 0) {\n        throw new SdJwtVcError(\n          `No supported JWA signature algorithms found for key ${publicJwk.jwkTypeHumanDescription}`\n        )\n      }\n      const alg = supportedSignatureAlgorithms[0]\n\n      this.assertValidX5cJwtIssuer(agentContext, issuer.issuer, leafCertificate)\n\n      return {\n        publicJwk,\n        iss: issuer.issuer,\n        x5c: issuer.x5c,\n        alg,\n      }\n    }\n\n    throw new SdJwtVcError(\"Unsupported credential issuer. Only 'did' and 'x5c' is supported at the moment.\")\n  }\n\n  private async verifyIssuer<Header extends SdJwtVcHeader, Payload extends SdJwtVcPayload>(\n    agentContext: AgentContext,\n    sdJwtVc: SdJwtVc<Header, Payload>,\n    trustedIssuers?: TrustedIssuer[]\n  ) {\n    const x509Config = agentContext.dependencyManager.resolve(X509ModuleConfig)\n\n    const issuer = sdJwtVc.issuer\n    if (!issuer) {\n      throw new SdJwtVcError('Unsupported signing method for SD-JWT VC. Only did and x5c are supported at the moment.')\n    }\n\n    if (issuer.method === 'x5c') {\n      // NOTE: we can't use the 'simpler' call directly to `ensureTrustedSigner` due to having to incorporate the\n      // legacy X509 API. In the future we can simplify this.\n      let x509Issuers = trustedIssuers?.filter((t) => t.method === 'x509')\n\n      const context = {\n        verification: { type: 'credential', credential: sdJwtVc },\n        signer: {\n          certificateChain: issuer.x5c,\n          method: 'x509',\n        },\n      } as const\n\n      // `trustedIssuers` may already be populated by a caller that pre-resolved trust with a richer\n      // context (e.g. OpenID4VP passing the `oid4VpCredential` context). When it didn't (value is\n      // `undefined`), we resolve here with the plain `credential` context; the decision is the same.\n      if (!x509Issuers) {\n        x509Issuers = (await TrustedIssuerContext.getTrustedIssuersForVerification(agentContext, context))\n          ?.trustedIssuers\n      }\n\n      // Fall back to legacy x509-specific API\n      if (!x509Issuers) {\n        const legacyTrustedCertificates =\n          (await x509Config.getTrustedCertificatesForVerification?.(agentContext, {\n            certificateChain: issuer.x5c,\n            verification: {\n              type: 'credential',\n              credential: sdJwtVc,\n            },\n          })) ?? x509Config.trustedCertificates\n\n        if (legacyTrustedCertificates) {\n          x509Issuers = legacyTrustedCertificatesToTrustedIssuers(legacyTrustedCertificates)\n        }\n      }\n\n      if (!x509Issuers) {\n        throw new SdJwtVcError(\n          'No trusted certificates configured for X509 certificate chain validation. Issuer cannot be verified.'\n        )\n      }\n\n      return await TrustedIssuerContext.ensureTrustedSigner(agentContext, context, x509Issuers)\n    }\n\n    if (issuer.method === 'did') {\n      // `ensureTrustedSigner` consults the `getTrustedIssuersForVerification` callback and, to mimic\n      // the original behavior, allows the did by default when neither explicit trusted issuers nor the\n      // callback return any trusted issuers.\n      return await TrustedIssuerContext.ensureTrustedSigner(\n        agentContext,\n        {\n          verification: { type: 'credential', credential: sdJwtVc },\n          signer: {\n            didUrl: issuer.didUrl,\n            method: 'did',\n          },\n        },\n        trustedIssuers\n      )\n    }\n\n    throw new SdJwtVcError('Unsupported signing method for SD-JWT VC. Only did and x5c are supported at the moment.')\n  }\n\n  private getBaseSdJwtConfig(agentContext: AgentContext): SDJWTVCConfig {\n    const kms = agentContext.resolve(KeyManagementApi)\n\n    return {\n      hasher: sdJwtVcHasher,\n      statusListFetcher: this.getStatusListFetcher(agentContext),\n      saltGenerator: (length) => TypedArrayEncoder.toBase64Url(kms.randomBytes({ length })).slice(0, length),\n    }\n  }\n\n  private getStatusListFetcher(agentContext: AgentContext) {\n    return async (uri: string) => {\n      const response = await fetchWithTimeout(agentContext.config.agentDependencies.fetch, uri, {\n        headers: {\n          Accept: 'application/statuslist+jwt',\n        },\n      })\n\n      if (!response.ok) {\n        throw new CredoError(\n          `Received invalid response with status ${\n            response.status\n          } when fetching status list from ${uri}. ${await response.text()}`\n        )\n      }\n\n      return await response.text()\n    }\n  }\n\n  /**\n   * Builds a `Verifier` for the status list JWT signature, gated by the trusted issuer that was matched\n   * for the credential issuer (the status list signer is not always the credential issuer).\n   *\n   * The library's `Verifier` only receives the unsigned token (`<header>.<payload>`) and the signature,\n   * so the status list JWT's own header (`x5c`/`kid`) is recovered by decoding the first segment.\n   */\n  private getStatusVerifier(\n    agentContext: AgentContext,\n    {\n      matchedTrustedIssuer,\n      credentialIssuerKey,\n      credentialIssuerCertificateChain,\n    }: {\n      matchedTrustedIssuer: TrustedIssuer | undefined\n      credentialIssuerKey: PublicJwk\n      credentialIssuerCertificateChain?: X509Certificate[]\n    }\n  ): Verifier {\n    return async (data, signatureBase64Url) => {\n      // A failure to extract or authorize the status list signer is thrown (rather than returning\n      // `false`) so the verification result carries the actual reason instead of a generic\n      // \"invalid signature\". Only the final signature check returns a boolean.\n      let header: { alg?: string; x5c?: string[]; kid?: string }\n      try {\n        header = JsonEncoder.fromBase64Url(data.split('.')[0])\n      } catch (error) {\n        throw new SdJwtVcError('Unable to decode the status list JWT header to extract the status list signer.', {\n          cause: error,\n        })\n      }\n\n      // No matched trusted issuer (e.g. did default-allow path with no configured trusted issuers).\n      // Preserve the previous behavior of verifying the status list with the credential issuer key.\n      if (!matchedTrustedIssuer) {\n        // Copy the jwk, so the alg of the status list does not affect verification of the credential itself\n        const signerJwk = PublicJwk.fromUnknown(credentialIssuerKey.toJson())\n        setJwkAlgFromJwtHeader(signerJwk, header.alg)\n        return getSdJwtVerifier(agentContext, signerJwk)(data, signatureBase64Url)\n      }\n\n      if (matchedTrustedIssuer.method === 'x509') {\n        if (!credentialIssuerCertificateChain) {\n          throw new SdJwtVcError('Missing credential issuer certificate chain for x509 status list verification.')\n        }\n\n        const hasDedicatedStatusCertificates = matchedTrustedIssuer.status !== undefined\n        const statusCertificates = matchedTrustedIssuer.status ?? matchedTrustedIssuer.issuance\n\n        if (!header.x5c?.length) {\n          throw new SdJwtVcError('Unable to extract the status list signer: the status list JWT has no x5c header.')\n        }\n        if (statusCertificates.length === 0) {\n          throw new SdJwtVcError(\n            'No trusted status list certificates configured for the trusted issuer. The status list signer cannot be verified.'\n          )\n        }\n\n        try {\n          // Trust check only: ensure the status list certificate chain anchors in the status certificates.\n          await X509Service.validateCertificateChain(agentContext, {\n            certificateChain: header.x5c,\n            trustedCertificates: statusCertificates,\n          })\n        } catch (error) {\n          throw new SdJwtVcError(\n            'The status list certificate chain could not be validated against the trusted status certificates.',\n            { cause: error }\n          )\n        }\n\n        // Mirror mdoc: when no dedicated status certificate is configured, the status list must\n        // be signed by the exact same key as the credential issuer.\n        const statusListChain = header.x5c.map((certificate) => X509Certificate.fromEncodedCertificate(certificate))\n        const chainMatchesCredentialIssuer =\n          statusListChain.length === credentialIssuerCertificateChain.length &&\n          statusListChain.every((certificate, index) => certificate.equal(credentialIssuerCertificateChain[index]))\n        if (!hasDedicatedStatusCertificates && !chainMatchesCredentialIssuer) {\n          throw new SdJwtVcError(\n            'The status list signer chain does not match the credential issuer chain, and no dedicated trusted status certificates were configured for the trusted issuer.'\n          )\n        }\n\n        const signerJwk = statusListChain[0].publicJwk\n        setJwkAlgFromJwtHeader(signerJwk, header.alg)\n        return getSdJwtVerifier(agentContext, signerJwk)(data, signatureBase64Url)\n      }\n\n      // did: require the status list signer did to equal the trusted issuer did. The signer did is the\n      // `iss` of the status list payload; the `kid` header is typically a relative reference (e.g.\n      // `#key-1`) that has to be resolved against that did.\n      let statusListIssuerDid: unknown\n      try {\n        statusListIssuerDid = JsonEncoder.fromBase64Url(data.split('.')[1]).iss\n      } catch (error) {\n        throw new SdJwtVcError('Unable to decode the status list JWT payload to extract the status list signer.', {\n          cause: error,\n        })\n      }\n\n      if (typeof statusListIssuerDid !== 'string') {\n        throw new SdJwtVcError('Unable to extract the status list signer: the status list JWT payload has no `iss`.')\n      }\n      if (parseDid(statusListIssuerDid).did !== parseDid(matchedTrustedIssuer.issuance).did) {\n        throw new SdJwtVcError(\n          `The status list signer did '${parseDid(statusListIssuerDid).did}' does not match the trusted issuer did.`\n        )\n      }\n\n      const didUrl = header.kid?.startsWith('#') ? `${statusListIssuerDid}${header.kid}` : header.kid\n      if (!didUrl) {\n        throw new SdJwtVcError('Unable to resolve the status list signer: the status list JWT has no `kid` header.')\n      }\n\n      const { verificationMethod } = await resolveDidUrl(agentContext, didUrl)\n      const publicJwk = getPublicJwkFromVerificationMethod(verificationMethod)\n      setJwkAlgFromJwtHeader(publicJwk, header.alg)\n      return getSdJwtVerifier(agentContext, publicJwk)(data, signatureBase64Url)\n    }\n  }\n\n  private getVctFetcher(\n    agentContext: AgentContext,\n    {\n      baseVct,\n      throwErrorOnFetchError = true,\n      throwErrorOnUnsupportedVctValue = true,\n    }: { baseVct: string; throwErrorOnFetchError?: boolean; throwErrorOnUnsupportedVctValue?: boolean }\n  ): VCTFetcher {\n    const sdJwtVcConfig = agentContext.dependencyManager.resolve(SdJwtVcModuleConfig)\n    return async (uri: string, integrity) => {\n      if (sdJwtVcConfig.customTypeMetadataResolver) {\n        const customTypeMetadata = await sdJwtVcConfig.customTypeMetadataResolver(uri, integrity, {\n          isExtendedVct: uri !== baseVct,\n          defaultResolver: (userOverrideOptions) =>\n            this.httpsTypeMetadataResolver(agentContext, uri, integrity, {\n              throwErrorOnFetchError: userOverrideOptions.throwErrorOnFetchError ?? throwErrorOnFetchError,\n              throwErrorOnUnsupportedVctValue:\n                userOverrideOptions.throwErrorOnUnsupportedVctValue ?? throwErrorOnUnsupportedVctValue,\n              isExtendedVct: uri !== baseVct,\n            }),\n        })\n\n        return customTypeMetadata as SdJwtVcTypeMetadata | undefined\n      }\n\n      if (!uri.startsWith('https://')) {\n        if (!throwErrorOnUnsupportedVctValue) return undefined\n        throw new SdJwtVcError(\n          `Unable to resolve type metadata for vct '${uri}'. Only https supported and no 'customTypeMetadataResolver' provided in agent config.`\n        )\n      }\n\n      const defaultTypeMetadata = await this.httpsTypeMetadataResolver(agentContext, uri, integrity, {\n        throwErrorOnFetchError,\n        throwErrorOnUnsupportedVctValue,\n        isExtendedVct: uri !== baseVct,\n      })\n      return defaultTypeMetadata as SdJwtVcTypeMetadata | undefined\n    }\n  }\n\n  private async httpsTypeMetadataResolver(\n    agentContext: AgentContext,\n    vct: string,\n    integrity: string | undefined,\n    {\n      throwErrorOnFetchError,\n      throwErrorOnUnsupportedVctValue,\n      isExtendedVct,\n    }: { throwErrorOnFetchError: boolean; throwErrorOnUnsupportedVctValue: boolean; isExtendedVct?: boolean }\n  ) {\n    if (!vct.startsWith('https://')) {\n      if (!throwErrorOnUnsupportedVctValue) return undefined\n      throw new SdJwtVcError(\n        `Unable to resolve type metadata for vct '${vct}'. Only https supported for default resolver`\n      )\n    }\n    let firstError: Error | undefined\n\n    // Fist try the new type metadata URL\n    // We add a catch, so that if e.g. the request fails due to CORS (which throws an error\n    // we will still continue trying the legacy url)\n    const firstResponse = await fetchWithTimeout(agentContext.config.agentDependencies.fetch, vct).catch((error) => {\n      firstError = error\n      return undefined\n    })\n    let response = firstResponse\n\n    // If the response is not ok, try the legacy URL (will be removed in 0.7)\n    if (!response?.ok) {\n      // modify the uri based on https://www.ietf.org/archive/id/draft-ietf-oauth-sd-jwt-vc-04.html#section-6.3.1\n      const vctElements = vct.split('/')\n      vctElements.splice(3, 0, '.well-known/vct')\n      const legacyVctUrl = vctElements.join('/')\n\n      response = await fetchWithTimeout(agentContext.config.agentDependencies.fetch, legacyVctUrl).catch(\n        () => undefined\n      )\n    }\n\n    if (!response?.ok) {\n      if (!throwErrorOnFetchError) return undefined\n\n      if (firstResponse) {\n        throw new SdJwtVcError(\n          `Unable to resolve type metadata vct '${vct}'. Fetch returned a non-successful ${firstResponse.status} response. ${await firstResponse.text()}.`,\n          { cause: firstError }\n        )\n      } else {\n        throw new SdJwtVcError(\n          `Unable to resolve type metadata vct '${vct}'. Fetch returned a non-successful response.`,\n          { cause: firstError }\n        )\n      }\n    }\n\n    const typeMetadata = (await response.clone().json()) as Record<string, unknown>\n    if (integrity) {\n      if (typeof integrity !== 'string') {\n        throw new SdJwtVcError(\n          `Found '${isExtendedVct ? 'extends' : 'vct'}#integrity' with value '${integrity}' but value was not of type 'string'.`\n        )\n      }\n\n      IntegrityVerifier.verifyIntegrity(new Uint8Array(await response.arrayBuffer()), integrity)\n    }\n\n    return typeMetadata\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+GO,IAAM,iBAAN,MAAM,eAAe;CAC1B,YAAmB,mBAA8C;EAAtC,KAAA,oBAAA;CAAuC;CAElE,MAAa,KACX,cACA,SACkB;EAClB,MAAM,EAAE,SAAS,iBAAiB,qBAAqB;EAEvD,MAAM,SAAS,MAAM,KAAK,qBAAqB,cAAc,QAAQ,QAAQ,IAAI;EAGjF,MAAM,gBAAgB,QAAQ,SAAS,MAAM,4BAA4B,cAAc,QAAQ,MAAM,IAAI,KAAA;EAEzG,MAAM,SAAS;GACb,KAAK,OAAO;GACZ,KAAK,QAAQ,cAAc;GAC3B,KAAK,OAAO;GACZ,KAAK,OAAO,KAAK,KAAK,SAAS,KAAK,SAAS,QAAQ,CAAC;EACxD;EAEA,OAAO,UAAU,MAAM,OAAO;EAE9B,MAAM,QAAQ,IAAI,gBAAgB;GAChC,GAAG,KAAK,mBAAmB,YAAY;GACvC,QAAQ,eAAe,cAAc,OAAO,SAAS;GACrD,SAAS,yBAAyB,gBAAgB;GAClD,SAAS,OAAO;EAClB,CAAC;EAED,IAAI,CAAC,QAAQ,OAAO,OAAO,QAAQ,QAAQ,UACzC,MAAM,IAAI,aAAa,kCAAkC;EAG3D,MAAM,EAAE,KAAK,YAAY,GAAG,sBAAsB;EAClD,MAAM,UAAU,MAAM,MAAM,MAC1B;GACE,GAAG;GACH,KAAK,eAAe;GACpB,KAAK,OAAO;GACZ,GAAI,eAAe,OAAO,CAAC,IAAI,EAAE,KAAK,cAAc,aAAa,EAAE;GACnE,KAAK,QAAQ;EACf,GACA,iBACA,EAAE,OAAO,CACX;EAEA,MAAM,eAAgB,MAAM,MAAM,UAAU,OAAO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