Git Product home page Git Product logo

cert-verifier-js's Introduction

@blockcerts/cert-verifier-js

Build Status codecov semantic-release

A library to parse and verify Blockcerts certificates.

Usage

Install

$ npm i @blockcerts/cert-verifier-js

Import

From version 4

Instantiation of the certificate now becomes asynchronous. While you would import the Certificate constructor and instantiate identically (see below), consumers now need to call the async function init.

Example:

import { Certificate } from '@blockcerts/cert-verifier-js';
let certificate = new Certificate(certificateDefinition);
await certificate.init();

Commonjs

Exposed by default:

const { Certificate } = require('@blockcerts/cert-verifier-js');
var certificate = new Certificate(certificateDefinition);

Running in Nodejs

const { Certificate } = require('@blockcerts/cert-verifier-js/lib');
var certificate = new Certificate(certificateDefinition);

ES module

import { Certificate } from '@blockcerts/cert-verifier-js';
let certificate = new Certificate(certificateDefinition);

Script tag (iife)

Check an example here

<script src='node_modules/@blockcerts/cert-verifier-js/dist/verifier-iife.js'></script>
<script>
  var certificate = new Verifier.Certificate(certificateDefinition);
</script>

Examples

You can find more examples in the test folder.

Parse a Blockcert certificate

var fs = require('fs');

fs.readFile('./certificate.json', 'utf8', function (err, data) {
  if (err) {
    console.log(err);
  }

  let certificate = new Certificate(data);
  console.log(cert.name);
});

Verify a Blockcert certificate

var fs = require('fs');

fs.readFile('./certificate.json', 'utf8', function (err, data) {
  if (err) {
    console.log(err);
  }

  let certificate = new Certificate(data);
  const verificationResult = await certificate.verify(({code, label, status, errorMessage}) => {
    console.log('Code:', code, label, ' - Status:', status);
    if (errorMessage) {
      console.log(`The step ${code} fails with the error: ${errorMessage}`);
    }
  });

  if (verificationResult.status === 'failure') {
    console.log(`The certificate is not valid. Error: ${verificationResult.errorMessage}`);
  }
});

API

Certificate

new Certificate(certificateDefinition, options)

const certificate = new Certificate(certificateDefinition);

The constructor automatically parses a certificate.

Parameter

  • certificateDefinition (String|Object): the certificate definition. Can either be a string or a JSON object.
  • options: (Object): an object of options. The following properties are used:
    • locale: (String): language code used to set the language used by the verifier. Default: en-US. If set to auto it will use the user's browser language if available, or default to en-US. See the dedicated section for more information.
    • explorerAPIs: ([Object]): As of v4.1.0 it is possible to provide a custom service API for the transaction explorer. This enables customers to select a potentially more reliable/private explorer to retrieve the blockchain transaction bound to a Blockcert. See the dedicated section for more information.

Returns

The certificate instance has the following properties:

  • certificateImage: String. Raw data of the certificate image
  • certificateJson: Object. Certificate JSON object
  • chain: Object. Chain the certificate was issued on
  • description: String. Description of the certificate
  • expires: String|null. Expiration date
  • id: String. Certificate's ID
  • isFormatValid: Boolean. Indicates whether or not the certificate has a valid format
  • issuedOn: String. Datetime of issuance (ISO-8601)
  • issuer: Object. Certificate issuer
  • locale: String. Language code used by the verifier
  • metadataJson: Object|null . Certificate metadata object
  • name: String. Name of the certificate
  • publicKey: String. Certificate's public key
  • receipt: Object. Certificate's receipt
  • recipientFullName: String. Full name of recipient
  • recordLink: String. Link to the certificate record
  • revocationKey: String|null. Revocation key (if any)
  • sealImage: String. Raw data of the seal's image;
  • signature: String|null. Certificate's signature
  • signatureImage: SignatureImage[]. Array of certificate signature lines.
  • subtitle: String|null. Subtitle of the certificate
  • transactionId: String. Transaction ID
  • rawTransactionLink: String. Raw transaction ID
  • transactionLink: String. Transaction link
  • verificationSteps: VerificationStep[]. The array of steps the certificate will have to go through during verification
  • version: CertificateVersion. Version of the certificate

Note: verificationSteps is generated according to the nature of the certificate. The full steps array is provided ahead of verification in order to give more flexibility to the consumer. For example, you might want to pre-render the verification steps for animation, or render a count of steps and/or sub-steps.

VerificationStep has the following shape:

{
    code: 'formatValidation',
    label: 'Format validation',
    labelPending: 'Validating format',
    subSteps: [
      {
        code: 'getTransactionId',
        label: 'Get transaction ID',
        labelPending: 'Getting transaction ID',
        parentStep: 'formatValidation'
      },
      ...
    ]
}

verify(stepCallback)

This will run the verification of a certificate. The function is asynchronous.

const certificateVerification = await certificate.verify(({code, label, status, errorMessage}) => {
    console.log('Sub step update:', code, label, status);
}));
console.log(`Verification was a ${certificateVerification.status}:`, certificateVerification.message);

Parameters

  • ({code, label, status, errorMessage}) => {} (Function): callback function called whenever a substep status has changed. The callback parameter has 4 properties:
    • code: substep code
    • label: readable label of the substep
    • status: substep status (success, failure, starting)
    • errorMessage: error message (optional)

Returns

The final verification status:

{ code, status, message }
  • code: code of the final step (final)
  • status: final verification status (success, failure)
  • message string | Object: status message. It is internationalized and in case of failure it returns the error message of the failed step. When an object, it takes the following shape:
    • label: Main label of the final step
    • description: further details about the issuance
    • linkText: translation provided for a link text towards the transaction

Shape of the returned object can be checked here: https://github.com/blockchain-certificates/cert-verifier-js/blob/master/src/data/i18n.json#L41

Constants

Several constants are being exposed:

import { BLOCKCHAINS, STEPS, SUB_STEPS, CERTIFICATE_VERSIONS, VERIFICATION_STATUSES } from '@blockcerts/cert-verifier-js';

i18n

The exposed function getSupportedLanguages() returns an array of language codes supported by the library.

import { getSupportedLanguages } from '@blockcerts/cert-verifier-js';
getSupportedLanguages(); // ['en-US', 'es-ES', 'mt', ...]

You can use the codes for the locale option.

Please note that while we are working to add new languages, any new translation is welcome through forking & PR.

explorerAPIs

As of v4.1.0, customers of this library have the ability to provide a set of blockchain explorers that will be used to retrieve the transaction data used for storing a Blockerts on a blockchain, through the explorerAPIs option key.

NOTE: With the addition of Typescript to this library, some types are now exposed for consumers.

The property is set as part of the options parameter of the Certificate constructor, as follows:

const certificate = new Certificate(definition, options);

The expected shape of the object is as follows:

  serviceURL: string | ExplorerURLs;
  priority: 0 | 1 | -1; // 0 means the custom API will be ran before the public APIs listed, 1 after
  parsingFunction: TExplorerParsingFunction;

More information on each item:

  • serviceURL: when set to string will be assumed to be set for the mainnet of the Blockchain. When set to an object, the customer will be able to provide a service url for the mainnet and for the testnet versions of the blockchain. The object is then shaped as such:
{
  main: 'url',
  test: 'url'
}
  • priority: this option allows the customer to decide if they wish to see their custom explorers to be executed before/after the default ones provided by the library (see the constants/api file for a list of default explorers). If the option is set to 0, custom explorers will be called first. If set to 1 they will be called after the default ones. -1 value is reserved for default explorers.

  • parsingFunction: this function is required to parse the data (server response) as returned from the API, into the TransactionData shape that will be used by the library. The expected output shape is as follows:

interface TransactionData {
  remoteHash: string;
  issuingAddress: string;
  time: string | Date;
  revokedAddresses: string[];
}

The consumer needs to write their own function for each service used.

Contribute

Run the tests

$ npm run test

Build

$ npm run build

The build files are in the dist folder.

Verification process

If you want more details about the verification process, please check out the documentation.

Contact

Contact us at the Blockcerts community forum.

cert-verifier-js's People

Contributors

akodate avatar dariomas avatar davidlj95 avatar dependabot-preview[bot] avatar dependabot-support avatar guix77 avatar kimdhamilton avatar raiseandfall avatar tadityar avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.