All files / src/CommonNetworkMember BaseNetworkMember.ts

64.34% Statements 166/258
59.48% Branches 69/116
65.3% Functions 32/49
64.42% Lines 163/253

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 11551x 1x 1x 1x             1x 1x                   1x   1x 1x   1x                                     1x     1x 1x 1x   1x 1x 1x 1x 1x   1x   1x 256x                                   1x                                               152x 152x 152x             152x 152x 152x 152x                           152x 152x 152x   152x   152x 152x 152x 152x 152x           152x           152x                           152x 152x 152x 152x 152x 152x 152x   152x 152x               5x               2x                                                         59x 59x 59x 59x                                                                                                     11x   10x                                                                                                   2x     2x 2x 2x         2x                                                         11x         10x 10x                   10x   9x   9x       2x   2x                                         5x           5x 5x                     5x   5x   5x                 6x   6x   6x   6x       2x   2x                                                                                                               4x           3x   3x 3x         3x 3x 1x     2x           2x   2x               34x               22x                                                           1x 1x       1x         1x 1x   1x             1x           1x   1x 1x   1x                                                                                                 1x                                                                                                               2x             2x         2x                                                     8x 8x 6x     8x           8x   7x 2x 2x 2x   2x 1x     1x 1x           6x           5x   5x                                         3x         2x   2x   1x   1x   1x                                                                                                                                                                                                                                                                                                                                                 6x       5x                   2x                 11x                   5x                 5x               3x                   14x 4x     10x                 3x                             3x   3x 2x     3x   3x                         5x     5x 1x 1x                   4x   4x     4x 4x                   3x   1x     3x 1x     2x 1x     1x      
import { DidDocumentService, JwtService, KeysService, Affinity } from '@affinidi/common'
import { fetch } from '@affinidi/platform-fetch'
import { DidAuthClientService, Signer } from '@affinidi/affinidi-did-auth-lib'
import {
  IssuerApiService,
  RegistryApiService,
  RevocationApiService,
  VerifierApiService,
} from '@affinidi/internal-api-clients'
import { EventComponent } from '@affinidi/affinity-metrics-lib'
import { profile } from '@affinidi/tools-common'
import {
  buildVCV1Skeleton,
  buildVCV1Unsigned,
  buildVPV1Unsigned,
  VCV1,
  VCV1SubjectBaseMA,
  VCV1Unsigned,
  VPV1,
  VPV1Unsigned,
} from '@affinidi/vc-common'
import { parse } from 'did-resolver'
 
import { extractSDKVersion, isW3cCredential } from '../_helpers'
import { DEFAULT_DID_METHOD, ELEM_DID_METHOD, SUPPORTED_DID_METHODS } from '../_defaultConfig'
 
import {
  ClaimMetadata,
  SignedCredential,
  SignCredentialOptionalInput,
  OfferedCredential,
  CredentialRequirement,
  JwtOptions,
  KeyParams,
  KeyAlgorithmType,
  KeyOptions,
  DidMethod,
} from '../dto/shared.dto'
 
import {
  CredentialShareResponseOutput,
  CredentialOfferResponseOutput,
  PresentationValidationOutput,
} from '../dto/verifier.dto'
 
import { DidAuthAdapter } from '../shared/DidAuthAdapter'
import { ParsedOptions } from '../shared/getOptionsFromEnvironment'
import { IPlatformCryptographyTools } from '../shared/interfaces'
import { ParametersValidator } from '../shared/ParametersValidator'
import { randomBytes } from '../shared/randomBytes'
import SdkErrorFromCode from '../shared/SdkErrorFromCode'
 
import { anchorDid } from '../services/anchoringHandler'
import HolderService from '../services/HolderService'
import KeyManagementService from '../services/KeyManagementService'
import { register } from '../services/registeringHandler'
import WalletStorageService from '../services/WalletStorageService'
 
import { Util } from './Util'
 
export const createKeyManagementService = ({ basicOptions, accessApiKey, otherOptions }: ParsedOptions) => {
  return new KeyManagementService({ ...basicOptions, accessApiKey, tenantToken: otherOptions.tenantToken })
}
 
export type StaticDependencies = {
  platformCryptographyTools: IPlatformCryptographyTools
  eventComponent: EventComponent
}
 
export type ConstructorUserData = {
  didDocument?: any
  did: string
  didDocumentKeyId: string
  encryptedSeed: string
  password: string
  accountNumber?: number
}
 
@profile()
export abstract class BaseNetworkMember {
  readonly didDocument?: any
  readonly accountNumber?: number
  private readonly _did: string
  private readonly _encryptedSeed: string
  private readonly _password: string
  protected readonly _walletStorageService: WalletStorageService
  private readonly _holderService: HolderService
  private readonly _issuerApiService
  private readonly _verifierApiService
  private readonly _registryApiService
  private readonly _revocationApiService
  protected readonly _keyManagementService
  protected readonly _affinity
  protected readonly _options
  private readonly _didDocumentKeyId: string
  protected readonly _component: EventComponent
  protected readonly _platformCryptographyTools
 
  constructor(
    { didDocument, did, didDocumentKeyId, encryptedSeed, password, accountNumber }: ConstructorUserData,
    { platformCryptographyTools, eventComponent }: StaticDependencies,
    options: ParsedOptions,
  ) {
    const isKeyManagerExternal = !!options.otherOptions.keyManager
    const isSeedLocal = did && didDocumentKeyId && encryptedSeed && password
    Iif (!did || !didDocumentKeyId || (!isSeedLocal && !isKeyManagerExternal)) {
      // TODO: implement appropriate error wrapper
      throw new Error(
        '`did`, `didDocumentKeyId`, `encryptedSeed` and `password` OR `did`, `didDocumentKeyId`, `keyManager` must be provided!',
      )
    }
 
    const { accessApiKey, basicOptions, storageRegion } = options
    const { issuerUrl, revocationUrl, metricsUrl, registryUrl, verifierUrl, affinidiVaultUrl } = basicOptions
    const keysService = new KeysService(encryptedSeed, password, accountNumber)
    this._affinity = new Affinity(
      {
        apiKey: accessApiKey,
        registryUrl: registryUrl,
        metricsUrl: metricsUrl,
        component: eventComponent,
        resolveLegacyElemLocally: options.otherOptions?.resolveLocallyElemMethod,
        resolveKeyLocally: options.otherOptions?.resolveKeyLocally,
        beforeDocumentLoader: options.otherOptions?.beforeDocumentLoader,
        keyManager: options.otherOptions?.keyManager,
        keysService: keysService,
      },
      platformCryptographyTools,
    )
    const signer = new Signer({ did, keyId: didDocumentKeyId, keyVault: this._affinity })
    const didAuthService = new DidAuthClientService(signer)
    const didAuthAdapter = new DidAuthAdapter(did, didAuthService)
 
    const sdkVersion = extractSDKVersion()
 
    this._registryApiService = new RegistryApiService({ registryUrl, accessApiKey, sdkVersion })
    this._issuerApiService = new IssuerApiService({ issuerUrl, accessApiKey, sdkVersion })
    this._verifierApiService = new VerifierApiService({ verifierUrl, accessApiKey, sdkVersion })
    this._keyManagementService = createKeyManagementService(options)
    this._revocationApiService = new RevocationApiService({
      revocationUrl,
      accessApiKey,
      sdkVersion,
      didAuthAdapter,
    })
    this._walletStorageService = new WalletStorageService(this._affinity.getKeyManager(), {
      affinidiVaultUrl,
      accessApiKey,
      storageRegion,
      didAuthAdapter,
    })
    this._holderService = new HolderService(
      {
        registryUrl,
        metricsUrl,
        accessApiKey,
        keyManager: options.otherOptions?.keyManager,
        keysService: keysService,
      },
      platformCryptographyTools,
      eventComponent,
      options.otherOptions?.resolveLocallyElemMethod,
      options.otherOptions?.beforeDocumentLoader,
    )
 
    this._options = options
    this._component = eventComponent
    this._encryptedSeed = encryptedSeed
    this._password = password
    this._did = did
    this._didDocumentKeyId = didDocumentKeyId
    this._platformCryptographyTools = platformCryptographyTools
 
    this.accountNumber = accountNumber
    this.didDocument = didDocument
  }
 
  /**
   * @description Returns user's encrypted seed
   * @returns encrypted seed
   */
  get encryptedSeed(): string {
    return this._encryptedSeed
  }
 
  /**
   * @description Returns user's password
   * @returns encrypted seed
   */
  get password(): string {
    return this._password
  }
 
  /**
   * @description Creates DID and anchors it
   * 1. generate seed/keys
   * 2. build DID document
   * 3. sign DID document
   * 4. store DID document in IPFS
   * 5. anchor DID with DID document ID from IPFS
   * @param dependencies
   * @param password - encryption key which will be used to encrypt randomly created seed/keys pair
   * @param options - optional parameter { registryUrl: 'https://affinity-registry.apse1.dev.affinidi.io' }
   * @param keyOptions
   * @returns
   *
   * did - hash from public key (your decentralized ID)
   *
   * encryptedSeed - seed is encrypted by provided password. Seed - it's a source to derive your keys
   */
  protected static async _register(
    dependencies: StaticDependencies,
    options: ParsedOptions,
    password: string,
    keyOptions?: KeyOptions,
  ) {
    const {
      basicOptions: { registryUrl },
      accessApiKey,
    } = options
    const api = new RegistryApiService({ registryUrl, accessApiKey, sdkVersion: extractSDKVersion() })
    const didMethod = options.otherOptions.didMethod || DEFAULT_DID_METHOD
    return register(
      api,
      didMethod,
      dependencies.platformCryptographyTools,
      password,
      keyOptions,
      options.origin,
      options.otherOptions.skipAnchoringForElemMethod,
      options.otherOptions.webDomain,
    )
  }
 
  protected static async _anchorDid(
    encryptedSeed: string,
    password: string,
    didDocument: any,
    nonce: number,
    {
      basicOptions: { registryUrl },
      accessApiKey,
      origin,
      otherOptions: { skipAnchoringForElemMethod },
    }: ParsedOptions,
  ) {
    const registry = new RegistryApiService({ registryUrl, accessApiKey, sdkVersion: extractSDKVersion() })
    const keysService = new KeysService(encryptedSeed, password)
    const { seed, didMethod } = keysService.decryptSeed()
    const didService = DidDocumentService.createDidDocumentService(keysService)
    return didMethod == ELEM_DID_METHOD && skipAnchoringForElemMethod
      ? { did: didService.getMyDid() }
      : anchorDid({
          registry,
          anchoredDidElem: false,
          did: didService.getMyDid(),
          didMethod: didMethod as DidMethod,
          keysService,
          nonce,
          additionalJoloParams: {
            didDocument,
            seedHex: seed.toString('hex'),
          },
          origin: origin || '',
        })
  }
 
  /**
   * @description Resolves DID
   * @param did - decentralized ID
   * @returns DID document
   */
  async resolveDid(did: string) {
    await ParametersValidator.validate([{ isArray: false, type: 'did', isRequired: true, value: did }])
 
    return this._affinity.resolveDid(did)
  }
 
  /**
   * @description Update DidDocument , supporting only jolo method at this point
   * @param didDocument - updated did document
   * @returns void
   */
  async updateDidDocument(didDocument: any) {
    // TODO: validate didDocument structure
    await ParametersValidator.validate([{ isArray: false, type: 'object', isRequired: true, value: didDocument }])
 
    const did = didDocument.id
    const isJoloMethod = did.startsWith('did:jolo')
    if (!isJoloMethod) {
      throw new SdkErrorFromCode('COR-20', { did })
    }
 
    const instanceDid = this.did
    if (instanceDid !== did) {
      throw new SdkErrorFromCode('COR-21', { did, instanceDid })
    }
 
    const ethereumPublicKeyHex = await this._affinity.getAnchorTransactionPublicKey()
 
    const {
      body: { transactionCount },
    } = await this._registryApiService.transactionCount({ ethereumPublicKeyHex })
 
    const nonce = transactionCount
 
    await BaseNetworkMember._anchorDid(this._encryptedSeed, this._password, didDocument, nonce, this._options)
  }
 
  getShareCredential(
    credentialShareRequestToken: string,
    options: { credentials: SignedCredential[] },
  ): SignedCredential[] {
    const { credentials } = options
    const credentialShareRequest = Util.fromJWT(credentialShareRequestToken)
    const types = this.getCredentialTypes(credentialShareRequest)
 
    const filteredCredentials = credentials.filter((cred: SignedCredential) => {
      return types.includes(cred.type[1])
    })
 
    return filteredCredentials
  }
 
  protected static _validateKeys(keyParams: KeyParams) {
    const { encryptedSeed, password } = keyParams
 
    let didMethod: DidMethod
    try {
      const keysService = new KeysService(encryptedSeed, password)
      didMethod = keysService.decryptSeed().didMethod as DidMethod
    } catch (error) {
      throw new SdkErrorFromCode('COR-24', {}, error)
    }
 
    Iif (!SUPPORTED_DID_METHODS.includes(didMethod)) {
      const supportedDidMethods = SUPPORTED_DID_METHODS.join(', ')
      throw new SdkErrorFromCode('COR-25', { didMethod, supportedDidMethods })
    }
  }
 
  /* istanbul ignore next: protected method */
  protected async saveEncryptedCredentials(data: any, storageRegion?: string): Promise<any[]> {
    return this._walletStorageService.saveCredentials(data, storageRegion)
  }
 
  /**
   * @description Creates JWT of credential offer request
   * @param offeredCredentials - array of credentials to be offered
   * @param options - optional, JwtOptions containing:
   *
   *   audienceDid (string) - audience of generated token
   *
   *   expiresAt (isoString) - expire date-time of generated token
   *
   *   nonce (string) - nonce/jti of generated token
   *
   *   callbackUrl (string)
   * @returns JWT
   */
  async generateCredentialOfferRequestToken(
    offeredCredentials: OfferedCredential[],
    options?: JwtOptions,
  ): Promise<string> {
    await ParametersValidator.validate([
      { isArray: true, type: OfferedCredential, isRequired: true, value: offeredCredentials },
      { isArray: false, type: JwtOptions, isRequired: false, value: options },
    ])
 
    const { audienceDid, expiresAt, nonce, callbackUrl } = options ?? {}
    const params = {
      offeredCredentials,
      audienceDid,
      expiresAt,
      nonce,
      callbackUrl,
    }
 
    const {
      body: { credentialOffer },
    } = await this._issuerApiService.buildCredentialOffer(params)
 
    const signedObject = await this._affinity.signJWTObject(credentialOffer as any, this.didDocumentKeyId)
 
    return JwtService.encodeObjectToJWT(signedObject)
  }
 
  async generateDidAuthRequest(options?: JwtOptions): Promise<string> {
    await ParametersValidator.validate([{ isArray: false, type: JwtOptions, isRequired: false, value: options }])
 
    return this.generateCredentialShareRequestToken([], null, options)
  }
 
  /**
   * @description Creates JWT of credential share request
   * @param credentialRequirements - array of credential requirements with credential types
   * @param issuerDid - DID of the issuer
   * @param options - optional, JwtOptions containing:
   *
   *   audienceDid (string) - audience of generated token
   *
   *   expiresAt (isoString) - expire date-time of generated token
   *
   *   nonce (number) - nonce/jti of generated token
   * @returns JWT
   */
  async generateCredentialShareRequestToken(
    credentialRequirements: CredentialRequirement[],
    issuerDid: string = undefined,
    options?: JwtOptions,
  ): Promise<string> {
    await ParametersValidator.validate([
      { isArray: true, type: CredentialRequirement, isRequired: true, value: credentialRequirements },
      { isArray: false, type: 'did', isRequired: false, value: issuerDid },
      { isArray: false, type: JwtOptions, isRequired: false, value: options },
    ])
 
    const { audienceDid, expiresAt, nonce, callbackUrl } = options ?? {}
    const params = {
      credentialRequirements,
      issuerDid,
      audienceDid,
      expiresAt,
      nonce,
      callbackUrl,
    }
 
    const {
      body: { credentialShareRequest },
    } = await this._verifierApiService.buildCredentialRequest(params)
 
    const signedObject = await this._affinity.signJWTObject(credentialShareRequest as any, this.didDocumentKeyId)
 
    return JwtService.encodeObjectToJWT(signedObject)
  }
 
  /**
   * @description Creates JWT of credential offer response
   * @param credentialOfferToken - JWT with offered credentials
   * @returns JWT
   */
  async createCredentialOfferResponseToken(credentialOfferToken: string): Promise<string> {
    await ParametersValidator.validate([{ isArray: false, type: 'jwt', isRequired: true, value: credentialOfferToken }])
 
    const credentialOfferResponse = await this._holderService.buildCredentialOfferResponse(credentialOfferToken)
 
    const signedObject = await this._affinity.signJWTObject(credentialOfferResponse, this.didDocumentKeyId)
 
    return JwtService.encodeObjectToJWT(signedObject)
  }
 
  async createDidAuthResponse(didAuthRequestToken: string, expiresAt?: string): Promise<string> {
    await ParametersValidator.validate([{ isArray: false, type: 'jwt', isRequired: true, value: didAuthRequestToken }])
 
    return this.createCredentialShareResponseToken(didAuthRequestToken, [], expiresAt)
  }
 
  // NOTE: to be removed after support of legacy credentials is dropped
  /* istanbul ignore next: private method */
  private _validateSignedCredentialsSupportedStructures(credentials: SignedCredential[]) {
    const errors: string[] = []
 
    for (const credential of credentials) {
      const hasIssuedDate = typeof credential.issued !== 'undefined'
      const hasIssuanceDate = typeof credential.issuanceDate !== 'undefined'
      const isLegacyCredential = typeof credential.claim !== 'undefined'
      const hasCredentialSubject = typeof credential.credentialSubject !== 'undefined'
 
      if (isLegacyCredential) {
        if (!hasIssuedDate) {
          const error = 'Parameter "issued" is missing for SignedCredential'
 
          errors.push(error)
        }
 
        continue
      }
 
      if (!hasIssuanceDate) {
        const error = 'Parameter "issuanceDate" is missing for SignedCredential'
 
        errors.push(error)
      }
 
      if (!hasCredentialSubject) {
        const error = 'Parameter "credentialSubject" is missing for SignedCredential'
 
        errors.push(error)
      }
    }
 
    const areCredentialsValid = errors.length === 0
 
    if (!areCredentialsValid) {
      throw new SdkErrorFromCode('COR-1', { errors, credentials })
    }
  }
 
  /**
   * @description Creates JWT of credential share response
   * @param credentialShareRequestToken - JWT with the requested VCs
   * @param suppliedCredentials - array of signed credentials
   * @param expiresAt (isoString) - optional, expire date-time of generated token
   * @returns JWT
   */
  async createCredentialShareResponseToken(
    credentialShareRequestToken: string,
    suppliedCredentials: SignedCredential[],
    expiresAt?: string,
  ): Promise<string> {
    await ParametersValidator.validate([
      { isArray: false, type: 'jwt', isRequired: true, value: credentialShareRequestToken },
      { isArray: true, type: SignedCredential, isRequired: true, value: suppliedCredentials },
      { isArray: false, type: 'string', isRequired: false, value: expiresAt },
    ])
 
    this._validateSignedCredentialsSupportedStructures(suppliedCredentials)
    let tokenDecoded: any
    try {
      tokenDecoded = JwtService.fromJWT(credentialShareRequestToken)
    } catch (error) {
      throw new Error(`Token can't be decoded`)
    }
 
    const { exp } = tokenDecoded.payload
    if (!exp || (expiresAt && exp > new Date(expiresAt).getTime())) {
      throw new Error('expiresAt of response token should be greater than expiresAt of request token.')
    }
 
    const credentialResponse = await this._holderService.buildCredentialResponse(
      credentialShareRequestToken,
      suppliedCredentials,
      expiresAt,
    )
 
    const signedObject = await this._affinity.signJWTObject(credentialResponse, this.didDocumentKeyId)
 
    return JwtService.encodeObjectToJWT(signedObject)
  }
 
  /**
   * @description Returns user's DID
   * @returns DID
   */
  get did() {
    return this._did
  }
 
  /**
   * @description Returns user's DID document key ID
   * @returns key ID
   */
  get didDocumentKeyId() {
    return this._didDocumentKeyId
  }
 
  /**
   * @description Returns credential types credential request token
   * @param credentialRequest - object with credential requirements
   * @returns array of credential types
   */
  getCredentialTypes(credentialRequest: any): any[] {
    // await ParametersValidator.validateSync(
    //   [
    //     { isArray: false, type: 'object', isRequired: true, value: credentialRequest }
    //   ]
    // )
 
    const { interactionToken } = credentialRequest.payload
    const { credentialRequirements } = interactionToken
    const credentialTypes = []
 
    for (const credential of credentialRequirements) {
      if (isW3cCredential(credential)) {
        const type = credential.type[1] // seems its always next structure type: ['Credential', 'ProofOfEmailCredential|....']
        credentialTypes.push(type)
      }
    }
 
    return credentialTypes
  }
 
  async buildRevocationListStatus(unsignedCredential: any): Promise<any> {
    const credentialId = unsignedCredential.id
    const subjectDid = unsignedCredential.holder?.id
 
    const {
      body: { credentialStatus, revocationListCredential },
    } = await this._revocationApiService.buildRevocationListStatus({
      credentialId,
      subjectDid,
    })
 
    const revokableUnsignedCredential = Object.assign({}, unsignedCredential, { credentialStatus })
    revokableUnsignedCredential['@context'].push('https://w3id.org/vc-revocation-list-2020/v1')
 
    Iif (revocationListCredential) {
      const revocationSignedListCredential = await this._affinity.signCredential(revocationListCredential as any)
      revocationSignedListCredential.issuanceDate = new Date().toISOString()
 
      await this._revocationApiService.publishRevocationListCredential(revocationSignedListCredential)
    }
 
    return revokableUnsignedCredential
  }
 
  async revokeCredential(credentialId: string, revocationReason: string): Promise<void> {
    const {
      body: { revocationListCredential },
    } = await this._revocationApiService.revokeCredential({ id: credentialId, revocationReason })
 
    const revocationSignedListCredential = await this._affinity.signCredential(revocationListCredential)
    revocationSignedListCredential.issuanceDate = new Date().toISOString()
 
    await this._revocationApiService.publishRevocationListCredential(revocationSignedListCredential)
  }
 
  /**
   * @description Signs credentials
   * @param credentialOfferResponseToken - credential offer response JWT
   * @param credentialParams - params for credentials
   * @returns array of SignedCredential
   */
  async signCredentials(credentialOfferResponseToken: string, credentialParams: VCV1Unsigned[]): Promise<VCV1[]> {
    await ParametersValidator.validate([
      { isArray: false, type: 'jwt', isRequired: true, value: credentialOfferResponseToken },
      { isArray: true, type: 'object', isRequired: true, value: credentialParams },
    ])
 
    const signedCredentials = []
    const credentialOfferResponse = Util.fromJWT(credentialOfferResponseToken)
    const { selectedCredentials } = credentialOfferResponse.payload.interactionToken
 
    const credentialTypesThatCanBeSigned: string[] = selectedCredentials.map(({ type }: any) => type)
 
    for (const unsignedCredential of credentialParams) {
      const isCredentialOffered = unsignedCredential.type.some((type) => credentialTypesThatCanBeSigned.includes(type))
 
      if (!isCredentialOffered) {
        continue
      }
 
      const { credentialSubject, type, '@context': context, expirationDate } = unsignedCredential
 
      const credentialMetadata = { type, context }
      const signedCredential = await this.signCredential(
        credentialSubject,
        credentialMetadata,
        { credentialOfferResponseToken },
        expirationDate,
      )
 
      signedCredentials.push(signedCredential)
    }
 
    if (signedCredentials.length === 0) {
      throw new SdkErrorFromCode('COR-22', { credentialOfferResponseToken, credentialParams })
    }
 
    return signedCredentials
  }
 
  async signUnsignedCredential(unsignedCredential: VCV1Unsigned, keyType?: KeyAlgorithmType) {
    return this._affinity.signCredential(unsignedCredential, keyType)
  }
 
  /**
   * @description Signs credential
   * @param claim - data which should be present in VC according to VC schema,
   * e.g. const claim = { ageOver: 18 }
   * @param claimMetadata - schema of credential
   * @param signCredentialOptionalInput - object with optional
   * credential offer response JWT and requester DID
   * @param expiresAt - optional, date-time when VC is to be expired
   * @returns signed credential object
   */
  async signCredential<Subject extends VCV1SubjectBaseMA>(
    credentialSubject: Subject,
    claimMetadata: ClaimMetadata,
    signCredentialOptionalInput: SignCredentialOptionalInput,
    expiresAt?: string,
    keyType?: KeyAlgorithmType,
  ): Promise<VCV1> {
    await ParametersValidator.validate([
      { isArray: false, type: 'object', isRequired: true, value: credentialSubject },
      { isArray: false, type: ClaimMetadata, isRequired: true, value: claimMetadata },
      { isArray: false, type: SignCredentialOptionalInput, isRequired: true, value: signCredentialOptionalInput },
      { isArray: false, type: 'isoString', isRequired: false, value: expiresAt },
    ])
 
    if (typeof expiresAt !== 'undefined' && new Date().getTime() > new Date(expiresAt).getTime()) {
      throw new Error('Expiry date should be greater than current date')
    }
 
    let { requesterDid } = signCredentialOptionalInput
    const { credentialOfferResponseToken } = signCredentialOptionalInput
 
    /* istanbul ignore else: code simplicity */
    Iif (credentialOfferResponseToken) {
      const credentialOfferResponse = JwtService.fromJWT(credentialOfferResponseToken)
      requesterDid = credentialOfferResponse.payload.iss
    }
 
    const unsignedCredential = buildVCV1Unsigned({
      skeleton: buildVCV1Skeleton({
        id: `claimId:${randomBytes(8).toString('hex')}`,
        credentialSubject,
        holder: { id: parse(requesterDid).did },
        type: claimMetadata.type,
        context: claimMetadata.context as any,
      }),
      issuanceDate: new Date().toISOString(),
      expirationDate: expiresAt ? new Date(expiresAt).toISOString() : undefined,
    })
 
    return this.signUnsignedCredential(unsignedCredential, keyType)
  }
 
  async validateCredential(signedCredential: SignedCredential, holderKey?: string, didDocument?: any) {
    return this._affinity.validateCredential(signedCredential, holderKey, didDocument)
  }
 
  async verifyDidAuthResponse(
    didAuthResponseToken: string,
    didAuthRequestToken?: string,
  ): Promise<CredentialShareResponseOutput> {
    await ParametersValidator.validate([
      { isArray: false, type: 'jwt', isRequired: true, value: didAuthResponseToken },
      { isArray: false, type: 'jwt', isRequired: false, value: didAuthRequestToken },
    ])
 
    return this.verifyCredentialShareResponseToken(didAuthResponseToken, didAuthRequestToken)
  }
 
  /**
   * @description Validates response token, verifies signature on provided VCs
   * and expiration date of VCs
   * @param credentialShareResponseToken - optional, used if need to check
   * response against request (when request have constrains)
   * @param credentialShareRequestToken - JWT with requested VC
   * @param shouldOwn - optional (boolean), can be passed as true,
   * when needed to verify if holder is a subject of VC
   * @returns { isValid, did, jti, suppliedCredentials, errors }
   *
   * isValid - boolean, result of the verification
   *
   * did - DID of the issuer
   *
   * jti - unique identifier for the JWT
   *
   * suppliedCredentials - array of supplied credentials
   */
  async verifyCredentialShareResponseToken(
    credentialShareResponseToken: string,
    credentialShareRequest?: any,
    shouldOwn: boolean = true,
  ): Promise<CredentialShareResponseOutput> {
    let credentialShareRequestToken
    const isFunction = credentialShareRequest instanceof Function
    if (!isFunction) {
      credentialShareRequestToken = credentialShareRequest
    }
 
    const paramsToValidate = [
      { isArray: false, type: 'jwt', isRequired: true, value: credentialShareResponseToken },
      { isArray: false, type: 'jwt', isRequired: false, value: credentialShareRequestToken },
      { isArray: false, type: 'boolean', isRequired: false, value: shouldOwn },
    ]
 
    await ParametersValidator.validate(paramsToValidate)
 
    if (isFunction) {
      const credentialShareResponse = Util.fromJWT(credentialShareResponseToken)
      const requestNonce: string = credentialShareResponse.payload.jti
      credentialShareRequestToken = await credentialShareRequest(requestNonce)
 
      if (!credentialShareRequestToken) {
        throw new SdkErrorFromCode('COR-15', { credentialShareRequestToken })
      }
 
      try {
        Util.fromJWT(credentialShareRequestToken)
      } catch (error) {
        throw new SdkErrorFromCode('COR-15', { credentialShareRequestToken })
      }
    }
 
    const response = await this._holderService.verifyCredentialShareResponse(
      credentialShareResponseToken,
      credentialShareRequestToken,
      shouldOwn,
    )
 
    const { isValid, did, jti, suppliedCredentials, errors } = response
 
    return { isValid, did, nonce: jti, suppliedCredentials, errors }
  }
 
  /**
   * @description Validates offer response against offer request
   * @param credentialOfferResponseToken - JWT with credential offer response
   * @param credentialOfferRequestToken - JWT with credential offer request
   * @returns { isValid, did, jti, selectedCredentials, errors }
   *
   * isValid - boolean, result of the verification
   *
   * did - DID of the issuer
   *
   * jti - unique identifier for the JWT
   *
   * selectedCredentials - array of selected credentials
   */
  async verifyCredentialOfferResponseToken(
    credentialOfferResponseToken: string,
    credentialOfferRequestToken?: string,
  ): Promise<CredentialOfferResponseOutput> {
    await ParametersValidator.validate([
      { isArray: false, type: 'jwt', isRequired: true, value: credentialOfferResponseToken },
      { isArray: false, type: 'jwt', isRequired: false, value: credentialOfferRequestToken },
    ])
 
    const params = { credentialOfferResponseToken, credentialOfferRequestToken }
 
    const res = await this._issuerApiService.verifyCredentialOfferResponse(params)
 
    const { isValid, issuer, jti, selectedCredentials, errors } = res.body
 
    const did = DidDocumentService.keyIdToDid(issuer)
 
    return { isValid, did, nonce: jti, selectedCredentials, errors }
  }
 
  /*
   * W3C-spec VP methods
   */
 
  /**
   * @description Creates JWT of presentation challenge
   * @param credentialRequirements - array of credential requirements with credential types
   * @param issuerDid - DID of the issuer
   * @param options - optional, JwtOptions containing:
   *
   *   audienceDid (string) - audience of generated token
   *
   *   expiresAt (isoString) - expire date-time of generated token
   *
   *   nonce (number) - nonce/jti of generated token
 
   *   callbackUrl (string)
   * @returns JWT
   */
  async generatePresentationChallenge(
    credentialRequirements: CredentialRequirement[],
    issuerDid: string = undefined,
    options?: JwtOptions,
  ): Promise<string> {
    await ParametersValidator.validate([
      { isArray: true, type: CredentialRequirement, isRequired: true, value: credentialRequirements },
      { isArray: false, type: 'did', isRequired: false, value: issuerDid },
      { isArray: false, type: JwtOptions, isRequired: false, value: options },
    ])
 
    const { audienceDid, expiresAt, nonce, callbackUrl } = options ?? {}
    const params = {
      credentialRequirements,
      issuerDid,
      audienceDid,
      expiresAt,
      nonce,
      callbackUrl,
    }
 
    const {
      body: { credentialShareRequest },
    } = await this._verifierApiService.buildCredentialRequest(params)
 
    const signedObject = await this._affinity.signJWTObject(credentialShareRequest as any)
 
    return JwtService.encodeObjectToJWT(signedObject)
  }
 
  async signUnsignedPresentation(vp: VPV1Unsigned, challenge: string, domain: string) {
    return this._affinity.signPresentation({
      vp,
      purpose: {
        challenge,
        domain,
      },
    })
  }
 
  /**
   * @description Creates VP from VP challenge and credentials
   * @param challenge - challenge with the requested VCs
   * @param vcs - array of signed credentials
   * @returns VPV1
   */
  async createPresentationFromChallenge(challenge: string, vcs: VCV1[], domain: string): Promise<VPV1> {
    await ParametersValidator.validate([
      { isArray: false, type: 'jwt', isRequired: true, value: challenge },
      { isArray: true, type: 'VCV1', isRequired: true, value: vcs },
    ])
 
    const requestedTypes = this.getCredentialTypes(Util.fromJWT(challenge))
 
    return this.signUnsignedPresentation(
      buildVPV1Unsigned({
        id: `presentationId:${randomBytes(8).toString('hex')}`,
        vcs: vcs.filter((vc) => requestedTypes.includes(vc.type[1])),
        holder: { id: this.did },
      }),
      challenge,
      domain,
    )
  }
 
  /**
   * @description Validate status of provided VC
   * @param credential - the W3c VC
   * @returns { verified, error }
   *
   * verified - boolean, result of the verification
   *
   * error - validation error
   */
  async checkCredentialStatus(credential: any): Promise<{ verified: boolean; error?: string }> {
    const result = await this._affinity.checkCredentialStatus(credential)
    return result
  }
 
  /**
   * @description Validates a VP, and the contained VCs
   * @param vp - the presentation to be validated
   * when needed to verify if holder is a subject of VC
   * @param challenge (optional) - challenge from VP requester to
   * be compared with challenge in presentation
   * @returns { isValid, did, challenge, suppliedPresentation, errors }
   *
   * isValid - boolean, result of the verification
   *
   * did - DID of the VP issuer (holder of the shared VCs)
   *
   * challenge - unique identifier for the presentation.
   * You are responsible for checking this to protect against replay attacks
   *
   * suppliedPresentation - the validated presentation
   *
   * errors - array of validation errors
   */
  async verifyPresentation(vp: unknown, challenge?: string, didDocuments?: any): Promise<PresentationValidationOutput> {
    const response = await this._affinity.validatePresentation(vp, null, challenge, didDocuments)
 
    if (response.result === true) {
      const vpChallenge = response.data.proof.challenge
      // After validating the VP we need to validate the VP's challenge token
      // to ensure that it was issued from the correct DID and that it hasn't expired.
      try {
        Util.isJWT(vpChallenge) && (await this._holderService.verifyPresentationChallenge(vpChallenge, this.did))
      } catch (error) {
        return {
          isValid: false,
          suppliedPresentation: response.data,
          errors: [error],
        }
      }
 
      return {
        isValid: true,
        did: response.data.holder.id,
        challenge: vpChallenge,
        suppliedPresentation: response.data,
      }
    } else {
      return {
        isValid: false,
        suppliedPresentation: vp,
        errors: [response.error],
      }
    }
  }
 
  /**
   * Wrapper for Affinity class validateJWT method.
   * @param token
   */
  async validateJWT(token: string): Promise<void> {
    return this._affinity.validateJWT(token)
  }
 
  /**
   * @description Save's encrypted VCs in Affinity Guardian Wallet
   * 1. encrypt VCs
   * 2. store encrypted VCs in Affinity Guardian Wallet
   * @param data - array of VCs
   * @param storageRegion (string) - (optional) specify region where credentials will be stored
   * @returns array of ids for corelated records
   */
  async saveCredentials(data: any[], storageRegion?: string): Promise<any> {
    const result = await this._walletStorageService.saveCredentials(data, storageRegion)
    // NOTE: what if creds actually were not saved in the vault?
    //       follow up with Isaak/Dustin on this - should we parse the response
    //       to define if we need to send the metrics
    return result
  }
 
  /**
   * @description Retrieve only the credential
   * @param credentialId (string) - id for the VC in vault
   * @param storageRegion (string) - (optional) specify region where credentials will be stored
   * @returns a single VC
   */
  async getCredentialById(credentialId: string, storageRegion?: string): Promise<any> {
    return this._walletStorageService.getCredentialById(credentialId, storageRegion)
  }
 
  /**
   * @description Retrieve all credentials
   * @param storageRegion (string) - (optional) specify region where credentials will be stored
   * @returns  array of VC
   */
  async getAllCredentials(storageRegion?: string): Promise<any[]> {
    return this._walletStorageService.getAllCredentials(storageRegion)
  }
 
  /**
   * @description Retrieve only the credential
   * @param token (string) - specify credential share request token to filter
   * @param storageRegion (string) - (optional) specify region where credentials will be stored
   * @returns  array of VCs
   */
  async getCredentialsByShareToken(token: string, storageRegion?: string): Promise<any[]> {
    return this._walletStorageService.getCredentialsByShareToken(token, storageRegion)
  }
 
  /**
   * @description Delete credential by id
   * @param credentialId (string) - credential to remove
   * @param storageRegion (string) - (optional) specify region where credentials will be stored
   */
  async deleteCredentialById(credentialId: string, storageRegion?: string): Promise<void> {
    return this._walletStorageService.deleteCredentialById(credentialId, storageRegion)
  }
 
  /**
   * @description Deletes all credentials from the wallet
   * @param storageRegion (string) - (optional) specify region where credentials will be stored
   */
  async deleteAllCredentials(storageRegion?: string): Promise<void> {
    return this._walletStorageService.deleteAllCredentials(storageRegion)
  }
 
  /**
   * @description Searches all of VCs for matches for the given credentialShareRequestToken.
   * If a token is not given returns all the available credentials
   * @param credentialShareRequestToken - JWT received from verifier
   * @returns array of VCs
   */
  async getCredentials(credentialShareRequestToken: string = null): Promise<any[]> {
    if (credentialShareRequestToken) {
      return this.getCredentialsByShareToken(credentialShareRequestToken)
    }
 
    return this.getAllCredentials()
  }
 
  /**
   * @description Decrypts message using user's private key
   * @param encryptedMessage - message encrypted for you by your public key
   * @returns decrypted message
   */
  async readEncryptedMessage(encryptedMessage: string): Promise<any> {
    return this._affinity.decryptByPrivateKey(encryptedMessage)
  }
 
  /**
   * @description Creates encrypted message for another user DID
   * 1. resolve DID (for whom message will be encrypted)
   * 2. get public key from resolved DID document
   * 3. encrypt message using public key of resolved DID
   * @param did - DID of user for whom message will be sent (only this user
   * will be able to decrypt it using his private key),
   * or if DID Document is passed, resolveDid won't happen
   * @param object - message object which will be send
   * @returns encryptedMessage - string version of encrypted message
   */
  async createEncryptedMessage(did: string | any, object: any) {
    let didDocument = did
 
    if (typeof did === 'string') {
      didDocument = await this.resolveDid(did)
    }
 
    const publicKeyBuffer = Util.getPublicKeyFromDidDocument(didDocument)
 
    return this._platformCryptographyTools.encryptByPublicKey(publicKeyBuffer, object)
  }
 
  async signJwt(jwtObject: any) {
    return this._affinity.signJWTObject(jwtObject)
  }
 
  /**
   * @description Claim credentials from credentialOfferRequestToken callback endpoint
   * @param credentialOfferRequestToken
   * @return array of VCs
   */
  async claimCredentials(credentialOfferRequestToken: string): Promise<any[]> {
    const { isValid, errorCode, error } = await this._holderService.verifyCredentialOfferRequest(
      credentialOfferRequestToken,
    )
    if (!isValid) {
      Eif (errorCode) {
        throw new SdkErrorFromCode(errorCode)
      }
 
      throw new Error(error)
    }
 
    const {
      payload: {
        interactionToken: { callbackURL },
      },
    } = JwtService.fromJWT(credentialOfferRequestToken)
 
    const credentialOfferResponseToken = await this.createCredentialOfferResponseToken(credentialOfferRequestToken)
    let credentialsRequest
    let credentialsRequestBody
    try {
      credentialsRequest = await fetch(callbackURL, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Api-Key': this._options.accessApiKey,
          'Content-Type': 'application/json',
          'X-SDK-Version': extractSDKVersion(),
        },
        body: JSON.stringify({ credentialOfferResponseToken }),
      })
      credentialsRequestBody = await credentialsRequest.json()
    } catch (error) {
      throw new SdkErrorFromCode('COR-29', { callbackURL }, error)
    }
 
    if (credentialsRequest.status !== 200) {
      throw new SdkErrorFromCode('COR-30', { callbackURL, status: credentialsRequest.status }, credentialsRequestBody)
    }
 
    if (!(credentialsRequestBody && Array.isArray(credentialsRequestBody.vcs))) {
      throw new SdkErrorFromCode('COR-31', { callbackURL }, credentialsRequestBody)
    }
 
    return credentialsRequestBody.vcs
  }
}