npm.io
0.1.8 • Published 4 years ago

sign-assistant-extension

Licence
MIT
Version
0.1.8
Deps
0
Size
99 kB
Vulns
0
Weekly
0

Web Sign Assistant Extension

A Typescript library to communicate web pages with Sign Assistant compatible extensions

Getting started

You can install the module via npm or yarn:

yarn add sign-assistant-extension
npm install sign-assistant-extension --save

This library can only be used in frontend (browser). If its used in server side rendering (like Nextjs), please, make a dynamic import of the component that uses it.

Features

  • Check if extension is installed and enabled
  • Check if the Sign Assistant is installed
  • Download extension based on current browser
  • Download Sign Assistnat based on extension response
  • Get certificate list from extension
  • Sign a hash
  • Listen to errors, requests and responses from extension

Examples

Here are some code examples.

Basic Usage

import Signer from 'sign-assistant-extension';

const signer = new Signer({
  key: "YOUR_KEY", // website sign assistant access key
  id: "extension-unique-id",
})

const loadCertificates = async () => {
  const certificates = await signer.getCertificates()
  console.log({ certificates })
}

loadCertificates()
Advanced Usage
import Signer, { isError } from 'sign-assistant-extension';
import toast from './toast';

const signer = new Signer({
  key: "YOUR_KEY", // website sign assistant access key
  id: "extension-unique-id",
})

const signWithFirstCertificate = async () => {
  const certificates = await signer.getCertificates() // sends error if not found extension or Sign Assistant

  const dataToSign = 'Q1VTVE9NIENPTlRFTlQ='
  const dataToSignArray = [{
    dataToSign, // string of data to sign
    key: 1,
  }]
  const certificate = certificates[0]
  const signResponse = await signer.sign({ dataToSignArray, certificate })
  
  if (isError(signResponse)) {
    toast(signResponse.error)
    return
  }
  console.log({ signature: signResponse[0].signature })
}

signWithFirstCertificate()

Response types

This library is strongly typed, but here are the method response type definitions to help you better understand its workings.

interface Certificate {
  isValid: boolean
  issuer: string
  name: string
  notAfter: string
  notBefore: string
  pem: string
  provider: string
  specialName: string
  type: string
  personId?: string
}

interface Signature {
  key: number
  signature: string
}

interface ErrorResponse {
  level: "BACKGROUND" | "CONTENT" | "CLI" | "LIB" | "EXTENSION_RUNTIME" // specify where the error occurred
  error: string // user friendly message
  code: number // code based on error level, explained later...
  originalErrorMessage?: string // original error message if it exist (set if level is "EXTENSION_RUNTIME" or "CLI")
}

Methods

List certificates
const searchResponse = await signer.getCertificates()
// will return: Certificate[] | ErrorResponse
Sign
const dataToSignArray = [{
  dataToSign, // string of data to sign
  key: 1,
}]
const signResponse = await signer.sign({ dataToSignArray, certificate })
// will return: Signature[] | ErrorResponse
Has Extension
const hasExtension = await signer.hasExtension() // timeout = 1000ms
// wil return: true | ErrorResponse
Has Software
const hasSoftware = await signer.hasSoftware() // timeout = 1000ms
// wil return: true | ErrorResponse
const url = signer.downloadExtension({
  openUrl: false // Optional, default: true
})
// wil return: string | ErrorResponse
// string is the download url, it will be open as new tab if openUrl is not set to false
Download software
const url = await signer.downloadSoftware({
  openUrl: false // Optional, default: true
})
// wil return: string | ErrorResponse
// string is the download url, it will be open as new tab if openUrl is not set to false
Is error (narrow type check) - This method is also exported from library index
const dataToSignArray = [{
  dataToSign, // string of data to sign
  key: 1,
}]
const signResponse = await signer.sign({ dataToSignArray, certificate })
const isError = signer.isError(signResponse) // boolean
if (isError) {
  console.log(signResponse.error)
}
// will return: boolean

Properties

Name Type Default Description
id string required Unique extension ID, e.g: ledger
key string required Sign assistant access key for website
requestTimeout number 3000 Timeout to check if extension is activated in milliseconds, e.g.: 1000
logs boolean false Enable lib and extension logs
downloadLinks object undefined Objeto com os links de download da extensões nas lojas.
onLoadExtension function undefined Callback when extension is loaded
onError function undefined Callback when a error is thrown
onRequest function undefined Callback when library sends a request to extension
onResponse function undefined Callback when lib receives a response from extension

Error codes

Level Code Portuguese Description
CLI 1 Erro desconhecido no nosso Sign Assistant.
CLI 2 Argumentos inválidos enviados ao Sign Assistant.
CLI 3 A comunicação com o Sign Assistant foi interrompida.
CLI 4 Um campo obrigatório não foi enviado ao Sign Assistant.
CLI 5 Um campo obrigatório foi enviado ao Sign Assistant com tipo inválido.
CLI 6 Algorítmo inválido enviado ao Sign Assistant.
CLI 7 Senha incorreta fornecida ao Sign Assistant.
CLI 8 O certificado enviado ao Sign Assistant não foi encontrado.
CLI 9 Operação cancelada pelo usuário no Sign Assistant.
CLI 10 Falha ao ler certificado no Sign Assistant.
CLI 11 O certificado já existe no Sign Assistant.
CLI 12 Erro no SQLite no Sign Assistant.
CLI 13 Erro no OpenSLL no Sign Assistant.
CLI 14 Erro ao inicializar interface gráfica no Sign Assistant.
CLI 15 Não foi possível acessar o certificado no Sign Assistant. Verifique se o token está conectado.
CLI 16 O caminho do driver já existe no banco de dados do Sign Assistant.
CLI 17 O token foi bloqueado no Sign Assistant por excesso de falhas de PIN.
EXTENSION_RUNTIME 1 Falha não identificada ao comunicar com o Sign Assistant.
EXTENSION_RUNTIME 2 Cheque as permissões do local de instalação do Sign Assistant.
EXTENSION_RUNTIME 3 A extensão está tentando conectar com um host não existente.
EXTENSION_RUNTIME 4 A comunicação com o Sign Assistant foi interrompida.
EXTENSION_RUNTIME 5 O nosso software não foi instalado.
EXTENSION_RUNTIME 6 O ID da sua extensão precisa ser adicionado à lista de extensões no arquivo de configuração do Sign Assistant.
EXTENSION_RUNTIME 7 Problema de comunicação com o Sign Assistant. Certifique-se de tê-lo atualizado.
CONTENT 1 Falha ao receber resposta da extensão.
CONTENT 2 A extensão foi desabilitada.
CONTENT 3 Operação não permitida.
BACKGROUND 1 Falha de configuração de comunicação com o Sign Assistant.
BACKGROUND 2 Versão de software incompatível.
BACKGROUND 3 Sistema operacional ainda não suportado.
LIB 1 Extensão não instalada.
LIB 2 Os dados para assinar não foram fornecidos.
LIB 3 Certificado para assinar não foi fornecido.
LIB 4 O seu navegador ainda não é suportado.
LIB 5 O seu sistema operacional ainda não é suportado.
LIB 6 Links de download não fornecidos.