All files / src/services HolderService.ts

69.73% Statements 53/76
35% Branches 7/20
83.33% Functions 5/6
68.91% Lines 51/74

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 2701x     1x                 1x   1x   1x                         1x 152x                     152x                         152x       6x 6x 6x   6x   6x         6x           6x       2x 2x   2x         2x             2x                                                                                                       6x 6x   6x   6x 6x   6x   6x   6x   6x 4x   4x     6x   6x   6x 6x   1x 1x                       5x 4x   1x     5x 3x           5x                                                                                                 5x 5x   1x       1x       1x 1x           4x      
import uniq from 'lodash.uniq'
 
import { EventComponent } from '@affinidi/affinity-metrics-lib'
import {
  Affinity,
  JwtService,
  DidDocumentService,
  DigestService,
  KeysService,
  DocumentLoader,
  KeyManager,
} from '@affinidi/common'
import { profile } from '@affinidi/tools-common'
 
import { stripParamsFromDidUrl } from '../_helpers'
import { IPlatformCryptographyTools } from '../shared/interfaces'
import SdkErrorFromCode from '../shared/SdkErrorFromCode'
 
type ConstructorOptions = {
  registryUrl: string
  metricsUrl: string
  accessApiKey: string
 
  keysService?: KeysService
 
  keyManager?: KeyManager
}
 
@profile()
export default class HolderService {
  private _didMap: Record<string, any> = {}
  private readonly _affinityService
  private readonly _digestService
 
  constructor(
    { registryUrl, metricsUrl, accessApiKey, keysService, keyManager }: ConstructorOptions,
    platformCryptographyTools: IPlatformCryptographyTools,
    component: EventComponent,
    resolveLegacyElemLocally?: boolean,
    beforeDocumentLoader?: DocumentLoader,
  ) {
    this._affinityService = new Affinity(
      {
        apiKey: accessApiKey,
        registryUrl,
        metricsUrl,
        component,
        resolveLegacyElemLocally,
        beforeDocumentLoader,
        keysService,
        keyManager,
      },
      platformCryptographyTools,
    )
    this._digestService = new DigestService()
  }
 
  async buildCredentialOfferResponse(credentialOfferToken: string) {
    const credentialOffer = JwtService.fromJWT(credentialOfferToken)
    const { interactionToken: offerRequestInteractionToken } = credentialOffer.payload
    const { callbackURL, offeredCredentials } = offerRequestInteractionToken
 
    const selectedCredentials = offeredCredentials
 
    const interactionToken = {
      callbackURL,
      selectedCredentials,
    }
 
    const offerResponse = await JwtService.buildJWTInteractionToken(
      interactionToken,
      'credentialOfferResponse',
      credentialOffer,
    )
 
    return offerResponse
  }
 
  async buildCredentialResponse(credentialRequestToken: string, suppliedCredentials: any, expiresAt?: string) {
    const credentialRequest = JwtService.fromJWT(credentialRequestToken)
    const { callbackURL } = credentialRequest.payload.interactionToken
 
    const interactionToken = {
      callbackURL,
      suppliedCredentials,
    }
 
    const credentialResponse = await JwtService.buildJWTInteractionToken(
      interactionToken,
      'credentialResponse',
      credentialRequest,
      expiresAt,
    )
 
    return credentialResponse
  }
 
  /* istanbul ignore next: private method */
  private _keyIdToDid(keyId: string): string {
    return DidDocumentService.keyIdToDid(keyId)
  }
 
  /* istanbul ignore next: private method */
  private async _resolveUniqDIDs(dids: string[]): Promise<void> {
    const promises = []
    const uniqDIDs = uniq(dids)
 
    for (const did of uniqDIDs) {
      promises.push(this._resolveDid(did))
    }
 
    await Promise.all(promises)
  }
 
  /* istanbul ignore next: private method */
  private async _resolveDid(did: string): Promise<any> {
    const didDocument = await this._affinityService.resolveDid(did)
    this._didMap[did] = didDocument
 
    return didDocument
  }
 
  /* istanbul ignore next: private method */
  private async _validateCredentials(
    credentials: any[],
    holderKey?: string,
  ): Promise<{ result: boolean; error: string }[]> {
    const signatureValidationResults = []
 
    for (const credential of credentials) {
      const didDocument = this._didMap[this._keyIdToDid(credential.issuer)]
 
      const { result, error } = await this._affinityService.validateCredential(credential, holderKey, didDocument)
 
      signatureValidationResults.push({ result, error })
    }
 
    return signatureValidationResults
  }
 
  async verifyCredentialShareResponse(
    credentialShareResponseToken: string,
    credentialShareRequestToken?: string,
    /* istanbul ignore next: shouldOwn = true is covered ! */
    shouldOwn: boolean = true,
  ) {
    let isValid = true
    const errors = []
 
    const credentialShareResponse = JwtService.fromJWT(credentialShareResponseToken)
 
    const { iss: issuer, jti } = credentialShareResponse.payload
    const { suppliedCredentials } = credentialShareResponse.payload.interactionToken
 
    const didArray: string[] = []
 
    const holderDid = this._keyIdToDid(issuer)
 
    didArray.push(holderDid)
 
    for (const credential of suppliedCredentials) {
      const issuerDid = this._keyIdToDid(credential.issuer)
 
      didArray.push(issuerDid)
    }
 
    await this._resolveUniqDIDs(didArray)
 
    const didDocument = this._didMap[holderDid]
 
    try {
      await this._affinityService.validateJWT(credentialShareResponseToken, credentialShareRequestToken, didDocument)
    } catch (error) {
      Eif (error.message === 'Token expired') {
        throw new SdkErrorFromCode('COR-19')
      }
 
      if (error.message === 'Invalid Token') {
        throw new SdkErrorFromCode('COR-35')
      }
 
      throw error
    }
 
    let results
 
    if (shouldOwn) {
      results = await this._validateCredentials(suppliedCredentials, issuer)
    } else {
      results = await this._validateCredentials(suppliedCredentials)
    }
 
    for (const result of results) {
      Iif (result.result === false) {
        isValid = false
        errors.push(result.error)
      }
    }
 
    return { isValid, did: holderDid, jti, suppliedCredentials, errors }
  }
 
  /**
   * @description Slightly modified version of Affinity.validateJWT,
   * this validates that the given challenge was signed by the expected
   * issuer and that it isn't exipred.
   * @param vp - the presentation to be validated
   * when needed to verify if holder is a subject of VC
   * @returns { isValid, did, challenge, suppliedPresentations, 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
   *
   * suppliedPresentations - the validated presentation
   *
   * errors - array of validation errors
   */
  async verifyPresentationChallenge(challenge: string, expectedIssuer: string) {
    const token = Affinity.fromJwt(challenge)
 
    const { payload } = token
 
    const strippedExpectedIssuer = stripParamsFromDidUrl(expectedIssuer)
    const strippedPayloadIssuer = stripParamsFromDidUrl(payload.iss)
    if (strippedExpectedIssuer !== strippedPayloadIssuer) {
      throw new Error('Token not issued by expected issuer.')
    }
 
    const did = DidDocumentService.keyIdToDid(expectedIssuer)
    const didDocument = await this._affinityService.resolveDid(did)
    const publicKey = DidDocumentService.getPublicKey(strippedExpectedIssuer, didDocument, payload.kid)
 
    const { digest: tokenDigest, signature } = this._digestService.getTokenDigest(token)
    const isSignatureVerified = KeysService.verify(tokenDigest, publicKey, signature)
 
    if (!isSignatureVerified) {
      throw new Error('Signature on token is invalid')
    }
 
    if (payload.exp < Date.now()) {
      throw new Error('Token expired')
    }
  }
  async verifyCredentialOfferRequest(credentialOfferRequestToken: string) {
    try {
      await this._affinityService.validateJWT(credentialOfferRequestToken)
    } catch (error) {
      Iif (error.message === 'Token expired') {
        return { isValid: false, errorCode: 'COR-19', error: error.message }
      }
 
      Iif (error.message === 'Invalid Token') {
        return { isValid: false, errorCode: 'COR-35', error: error.message }
      }
 
      Eif (error.message === 'Signature on token is invalid') {
        return { isValid: false, errorCode: 'COR-28', error: error.message }
      }
 
      return { isValid: false, errorCode: '', error: error.message }
    }
 
    return { isValid: true, error: '', errorCode: '' }
  }
}