0.1.8 • Published 2 years ago

sign-assistant-extension v0.1.8

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

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()

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

Download extension (Its not a Promise because download urls already setten in downloadLinks property)

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

NameTypeDefaultDescription
idstringrequiredUnique extension ID, e.g: ledger
keystringrequiredSign assistant access key for website
requestTimeoutnumber3000Timeout to check if extension is activated in milliseconds, e.g.: 1000
logsbooleanfalseEnable lib and extension logs
downloadLinksobjectundefinedObjeto com os links de download da extensões nas lojas.
onLoadExtensionfunctionundefinedCallback when extension is loaded
onErrorfunctionundefinedCallback when a error is thrown
onRequestfunctionundefinedCallback when library sends a request to extension
onResponsefunctionundefinedCallback when lib receives a response from extension

Error codes

LevelCodePortuguese Description
CLI1Erro desconhecido no nosso Sign Assistant.
CLI2Argumentos inválidos enviados ao Sign Assistant.
CLI3A comunicação com o Sign Assistant foi interrompida.
CLI4Um campo obrigatório não foi enviado ao Sign Assistant.
CLI5Um campo obrigatório foi enviado ao Sign Assistant com tipo inválido.
CLI6Algorítmo inválido enviado ao Sign Assistant.
CLI7Senha incorreta fornecida ao Sign Assistant.
CLI8O certificado enviado ao Sign Assistant não foi encontrado.
CLI9Operação cancelada pelo usuário no Sign Assistant.
CLI10Falha ao ler certificado no Sign Assistant.
CLI11O certificado já existe no Sign Assistant.
CLI12Erro no SQLite no Sign Assistant.
CLI13Erro no OpenSLL no Sign Assistant.
CLI14Erro ao inicializar interface gráfica no Sign Assistant.
CLI15Não foi possível acessar o certificado no Sign Assistant. Verifique se o token está conectado.
CLI16O caminho do driver já existe no banco de dados do Sign Assistant.
CLI17O token foi bloqueado no Sign Assistant por excesso de falhas de PIN.
EXTENSION_RUNTIME1Falha não identificada ao comunicar com o Sign Assistant.
EXTENSION_RUNTIME2Cheque as permissões do local de instalação do Sign Assistant.
EXTENSION_RUNTIME3A extensão está tentando conectar com um host não existente.
EXTENSION_RUNTIME4A comunicação com o Sign Assistant foi interrompida.
EXTENSION_RUNTIME5O nosso software não foi instalado.
EXTENSION_RUNTIME6O ID da sua extensão precisa ser adicionado à lista de extensões no arquivo de configuração do Sign Assistant.
EXTENSION_RUNTIME7Problema de comunicação com o Sign Assistant. Certifique-se de tê-lo atualizado.
CONTENT1Falha ao receber resposta da extensão.
CONTENT2A extensão foi desabilitada.
CONTENT3Operação não permitida.
BACKGROUND1Falha de configuração de comunicação com o Sign Assistant.
BACKGROUND2Versão de software incompatível.
BACKGROUND3Sistema operacional ainda não suportado.
LIB1Extensão não instalada.
LIB2Os dados para assinar não foram fornecidos.
LIB3Certificado para assinar não foi fornecido.
LIB4O seu navegador ainda não é suportado.
LIB5O seu sistema operacional ainda não é suportado.
LIB6Links de download não fornecidos.
0.1.8

2 years ago

0.1.7

2 years ago

0.1.4

3 years ago

0.1.3

3 years ago

0.1.6

3 years ago

0.1.5

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago