npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

techface-sdk

v0.2.1

Published

SDK React de prova de vida (liveness) e comparação facial. UI em pt-BR.

Readme

techface-sdk

SDK React para prova de vida (liveness) e comparação facial, com interface e mensagens em pt-BR. Conecta-se à API techfaceID — você só precisa de uma chave de API.

Funcionalidades

| Fluxo | Componente | Descrição | | --- | --- | --- | | Prova de vida | <LivenessCheck /> | Confirma que há uma pessoa real diante da câmera. | | Prova de vida + comparação | <FaceMatchCheck liveness /> | Liveness seguido de comparação com foto de referência. | | Comparação facial simples | <FaceMatchCheck liveness={false} /> | Selfie vs. referência, sem liveness. |

O SDK exibe telas prontas (câmera, instruções, resultado) e entrega o mesmo JSON via callback onResult para o seu backend ou fluxo de negócio.

Requisitos

  • React ≥ 18 e React DOM ≥ 18 (peer dependencies)
  • Navegador com acesso à câmera (HTTPS em produção)
  • Chave de API techfaceID (tf_live_…), gerada no dashboard

Instalação

npm install techface-sdk
# ou
yarn add techface-sdk

Configuração rápida

Importe o CSS global e configure a apiKey uma vez, antes de renderizar qualquer componente:

import "techface-sdk/styles.css";
import { Techface, LivenessCheck } from "techface-sdk";

Techface.configure({ apiKey: "tf_live_sua_chave_aqui" });

export function Verificacao() {
  return (
    <LivenessCheck
      onResult={(result) => console.log(result)}
      onError={(error) => console.error(error.code, error.message)}
    />
  );
}

Segurança: não commite chaves em repositórios públicos. Em Next.js, use NEXT_PUBLIC_TECHFACE_API_KEY apenas se o SDK rodar no navegador. Restrinja domínios autorizados na chave quando possível.

Next.js (App Router)

Os componentes usam APIs do navegador (câmera, fetch). Use "use client" na página ou componente que renderiza o SDK:

"use client";

import { FaceMatchCheck } from "techface-sdk";

export default function Page() {
  return (
    <FaceMatchCheck
      liveness
      referenceImage={{ url: "https://exemplo.com/documento.jpg" }}
      onResult={(result) => console.log(result.approved)}
    />
  );
}

Importe techface-sdk/styles.css no app/layout.tsx (ou _app.tsx no Pages Router).

React (Vite, CRA, etc.)

// main.tsx
import "techface-sdk/styles.css";
import { Techface } from "techface-sdk";

Techface.configure({ apiKey: import.meta.env.VITE_TECHFACE_API_KEY });

Componentes

LivenessCheck

Prova de vida isolada. O usuário passa pelo detector de liveness; o resultado inclui confiança e, quando disponível, selfieBase64 capturado no navegador.

"use client";
import { LivenessCheck } from "techface-sdk";

<LivenessCheck
  onResult={(result) => console.log(result)}
  onError={(error) => console.error(error.code, error.message)}
/>;

FaceMatchCheck

Comparação facial com ou sem liveness. Exige referenceImage (URL pública ou base64).

// Com prova de vida (padrão)
<FaceMatchCheck
  liveness
  referenceImage={{ url: "https://exemplo.com/foto-documento.jpg" }}
  onResult={(result) => console.log(result.approved)}
/>;

// Sem prova de vida — selfie + comparação
<FaceMatchCheck
  liveness={false}
  referenceImage={{ base64: "<conteudo-base64-da-foto>" }}
  onResult={(result) => console.log(result.faceMatch?.similarity)}
/>;

Props

Props compartilhadas (LivenessCheck e FaceMatchCheck)

| Prop | Tipo | Padrão | Descrição | | --- | --- | --- | --- | | onResult | (result: VerificationResult) => void | — | Callback com o resultado consolidado em JSON. | | onError | (error: TechfaceError) => void | — | Erros com code e message em pt-BR. | | id | string | — | Identificador do fluxo na página. Necessário para useTechfaceReset(id) com UI customizada. Use ids únicos se houver mais de um verificador. | | showResultScreen | boolean | true | Exibe a tela de resultado interna do SDK. | | resultFields | ResultField[] | todos | Quais detalhes exibir na tela de resultado. Não altera o JSON de onResult. | | onReady | (api: TechfaceVerificationHandle) => void | — | Recebe { reset } ao montar. Alternativa a useTechfaceReset / ref. |

Personalizar a tela de resultado (resultFields)

Com showResultScreen ativo (padrão), a prop resultFields controla quais linhas de detalhe aparecem na ResultScreen. O JSON completo continua chegando em onResult — a prop só muda a UI.

Sempre visíveis (independente de resultFields):

  • Título aprovado / reprovado
  • Botão "Tentar novamente" (quando o fluxo oferece retry)

| Valor | O que mostra na UI | Só aparece se… | | --- | --- | --- | | type | Subtítulo do tipo (Prova de vida, etc.) | — | | liveness | Pessoa viva: sim / não | result.liveness existir | | livenessConfidence | Confiança da prova de vida (%) | result.liveness existir | | faceMatch | Match facial: sim / não | result.faceMatch existir | | similarity | Similaridade (%) | result.faceMatch existir | | verificationId | ID da verificação | — | | timestamp | Data/hora da conclusão | — |

Padrão: todos os campos (DEFAULT_RESULT_FIELDS). Array vazio [] = só título (e retry).

// Liveness: só métricas, sem id/data
<LivenessCheck
  resultFields={["liveness", "livenessConfidence"]}
  onResult={(result) => console.log(result)}
/>

// Face match: tipo + similaridade
<FaceMatchCheck
  liveness
  referenceImage={{ url: "https://exemplo.com/documento.jpg" }}
  resultFields={["type", "faceMatch", "similarity"]}
  onResult={(result) => console.log(result)}
/>

// Só título aprovado/reprovado
<LivenessCheck resultFields={[]} onResult={(result) => console.log(result)} />

UI híbrida — tela do SDK com campos filtrados, fora do fluxo:

import { ResultScreen, DEFAULT_RESULT_FIELDS } from "techface-sdk";

<ResultScreen
  result={result}
  onRetry={reset}
  resultFields={["faceMatch", "similarity"]}
/>

Reiniciar com UI customizada (useTechfaceReset)

Com showResultScreen={false}, passe um id no componente e use o mesmo valor no hook. Não precisa de ref nem key. Mantenha o componente montado (pode ocultar com CSS).

import { useState } from "react";
import {
  LivenessCheck,
  useTechfaceReset,
  type VerificationResult,
} from "techface-sdk";

const reset = useTechfaceReset("verificacao");
const [result, setResult] = useState<VerificationResult | null>(null);

return (
  <>
    <div style={{ display: result ? "none" : "block" }}>
      <LivenessCheck
        id="verificacao"
        showResultScreen={false}
        onResult={setResult}
      />
    </div>

    {result && (
      <button
        type="button"
        onClick={() => {
          setResult(null);
          reset();
        }}
      >
        Tentar novamente
      </button>
    )}
  </>
);

Com vários verificadores na mesma tela, use um id por componente:

const resetLiveness = useTechfaceReset("liveness");
const resetMatch = useTechfaceReset("facematch");

<LivenessCheck id="liveness" showResultScreen={false} ... />
<FaceMatchCheck id="facematch" showResultScreen={false} ... />

Com a tela de resultado padrão do SDK, o botão "Tentar novamente" já reinicia o fluxo — não é necessário o hook.

Props adicionais (FaceMatchCheck)

| Prop | Tipo | Padrão | Descrição | | --- | --- | --- | --- | | referenceImage | { url: string } | { base64: string } | — | Obrigatória. Imagem de referência para comparação. | | liveness | boolean | true | Ativa prova de vida antes da comparação facial. |

Configuração global

import { Techface } from "techface-sdk";

Techface.configure({ apiKey: "tf_live_sua_chave_aqui" });

O SDK usa sempre a API oficial (https://api.techfaceid.com). A URL não é configurável em runtime.

Resultado (onResult)

Reprovação (approved: false) não dispara onError — apenas onResult com os dados da verificação.

Prova de vida

{
  "verificationId": "7b5ced4c-678b-4574-8898-62aad1ece852",
  "type": "liveness",
  "approved": true,
  "liveness": { "isLive": true, "confidence": 98.4 },
  "selfieBase64": "/9j/4AAQSkZJRg...",
  "timestamp": "2026-07-15T15:00:00.000Z"
}

Prova de vida + comparação facial

{
  "verificationId": "7b5ced4c-678b-4574-8898-62aad1ece852",
  "type": "liveness_facematch",
  "approved": true,
  "liveness": { "isLive": true, "confidence": 98.4 },
  "faceMatch": { "matched": true, "similarity": 99.1 },
  "selfieBase64": "/9j/4AAQSkZJRg...",
  "timestamp": "2026-07-15T15:00:00.000Z"
}

Comparação facial simples

{
  "verificationId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "type": "facematch",
  "approved": true,
  "faceMatch": { "matched": true, "similarity": 97.2 },
  "selfieBase64": "/9j/4AAQSkZJRg...",
  "timestamp": "2026-07-15T15:00:00.000Z"
}

Campos

| Campo | Descrição | | --- | --- | | verificationId | Identificador único da verificação na API techfaceID. | | type | liveness, facematch ou liveness_facematch. | | approved | true quando todos os critérios do fluxo foram atendidos. | | liveness | Presente em fluxos com prova de vida: isLive e confidence (%). | | faceMatch | Presente em fluxos com comparação: matched e similarity (%). | | selfieBase64 | JPEG em base64 (sem prefixo data:). Ver tabela abaixo. | | timestamp | Data/hora ISO 8601 da conclusão. |

selfieBase64 por fluxo

| Fluxo | No onResult | Enviada à API | | --- | --- | --- | | liveness | Sim — frame da câmera de liveness | Não | | liveness_facematch | Sim — frame da câmera de liveness | Não | | facematch | Sim — selfie capturada pelo componente | Sim |

Nos fluxos com liveness, o SDK anexa a selfie no cliente — a API não devolve a imagem. Isso mantém a foto disponível para o seu backend via onResult sem tráfego extra na resposta HTTP.

Erros (onError)

Falhas de rede, autenticação, câmera ou verificação chegam como TechfaceError:

onError={(error) => {
  console.error(error.code);    // ex.: API_KEY_INVALIDA
  console.error(error.message); // mensagem em pt-BR
}}

Em caso de erro, onResult não é chamado e selfieBase64 não é incluído.

Códigos comuns

| Código | Significado | | --- | --- | | API_KEY_NAO_CONFIGURADA | Techface.configure() não foi chamado. | | API_KEY_INVALIDA | Chave inválida ou não encontrada. | | API_KEY_AUSENTE | Cabeçalho Authorization ausente na requisição. | | APIKEY_REVOGADA | Chave revogada no dashboard. | | ORIGEM_NAO_AUTORIZADA | Domínio não autorizado na chave. | | ERRO_DE_REDE | Falha ao contactar a API. | | ERRO_LIVENESS | Falha no detector de prova de vida. | | CANCELADO_PELO_USUARIO | Usuário cancelou a verificação. | | SESSAO_INCOMPLETA | API não retornou dados necessários para liveness. |

UI customizada

Desative a tela interna e use apenas os callbacks. Combine com id + useTechfaceReset para o botão "Tentar novamente" (veja seção acima).

<LivenessCheck
  id="verificacao"
  showResultScreen={false}
  onResult={(result) => {
    // monte seu próprio UI com result.approved, result.selfieBase64, etc.
  }}
/>

Se quiser só filtrar os detalhes da tela pronta do SDK (sem montar UI própria), use resultFields — não precisa de showResultScreen={false}.

Exportações avançadas

Para layouts totalmente customizados, o pacote também exporta:

import {
  ResultScreen,
  ErrorScreen,
  DEFAULT_RESULT_FIELDS,
  useTechfaceReset,
  livenessDisplayTextPtBR,
  sdkTextsPtBR,
  type VerificationResult,
  type ReferenceImage,
  type ResultField,
  type TechfaceError,
} from "techface-sdk";
  • ResultScreen / ErrorScreen — telas de resultado e erro reutilizáveis (ResultScreen aceita resultFields).
  • DEFAULT_RESULT_FIELDS / ResultField — lista padrão e tipo dos campos da tela de resultado.
  • useTechfaceReset — reinicia um fluxo registrado com a prop id.
  • livenessDisplayTextPtBR / sdkTextsPtBR — strings pt-BR usadas internamente (útil para testes ou UI híbrida).

Chaves de API

  1. Crie uma conta em techfaceid.com.
  2. No dashboard, acesse Chaves de API e gere uma chave tf_live_….
  3. Copie a chave na criação — ela só é exibida completa uma vez.
  4. (Opcional) Restrinja domínios autorizados (app.exemplo.com, localhost:3000, etc.).

Documentação completa: techfaceid.com/docs

API utilizada pelo SDK

O SDK autentica com Authorization: Bearer <apiKey> em:

| Método | Rota | Descrição | | --- | --- | --- | | POST | /v1/sessions | Cria sessão de verificação. Body: { "type": "liveness" \| "facematch" \| "liveness_facematch" }. | | GET | /v1/sessions/:verificationId | Consulta o resultado pelo id (mesmo payload do SDK, sem selfieBase64, com status). | | POST | /v1/sessions/:verificationId/result | Consolida o resultado. Body opcional: { referenceImage?, selfieBase64? }. |

Para comparar duas imagens já disponíveis (sem câmera nem SDK), use POST /v1/compare diretamente — veja a documentação da API. Para validar um verificationId no seu backend, use GET /v1/sessions/:id.

Exemplo completo

Veja examples/minimal.tsx no repositório do pacote para um exemplo copiável com os três fluxos.

"use client";

import "techface-sdk/styles.css";
import {
  Techface,
  FaceMatchCheck,
  type VerificationResult,
  type TechfaceError,
} from "techface-sdk";

Techface.configure({ apiKey: process.env.NEXT_PUBLIC_TECHFACE_API_KEY! });

function handleResult(result: VerificationResult) {
  if (result.approved) {
    // prossiga no fluxo do seu produto
  }
  if (result.selfieBase64) {
    // persistir ou enviar ao seu backend
  }
}

function handleError(error: TechfaceError) {
  console.error(error.code, error.message);
}

export function VerificacaoIdentidade() {
  return (
    <FaceMatchCheck
      liveness
      referenceImage={{ url: "https://exemplo.com/documento.jpg" }}
      onResult={handleResult}
      onError={handleError}
    />
  );
}

TypeScript

Tipos incluídos em dist/index.d.ts. Principais exports:

  • VerificationResult, VerificationType
  • LivenessResultData, FaceMatchResultData
  • ReferenceImage, TechfaceConfig
  • TechfaceError, CommonVerificationProps, ResultField, DEFAULT_RESULT_FIELDS, TechfaceVerificationHandle
  • useTechfaceReset(id) — reinicia um fluxo registrado com a prop id (UI customizada)
  • LivenessCheckProps, FaceMatchCheckProps

Licença

MIT © techfaceID