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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@ha_tecno/react-native-sdk

v0.1.0

Published

React Native SDK for biometric authentication, liveness detection, and fingerprint recognition

Readme

React Native SDK

Esta SDK oferece componentes e serviços para captura de biometria (dedo, liveness), autenticação e integração com backend.

Instalação

NPM

npm install @hatecno/react-native-sdk

Yarn

yarn add @hatecno/react-native-sdk

Dependências Nativas

Esta SDK depende de algumas bibliotecas nativas. Instale-as seguindo suas respectivas documentações:

# Dependências obrigatórias
npm install react-native-vision-camera react-native-device-info react-native-fs
npm install react-native-gesture-handler react-native-reanimated react-native-svg
npm install react-native-worklets-core uuid

# iOS
cd ios && pod install

# Android - adicione as permissões necessárias ao AndroidManifest.xml

Permissões

iOS (ios/Info.plist)

<key>NSCameraUsageDescription</key>
<string>Esta app precisa acessar a câmera para captura biométrica</string>

Android (android/app/src/main/AndroidManifest.xml)

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Configuração Inicial

Antes de usar qualquer funcionalidade, configure a SDK com um token de autenticação:

import { configureLibrary } from '@hatecno/react-native-sdk';

await configureLibrary('SEU_TOKEN_AQUI');

Componentes

<Camera />

Componente principal para captura de foto/vídeo biométrico.

Props principais:

  • serviceType: 'finger' | 'liveness' — Define o tipo de serviço.
  • onCapturePhoto(path, focusScore?, deviceConfig?): callback ao capturar foto.
  • onCaptureVideo(path): callback ao capturar vídeo.
  • captureButtonVisible: exibe botão de captura.
  • disabled: desabilita a câmera.
  • torch: 'on' | 'off' — flash.

Exemplo:

<Camera
  serviceType="finger"
  onCapturePhoto={(path, focusScore, deviceConfig) => {
    /* ... */
  }}
  captureButtonVisible
/>

Serviços

cameraService

Configurações e parâmetros da câmera:

  • getCameraDeviceConfig(): Busca configurações do dispositivo.
  • getFocusScoreParams(): Busca parâmetros de foco.

userService

Autenticação tradicional com CPF/senha:

  • validCpf(cpf: string): Valida CPF.
  • login(cpf: string, password: string): Login com CPF e senha.
  • register(cpf: string, name: string, password: string): Cadastro de usuário.

biometricService

Autenticação e cadastro biométrico:

  • loginWithFingerprint(params): Autenticação por biometria.
  • registerWithFingerprint(params): Cadastro de biometria.

Parâmetros comuns:

  • deviceModel: Modelo do dispositivo
  • uid: ID do usuário
  • finger: Dedo (ex: 'RI' para indicador direito)
  • exposure: Exposição da câmera
  • zoom: Zoom da câmera
  • meanScore, stdScore, varScore: Parâmetros de qualidade de foco

Login específico:

  • image: Imagem em base64

Cadastro específico:

  • imagens: Array de imagens em base64

livenessService

Prova de vida:

  • lifeCertificate(params): Processa prova de vida com vídeo.

Parâmetros:

  • videoPath: Caminho do vídeo capturado
  • uid: ID do usuário
  • exposure: Valor de exposição da câmera
  • exposureMax?: Exposição máxima (opcional)
  • exposureMin?: Exposição mínima (opcional)
  • exposureScaleZeroToOne?: Escala de exposição 0-1 (opcional)

Retorno:

  • code: Código de status (0 = sucesso)
  • bpm?: Batimentos cardíacos detectados
  • message?: Mensagem de erro/sucesso

calibrationService

Calibração de pontos de operação para otimizar captura em diferentes dispositivos:

  • registerOperationPointsBiometrics(params): Calibra pontos de operação para biometria.
  • registerOperationPointsLiveness(params): Calibra pontos de operação para prova de vida.

Parâmetros Biometria:

  • images: Array de imagens em base64 para calibração
  • exposure, exposureMin, exposureMax: Configurações de exposição
  • exposureScaleZeroToOne: Escala de exposição 0-1
  • zoom, zoomMin, zoomMax: Configurações de zoom
  • zoomScaleZeroToOne: Escala de zoom 0-1
  • deviceModel?: Modelo do dispositivo (opcional, detectado automaticamente)

Parâmetros Prova de Vida:

  • videoPath: Caminho do vídeo para calibração
  • exposure, exposureMin, exposureMax: Configurações de exposição
  • exposureScaleZeroToOne: Escala de exposição 0-1
  • deviceModel?: Modelo do dispositivo (opcional, detectado automaticamente)

Retorno:

  • status: Código de status
  • message: Mensagem de resultado
  • hasConfig?: Indica se a configuração foi criada (apenas para liveness)

Utilitários

Enum Finger

Enum para identificar dedos:

Finger.LEFT_THUMB; // 'LT'
Finger.RIGHT_INDEX; // 'RI'
// etc.

Tipos

  • CameraProps: Tipagem das props do componente Camera.
  • DeviceParams: Configuração do dispositivo para captura.
  • BiometricLoginParams: Parâmetros para login biométrico.
  • BiometricRegisterParams: Parâmetros para cadastro biométrico.
  • BiometricResponse: Resposta das operações biométricas.
  • LifeCertificateParams: Parâmetros para prova de vida.
  • LifeCertificateResponse: Resposta da prova de vida.
  • BiometricCalibrationParams: Parâmetros para calibração de biometria.
  • LivenessCalibrationParams: Parâmetros para calibração de prova de vida.
  • CalibrationResponse: Resposta das operações de calibração.

Exemplo de Uso Completo

Prova de Vida

import { Camera, livenessService } from '@hatecno/react-native-sdk';

const ProvaDeVida = () => {
  const onCaptureVideo = async (videoPath: string | undefined) => {
    if (!videoPath) return;

    try {
      const result = await livenessService.lifeCertificate({
        videoPath,
        uid: 'USER_ID_123',
        exposure: 0.5,
        exposureMax: 1.0,
        exposureMin: 0.0,
        exposureScaleZeroToOne: 0.5,
      });

      if (result.code === 0) {
        console.log(`✅ Prova de vida concluída! BPM: ${result.bpm}`);
      } else {
        console.log(`❌ Erro: ${result.message}`);
      }
    } catch (error) {
      console.error('Erro na prova de vida:', error);
    }
  };

  return (
    <Camera
      serviceType="liveness"
      onCaptureVideo={onCaptureVideo}
      totalRemainingSeconds={10}
    />
  );
};

Login Biométrico

import { Camera, biometricService, Finger } from '@hatecno/react-native-sdk';
import { readFile } from 'react-native-fs';
import { getModel } from 'react-native-device-info';

const LoginBiometrico = () => {
  const onCapturePhoto = async (
    path: string | undefined,
    focusScore?: any,
    deviceConfig?: any
  ) => {
    if (!path) return;

    try {
      const image = await readFile(path, 'base64');

      const result = await biometricService.loginWithFingerprint({
        deviceModel: getModel(),
        uid: 'USER_ID_123',
        image,
        finger: Finger.RIGHT_INDEX,
        exposure: deviceConfig?.exposure ?? 0,
        zoom: deviceConfig?.zoom ?? 0,
        meanScore: focusScore?.meanScore ?? 0,
        stdScore: focusScore?.stdScore ?? 0,
        varScore: focusScore?.varScore ?? 0,
      });

      if (result.status === 200) {
        console.log('✅ Login biométrico realizado com sucesso!');
      } else {
        console.log(`❌ Erro: ${result.message}`);
      }
    } catch (error) {
      console.error('Erro no login biométrico:', error);
    }
  };

  return (
    <Camera
      serviceType="finger"
      onCapturePhoto={onCapturePhoto}
      captureButtonVisible
    />
  );
};

Cadastro Biométrico

import { Camera, biometricService, Finger } from '@hatecno/react-native-sdk';

const CadastroBiometrico = () => {
  const [images, setImages] = useState<string[]>([]);

  const onCapturePhoto = async (path: string | undefined) => {
    if (!path) return;

    const image = await readFile(path, 'base64');
    const newImages = [...images, image];
    setImages(newImages);

    // Cadastrar após 3 capturas
    if (newImages.length === 3) {
      const result = await biometricService.registerWithFingerprint({
        deviceModel: getModel(),
        uid: 'USER_ID_123',
        imagens: newImages,
        finger: Finger.RIGHT_INDEX,
        exposure: 0.5,
        zoom: 1.0,
        meanScore: 0,
        stdScore: 0,
        varScore: 0,
      });

      console.log('Resultado cadastro:', result);
      setImages([]); // Reset
    }
  };

  return (
    <Camera
      serviceType="finger"
      onCapturePhoto={onCapturePhoto}
      captureButtonVisible
    />
  );
};

Calibração de Dispositivo

import { calibrationService, Camera } from '@hatecno/react-native-sdk';
import { readFile } from 'react-native-fs';

const CalibracaoDispositivo = () => {
  const [calibrationImages, setCalibrationImages] = useState<string[]>([]);

  // Calibração para Biometria
  const calibrateBiometrics = async () => {
    const result = await calibrationService.registerOperationPointsBiometrics({
      images: calibrationImages,
      exposure: 0.5,
      exposureMin: 0.0,
      exposureMax: 1.0,
      exposureScaleZeroToOne: 0.5,
      zoom: 1.0,
      zoomMin: 1.0,
      zoomMax: 3.0,
      zoomScaleZeroToOne: 0.33,
    });

    if (result.status === 200) {
      console.log('✅ Calibração de biometria concluída!');
    } else {
      console.log(`❌ Erro na calibração: ${result.message}`);
    }
  };

  // Calibração para Prova de Vida
  const onCaptureVideoCalibration = async (videoPath: string | undefined) => {
    if (!videoPath) return;

    const result = await calibrationService.registerOperationPointsLiveness({
      videoPath,
      exposure: 0.5,
      exposureMin: 0.0,
      exposureMax: 1.0,
      exposureScaleZeroToOne: 0.5,
    });

    if (result.status === 200) {
      console.log('✅ Calibração de prova de vida concluída!');
      if (result.hasConfig) {
        console.log('🎯 Configuração criada com sucesso!');
      } else {
        console.log('🔄 Repita o processo mais uma vez');
      }
    } else {
      console.log(`❌ Erro na calibração: ${result.message}`);
    }
  };

  const onCapturePhotoCalibration = async (path: string | undefined) => {
    if (!path) return;

    const image = await readFile(path, 'base64');
    const newImages = [...calibrationImages, image];
    setCalibrationImages(newImages);

    // Calibrar após 5 capturas
    if (newImages.length >= 5) {
      await calibrateBiometrics();
      setCalibrationImages([]); // Reset
    }
  };

  return (
    <div>
      <h3>Calibração de Biometria</h3>
      <Camera
        serviceType="finger"
        onCapturePhoto={onCapturePhotoCalibration}
        captureButtonVisible
      />

      <h3>Calibração de Prova de Vida</h3>
      <Camera
        serviceType="liveness"
        onCaptureVideo={onCaptureVideoCalibration}
        totalRemainingSeconds={10}
      />
    </div>
  );
};

Observações

  • Certifique-se de conceder permissões de câmera.
  • Para biometria, utilize o enum Finger para identificar o dedo.
  • Os serviços retornam promessas e podem lançar erros.

Se precisar de exemplos mais avançados ou integração específica, abra uma issue!