All files / src/suites Ed25519Signature2020.ts

83.11% Statements 64/77
86.36% Branches 19/22
100% Functions 9/9
82.89% Lines 63/76

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                                        24x   24x 24x 24x 24x       30x                 30x                   30x   30x   30x 30x 30x 30x 30x 30x 30x       30x                     90x                 3x 9x         3x       3x       3x         3x     3x         6x       3x               3x       30x             30x       30x     228x           108x   30x       30x     3x 3x 3x       30x   30x         10x     6x           54x     54x 54x       40x   202x           2x       30x     30x           30x               30x           30x                       30x             30x                                       30x     30x 30x     1x     30x                     2x 2x     28x              
import domain from '../domain';
import jsigs from 'jsonld-signatures';
import jsonld from 'jsonld';
// @ts-expect-error: not a typescript package
import { Ed25519VerificationKey2020 } from '@digitalbazaar/ed25519-verification-key-2020';
// @ts-expect-error: not a typescript package
import { Ed25519Signature2020 as Ed25519VerificationSuite } from '@digitalbazaar/ed25519-signature-2020';
import { Suite } from '../models/Suite';
import { VerifierError } from '../models';
import { preloadedContexts } from '../constants';
import { deepCopy } from '../helpers/object';
import type { Blockcerts } from '../models/Blockcerts';
import type IVerificationMethod from '../models/VerificationMethod';
import type { Issuer } from '../models/Issuer';
import type VerificationSubstep from '../domain/verifier/valueObjects/VerificationSubstep';
import type { SuiteAPI } from '../models/Suite';
import type { BlockcertsV3, VCProof } from '../models/BlockcertsV3';
import type { IDidDocument } from '../models/DidDocument';
import {jwkToMultibaseEd25519} from "../helpers/keyUtils";
 
const { purposes: { AssertionProofPurpose, AuthenticationProofPurpose } } = jsigs;
 
enum SUB_STEPS {
  retrieveVerificationMethodPublicKey = 'retrieveVerificationMethodPublicKey',
  ensureVerificationMethodValidity = 'ensureVerificationMethodValidity',
  checkDocumentSignature = 'checkDocumentSignature'
}
 
export default class Ed25519Signature2020 extends Suite {
  public verificationProcess = [
    SUB_STEPS.retrieveVerificationMethodPublicKey,
    SUB_STEPS.ensureVerificationMethodValidity,
    SUB_STEPS.checkDocumentSignature
  ];
 
  public documentToVerify: Blockcerts;
  public issuer: Issuer;
  public proof: VCProof;
  public type = 'Ed25519Signature2020';
  public verificationKey: Ed25519VerificationKey2020;
  public verificationMethod: IVerificationMethod;
  public publicKey: string;
  public proofPurpose: string;
  public challenge: string;
  public domain: string | string[];
  private readonly proofPurposeMap: any;
 
  constructor (props: SuiteAPI) {
    super(props);
    if (props.executeStep) {
      this.executeStep = props.executeStep;
    }
    this.documentToVerify = props.document;
    this.issuer = props.issuer;
    this.proof = props.proof as VCProof;
    this.proofPurpose = props.proofPurpose ?? 'assertionMethod';
    this.challenge = props.proofChallenge ?? '';
    this.domain = props.proofDomain;
    this.proofPurposeMap = {
      authentication: AuthenticationProofPurpose,
      assertionMethod: AssertionProofPurpose
    };
    this.validateProofType();
  }
 
  async init (): Promise<void> {}
 
  async verifyProof (): Promise<void> {
    for (const verificationStep of this.verificationProcess) {
      if (!this[verificationStep]) {
        console.error('verification logic for', verificationStep, 'not implemented');
        return;
      }
      await this[verificationStep]();
    }
  }
 
  async verifyIdentity (): Promise<void> {}
 
  getProofVerificationSteps (parentStepKey): VerificationSubstep[] {
    // TODO: for now we are relying on i18n from this package, eventually we would want to split it and make this suite
    // TODO: standalone
    return this.verificationProcess.map(childStepKey =>
      domain.verifier.convertToVerificationSubsteps(parentStepKey, childStepKey)
    );
  }
 
  getIdentityVerificationSteps (): VerificationSubstep[] {
    return [];
  }
 
  getIssuerPublicKey (): string {
    return this.publicKey;
  }
 
  getIssuerName (): string {
    return this.issuer.name ?? '';
  }
 
  getIssuerProfileDomain (): string {
    try {
      const issuerProfileUrl = new URL(this.getIssuerProfileUrl());
      return issuerProfileUrl.hostname ?? '';
    } catch (e) {
      return '';
    }
  }
 
  getIssuerProfileUrl (): string {
    return this.issuer.id ?? '';
  }
 
  getSigningDate (): string {
    return this.proof.created;
  }
 
  async executeStep (step: string, action, verificationSuite: string): Promise<any> {
    throw new Error('doAction method needs to be overwritten by injecting from CVJS');
  }
 
  private publicKeyJwkToString (publicKey: any): string {
    return jwkToMultibaseEd25519(publicKey.publicKeyJwk);
  }
 
  private validateProofType (): void {
    const proofType = this.isProofChain() ? this.proof.chainedProofType : this.proof.type;
    if (proofType !== this.type) {
      throw new Error(`Incompatible proof type passed. Expected: ${this.type}, Got: ${proofType}`);
    }
  }
 
  private isProofChain (): boolean {
    return this.proof.type === 'ChainedProof2021';
  }
 
  private generateDocumentLoader (): any {
    preloadedContexts[(this.documentToVerify as BlockcertsV3).issuer as string] = this.issuer.didDocument;
    const customLoader = function (url): any {
      if (url in preloadedContexts) {
        return {
          contextUrl: null,
          document: preloadedContexts[url],
          documentUrl: url
        };
      }
      return jsonld.documentLoader(url);
    };
    return customLoader;
  }
 
  private retrieveInitialDocument (): BlockcertsV3 {
    const document: BlockcertsV3 = deepCopy<BlockcertsV3>(this.documentToVerify as BlockcertsV3);
    if (Array.isArray(document.proof)) {
      // TODO: handle case when ed25519 proof is chained
      const initialProof = document.proof.find(p => p.type === this.type);
      delete document.proof;
      document.proof = initialProof;
    }
    // when the document to verify is an issuer profile and it was brought up by a DID
    // the didDocument gets appended. However it is not part of the initial document
    delete (document as any).didDocument;
 
    return document;
  }
 
  private getTargetVerificationMethodContainer (): Issuer | IDidDocument {
    if (this.issuer.didDocument) {
      const verificationMethod = this.findVerificationMethod(
        this.issuer.didDocument.verificationMethod, this.issuer.didDocument.id);
      if (verificationMethod) {
        return this.issuer.didDocument;
      }
    }
 
    // let's assume the verification method is in the issuer profile and further checks will fail
    // if that's not the case
    const controller = {
      ...this.issuer
    };
    delete controller.didDocument; // not defined in JSONLD for verification
    return controller;
  }
 
  private findVerificationMethod (verificationMethods: IVerificationMethod[], controller: string): IVerificationMethod {
    return verificationMethods.find(
      verificationMethod => {
        return verificationMethod.id === this.proof.verificationMethod ||
          controller + verificationMethod.id === this.proof.verificationMethod;
      }) ?? null;
  }
 
  private getErrorMessage (verificationStatus): string {
    return verificationStatus.error.errors[0].message;
  }
 
  private async retrieveVerificationMethodPublicKey (): Promise<void> {
    this.verificationKey = await this.executeStep(
      SUB_STEPS.retrieveVerificationMethodPublicKey,
      async (): Promise<Ed25519VerificationKey2020> => {
        const issuerDoc = this.getTargetVerificationMethodContainer();
        if (!issuerDoc) {
          throw new VerifierError(SUB_STEPS.retrieveVerificationMethodPublicKey,
            'The verification method of the document does not match the provided issuer.');
        }
 
        this.verificationMethod = this.findVerificationMethod(issuerDoc.verificationMethod, issuerDoc.id);
 
        if (!this.verificationMethod) {
          throw new VerifierError(SUB_STEPS.retrieveVerificationMethodPublicKey,
            'The verification method of the document does not match the provided issuer.');
        }
 
        try {
          this.publicKey = this.verificationMethod.publicKeyMultibase ??
            this.publicKeyJwkToString(this.verificationMethod);
        } catch (e) {
          console.error('ERROR retrieving Ed25519Signature2020 public key', e);
        }
 
        const key = await Ed25519VerificationKey2020.from({
          ...this.verificationMethod
        });
 
        if (!key) {
          throw new VerifierError(SUB_STEPS.retrieveVerificationMethodPublicKey, 'Could not derive the verification key');
        }
 
        if (key.revoked) {
          throw new VerifierError(SUB_STEPS.retrieveVerificationMethodPublicKey, 'The verification key has been revoked');
        }
 
        return key;
      },
      this.type
    );
  }
 
  private async ensureVerificationMethodValidity (): Promise<void> {
    await this.executeStep(
      SUB_STEPS.ensureVerificationMethodValidity,
      async (): Promise<void> => {
        if (this.verificationMethod.expires) {
          const expirationDate = new Date(this.verificationMethod.expires).getTime();
          if (expirationDate < Date.now()) {
            throw new VerifierError(SUB_STEPS.ensureVerificationMethodValidity, 'The verification key has expired');
          }
        }
 
        if (this.verificationMethod.revoked) {
          // waiting on clarification https://github.com/w3c/cid/issues/152
          throw new VerifierError(SUB_STEPS.ensureVerificationMethodValidity, 'The verification key has been revoked');
        }
      },
      this.type
    );
  }
 
  private async checkDocumentSignature (): Promise<void> {
    await this.executeStep(
      SUB_STEPS.checkDocumentSignature,
      async (): Promise<void> => {
        const suite = new Ed25519VerificationSuite({ key: this.verificationKey });
        suite.date = new Date(Date.now()).toISOString();
 
        if (this.proofPurpose === 'authentication' && !this.proof.challenge) {
          this.proof.challenge = '';
        }
 
        const verificationStatus = await jsigs.verify(this.retrieveInitialDocument(), {
          suite,
          purpose: new this.proofPurposeMap[this.proofPurpose]({
            controller: this.getTargetVerificationMethodContainer(),
            challenge: this.challenge,
            domain: this.domain
          }),
          documentLoader: this.generateDocumentLoader()
        });
 
        if (!verificationStatus.verified) {
          console.error(JSON.stringify(verificationStatus, null, 2));
          throw new VerifierError(SUB_STEPS.checkDocumentSignature,
            `The document's ${this.type} signature could not be confirmed: ${this.getErrorMessage(verificationStatus)}`);
        } else {
          console.log('Credential Ed25519 signature successfully verified');
        }
      },
      this.type
    );
  }
}