All files / src certificate.ts

98.33% Statements 59/60
88.88% Branches 8/9
100% Functions 2/2
98.33% Lines 59/60

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                                                                                                                              130x                                     130x     130x               130x       3x   2x         128x 128x     4x 6x             6x         70x   1x 1x       116x 108x                         108x 106x       88x 88x       6x   6x     1x                   88x 88x       116x   8x   108x       88x       130x     130x 130x 130x 130x 130x     1x     130x                                             108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x       108x   44x           64x 64x      
import domain from './domain';
import type { ParsedCertificate } from './parsers';
import parseJSON from './parsers/index';
import type { IFinalVerificationStatus, IVerificationStepCallbackFn } from './verifier';
import Verifier from './verifier';
import { DEFAULT_OPTIONS } from './constants';
import { deepCopy } from './helpers/object';
import convertHashlink, { getHashlinksFrom } from './parsers/helpers/convertHashlink';
import type { HashlinkVerifier } from '@blockcerts/hashlink-verifier';
import type { ExplorerAPI, IBlockchainObject } from '@blockcerts/explorer-lookup';
import type { Blockcerts } from './models/Blockcerts';
import type { Issuer } from './models/Issuer';
import type { SignatureImage } from './models';
import type { BlockcertsV3, BlockcertsV3Display } from './models/BlockcertsV3';
import { isVerifiablePresentation } from './models/BlockcertsV3';
import type { IVerificationMapItem } from './models/VerificationMap';
import { VERIFICATION_STATUSES } from './constants/verificationStatuses';
 
export interface ExplorerURLs {
  main: string;
  test: string;
}
 
export interface CertificateOptions {
  // language option
  locale?: string;
  // provide your own custom explorer API to either pass an identifier to a default service
  // or use your own blockchain explorer
  explorerAPIs?: ExplorerAPI[];
  // specify your own DID resolver url
  didResolverUrl?: string;
  // allows to define a specific purpose verification for the verifier (authentication, assertionMethod, etc)
  // https://www.w3.org/TR/vc-data-integrity/#proof-purposes
  proofPurpose?: string;
  // restricts the verification to (a) specific domain(s) - useful for authentication, should match the domain property in the proof
  // https://www.w3.org/TR/vc-data-integrity/#defn-domain
  domain?: string | string[];
  // the property must match the one provided by the proof
  // https://www.w3.org/TR/vc-data-integrity/#defn-challenge
  // https://github.com/w3c/vc-data-integrity/issues/324#issuecomment-2521054375
  challenge?: string;
}
 
export interface Signers {
  chain?: IBlockchainObject;
  issuerName?: string;
  issuerProfileDomain?: string;
  issuerProfileUrl?: string;
  issuerPublicKey: string;
  rawTransactionLink?: string;
  signatureSuiteType: string;
  signingDate: string;
  transactionId?: string;
  transactionLink?: string;
}
 
export default class Certificate {
  public certificateImage?: string;
  public certificateJson: Blockcerts;
  public description?: string; // v1, v3.2
  public display?: BlockcertsV3Display;
  public expires: string;
  public validFrom: string;
  public explorerAPIs: ExplorerAPI[] = [];
  public id: string;
  public isFormatValid: boolean;
  public isVerifiablePresentation: boolean;
  public issuedOn: string;
  public issuer: Issuer;
  public locale: string; // enum?
  public metadataJson: any; // TODO: define metadataJson interface.
  public name?: string;
  public options: CertificateOptions;
  public proofPurpose: string;
  public proofDomain?: string | string[];
  public proofChallenge?: string;
  public recipientFullName: string;
  public recordLink: string;
  public revocationKey: string;
  public sealImage?: string; // v1
  public signature?: string; // v1
  public signatureImage?: SignatureImage[]; // v1
  public signers: Signers[] = [];
  public subtitle?: string; // v1
  public hashlinkVerifier: HashlinkVerifier;
  public hasHashlinks: boolean = false;
  public verifiableCredentials: Certificate[];
  public verificationSteps: IVerificationMapItem[];
  public verifier: Verifier;
  public verificationStatus: IFinalVerificationStatus;
 
  constructor (certificateDefinition: Blockcerts | string, options: CertificateOptions = {}) {
    // Options
    this._setOptions(options);
 
    if (typeof certificateDefinition !== 'object') {
      try {
        certificateDefinition = JSON.parse(certificateDefinition) as Blockcerts;
      } catch (err) {
        throw new Error(domain.i18n.getText('errors', 'certificateNotValid'));
      }
    }
 
    // Keep certificate JSON object
    this.certificateJson = deepCopy<Blockcerts>(certificateDefinition);
    this.isVerifiablePresentation = isVerifiablePresentation(this.certificateJson as any);
 
    if (this.isVerifiablePresentation) {
      this.verifiableCredentials = (this.certificateJson as any)
        .verifiableCredential?.map((vc: Blockcerts) => new Certificate(vc, options)) ?? [];
    }
  }
 
  async init (): Promise<void> {
    if (this.isVerifiablePresentation) {
      for (const vc of this.verifiableCredentials) {
        await vc.init();
      }
    }
    // Parse certificate
    if ((this.certificateJson as BlockcertsV3).display?.content) {
      const hashlinks = getHashlinksFrom((this.certificateJson as BlockcertsV3).display.content);
      if (hashlinks.length) {
        await import('@blockcerts/hashlink-verifier').then((hashlinkLib) => {
          this.hashlinkVerifier = new hashlinkLib.HashlinkVerifier();
        });
      }
    }
    await this.parseJson(this.certificateJson);
    this.verifier = new Verifier({
      certificateJson: this.certificateJson,
      expires: this.expires,
      validFrom: this.validFrom,
      id: this.id,
      issuer: this.issuer,
      hashlinkVerifier: this.hashlinkVerifier,
      revocationKey: this.revocationKey,
      explorerAPIs: deepCopy<ExplorerAPI[]>(this.explorerAPIs),
      proofPurpose: this.proofPurpose,
      proofDomain: this.proofDomain,
      proofChallenge: this.proofChallenge
    });
    await this.verifier.init();
    this.verificationSteps = this.verifier.getVerificationSteps();
  }
 
  async verify (stepCallback?: IVerificationStepCallbackFn): Promise<IFinalVerificationStatus> {
    let mainDocumentVerificationStatus = await this.verifier.verify(stepCallback);
    this.setSigners();
 
    if (this.isVerifiablePresentation) {
      for (const vc of this.verifiableCredentials) {
        const verificationStatus = await vc.verify();
 
        vc.verificationStatus = verificationStatus;
 
        if (verificationStatus.status !== VERIFICATION_STATUSES.SUCCESS) {
          mainDocumentVerificationStatus = {
            ...mainDocumentVerificationStatus,
            status: VERIFICATION_STATUSES.FAILURE,
            message: `Credential ${vc.name ? vc.name + ' ' : ''}with id ${vc.id} failed verification. Error: ${verificationStatus.message}`,
            errors: [verificationStatus]
          };
        }
      }
    }
 
    this.verificationStatus = mainDocumentVerificationStatus;
    return mainDocumentVerificationStatus;
  }
 
  private async parseJson (certificateDefinition: Blockcerts): Promise<void> {
    const parsedCertificate: ParsedCertificate = await parseJSON(certificateDefinition, this.locale);
    if (!parsedCertificate.isFormatValid) {
      throw new Error(parsedCertificate.error);
    }
    await this._setProperties(parsedCertificate);
  }
 
  private setSigners (): void {
    this.signers = this.verifier.getSignersData();
  }
 
  private _setOptions (options: CertificateOptions): void {
    this.options = Object.assign({}, DEFAULT_OPTIONS, options);
 
    // Set locale
    this.locale = domain.i18n.ensureIsSupported(this.options.locale === 'auto' ? domain.i18n.detectLocale() : this.options.locale);
    this.explorerAPIs = this.options.explorerAPIs ?? [];
    this.proofPurpose = this.options.proofPurpose;
    this.proofDomain = this.options.domain;
    this.proofChallenge = this.options.challenge;
 
    if (options.didResolverUrl) {
      domain.did.didResolver.url = options.didResolverUrl;
    }
 
    domain.i18n.setLocale(this.locale);
  }
 
  private async _setProperties ({
    certificateImage,
    description,
    display,
    expires,
    validFrom,
    id,
    isFormatValid,
    issuedOn,
    issuer,
    metadataJson,
    name,
    recipientFullName,
    recordLink,
    revocationKey,
    sealImage,
    signature,
    signatureImage,
    subtitle
  }: ParsedCertificate): Promise<void> {
    this.isFormatValid = isFormatValid;
    this.certificateImage = certificateImage;
    this.description = description;
    this.expires = expires;
    this.validFrom = validFrom;
    this.id = id;
    this.issuedOn = issuedOn;
    this.issuer = issuer;
    this.metadataJson = metadataJson;
    this.name = name;
    this.recipientFullName = recipientFullName;
    this.recordLink = recordLink;
    this.revocationKey = revocationKey;
    this.sealImage = sealImage;
    this.signature = signature;
    this.signatureImage = signatureImage;
    this.subtitle = subtitle;
    this.display = await this.parseHashlinksInDisplay(display);
  }
 
  async parseHashlinksInDisplay (display: BlockcertsV3Display): Promise<BlockcertsV3Display> {
    const modifiedDisplay = deepCopy<BlockcertsV3Display>(display);
    if (!modifiedDisplay) {
      return;
    }
 
    if (modifiedDisplay.contentMediaType !== 'text/html') { // TODO: enum supported content media types
      return modifiedDisplay;
    }
    modifiedDisplay.content = await convertHashlink(modifiedDisplay.content, this.hashlinkVerifier);
    return modifiedDisplay;
  }
}