@neofaceid/web-sdk 1.43.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -191,80 +191,6 @@ export declare interface AwaitPushApprovalOptions {
191
191
  onFallback?: () => void;
192
192
  }
193
193
 
194
- export declare class BiometricCaptureModal {
195
- private modal;
196
- private video;
197
- private canvas;
198
- private stream;
199
- private options;
200
- private countdownInterval;
201
- private isCapturing;
202
- private flashController;
203
- constructor(options: BiometricCaptureOptions);
204
- /**
205
- * Abre o modal de captura biométrica
206
- */
207
- open(): Promise<void>;
208
- /**
209
- * Fecha o modal e limpa recursos
210
- */
211
- close(): void;
212
- /**
213
- * Cria a estrutura HTML do modal
214
- */
215
- private createModal;
216
- /**
217
- * Inicializa a câmera
218
- */
219
- private initializeCamera;
220
- /**
221
- * NEO-413 · US14.6 (item 18) — a contagem "3, 2, 1" foi removida.
222
- * Agora habilita direto o botão "Capturar" assim que a câmera fica pronta.
223
- * Vivacidade fica com o desafio `runLivenessChallenge` (NEO-408), servidor decide.
224
- */
225
- private enableCaptureButton;
226
- /**
227
- * Captura a imagem da câmera
228
- */
229
- private captureImage;
230
- /**
231
- * Detecta o tipo biométrico na imagem (face ou mão)
232
- */
233
- private detectBiometricType;
234
- /**
235
- * Adiciona event listeners aos elementos do modal
236
- */
237
- private addEventListeners;
238
- /**
239
- * Limpa recursos (câmera, intervalos, etc.)
240
- */
241
- private cleanup;
242
- /**
243
- * Retorna o título padrão baseado no modo
244
- */
245
- private getDefaultTitle;
246
- /**
247
- * Retorna o subtítulo padrão baseado no modo
248
- */
249
- private getDefaultSubtitle;
250
- /**
251
- * Adiciona estilos CSS ao modal
252
- */
253
- private addStyles;
254
- }
255
-
256
- declare interface BiometricCaptureOptions {
257
- mode: 'face' | 'hand' | 'auto';
258
- onSuccess: (imageData: string, detectedType: 'face' | 'hand') => void;
259
- onError: (error: NeoFaceError) => void;
260
- onCancel?: () => void;
261
- countdown?: number;
262
- title?: string;
263
- subtitle?: string;
264
- /** NEO-425 · US14.11.a — screen flash assistivo em ambiente escuro. Default true. */
265
- autoLighting?: boolean;
266
- }
267
-
268
194
  export declare interface BiometricLoginOptions {
269
195
  applicationToken: string;
270
196
  /**
@@ -425,10 +351,21 @@ export declare interface CameraOvalGuideProps {
425
351
  }
426
352
 
427
353
  /**
428
- * Options for capturing face frames
354
+ * Captura quadros do rosto sem abrir modal.
355
+ *
356
+ * Substitui `new NeoFaceID(...).captureFaceFrames(options)`, removido na 2.0.0.
357
+ * Não precisava da instância — só a mantinha por estar pendurado na classe.
429
358
  */
359
+ export declare function captureFaceFrames(options: CaptureFaceFramesOptions): Promise<Blob[]>;
360
+
361
+ /** Opções de {@link captureFaceFrames}. */
430
362
  export declare interface CaptureFaceFramesOptions {
363
+ /** Quantos quadros capturar, de 1 a 10. */
431
364
  numFrames: number;
365
+ /**
366
+ * Espaça as capturas em 300 ms. Uma foto estática produz quadros idênticos;
367
+ * um rosto presente, não.
368
+ */
432
369
  livenessCheck: boolean;
433
370
  }
434
371
 
@@ -628,26 +565,41 @@ export declare function consumeSseStream<T>(options: ConsumeSseOptions<T>): Prom
628
565
  */
629
566
  export declare const DEFAULT_CONSENT_INFO: ConsentInfo;
630
567
 
631
- /**
632
- * Detecta automaticamente o tipo biométrico na imagem
633
- * @param imageData Dados da imagem em base64
634
- * @returns Resultado da detecção com tipo e confiança
635
- */
636
- export declare function detectBiometricType(imageData: string): Promise<DetectionResult>;
637
-
638
- /**
639
- * Módulo de detecção automática de tipo biométrico
640
- * Utiliza face-api.js para detectar se a imagem contém face ou mão
641
- */
642
- export declare interface DetectionResult {
643
- type: 'face' | 'hand' | 'unknown';
644
- confidence: number;
645
- details?: any;
646
- }
568
+ /** Desfecho da inscrição de aparelho. */
569
+ export declare type DeviceEnrollmentOutcome = {
570
+ status: 'enrolled';
571
+ deviceLabel: string | null;
572
+ enrolledAt?: string;
573
+ } | {
574
+ status: 'expired';
575
+ } | {
576
+ status: 'cancelled';
577
+ };
647
578
 
648
579
  /** Token de inscrição de aparelho, devolvido por {@link requestDeviceEnrollmentToken}. */
649
580
  export declare interface DeviceEnrollmentToken {
650
- /** JWT RS256 de uso único. Vira o conteúdo do QR. */
581
+ /**
582
+ * Identificador curto, no formato `XXXX-XXXX`, de um alfabeto sem os pares
583
+ * que se confundem (`0/O`, `1/I/L`, `U/V`).
584
+ *
585
+ * **É isto que o QR deve carregar**, não o {@link token}. O JWT inteiro vira
586
+ * uma grade densa que exige tela grande e câmera boa, e deixa o segredo
587
+ * óptico — exposto em qualquer foto da tela. O handle fotografado vale muito
588
+ * menos: não carrega `person_id`, `consumer_id` nem assinatura, e morre na
589
+ * primeira troca. Como é legível, também serve para ditar por telefone ou
590
+ * digitar à mão quando a câmera falha.
591
+ */
592
+ handle: string;
593
+ /**
594
+ * Identificador da solicitação. É a chave do canal SSE que avisa quando o
595
+ * aparelho for inscrito: `/api/v1/devices/enrollment/{jti}/events/`.
596
+ */
597
+ jti: string;
598
+ /**
599
+ * JWT RS256 de uso único. Continua vindo por compatibilidade, mas **não deve
600
+ * ir para o QR** — quem resolve o handle é o Push, contra o core, por canal
601
+ * interno.
602
+ */
651
603
  token: string;
652
604
  /** Validade em segundos (o core emite 300). */
653
605
  expiresIn: number;
@@ -974,18 +926,6 @@ export declare const identifyPersonAsync: (image: Blob, applicationToken: string
974
926
  */
975
927
  export declare function init(options?: SDKInitOptions): void;
976
928
 
977
- /**
978
- * Inicializa o sistema de detecção biométrica
979
- * Carrega bibliotecas e modelos necessários
980
- */
981
- export declare function initializeBiometricDetection(): Promise<void>;
982
-
983
- /**
984
- * Verifica se o sistema de detecção está disponível
985
- * @returns true se a detecção avançada está disponível
986
- */
987
- export declare function isAdvancedDetectionAvailable(): boolean;
988
-
989
929
  /**
990
930
  * Verifica se o SDK foi inicializado.
991
931
  */
@@ -1013,30 +953,6 @@ export declare interface LivenessChallengeResult {
1013
953
  raw: unknown;
1014
954
  }
1015
955
 
1016
- /**
1017
- * Options for login recognition
1018
- */
1019
- export declare interface LoginRecognitionOptions {
1020
- biometricData: Blob | Blob[];
1021
- typeOfIdentification: 'FACE' | 'HAND';
1022
- purpose: 'LOGIN' | 'PROOF_OF_LIFE' | 'AUTHORIZATION' | 'SIMPLE_IDENTIFICATION' | 'SIMPLIFIED_REGISTRATION';
1023
- confidenceThreshold?: number;
1024
- }
1025
-
1026
- /**
1027
- * Result of login recognition
1028
- */
1029
- export declare interface LoginRecognitionResult {
1030
- success: boolean;
1031
- personName: string;
1032
- email: string;
1033
- cpf: string;
1034
- signature?: string;
1035
- sessionId?: string;
1036
- confidenceScore?: number;
1037
- accessToken?: string;
1038
- }
1039
-
1040
956
  /**
1041
957
  * Performs biometric login using face recognition
1042
958
  * @param image The image blob to process
@@ -1075,194 +991,6 @@ export declare class NeoFaceError extends Error {
1075
991
  getFriendlyMessage(): string;
1076
992
  }
1077
993
 
1078
- /**
1079
- * NeoFaceID SDK class for biometric authentication
1080
- *
1081
- * This class provides a high-level API for biometric recognition,
1082
- * supporting both internal use (without signature) and external integrations
1083
- * (with signature and session data for systems like OpsPay).
1084
- *
1085
- * @example
1086
- * ```typescript
1087
- * // For external integrations (with signature)
1088
- * const sdk = new NeoFaceID({
1089
- * appToken: 'your-application-token',
1090
- * baseUrl: 'https://core.neofaceid.com',
1091
- * signature: signatureFromBackend,
1092
- * sessionData: {
1093
- * email: 'user@example.com',
1094
- * cpf: '12345678901',
1095
- * sessionId: 'session-uuid-123'
1096
- * }
1097
- * });
1098
- *
1099
- * // For internal use (without signature)
1100
- * const sdk = new NeoFaceID({
1101
- * appToken: 'your-application-token'
1102
- * });
1103
- * ```
1104
- */
1105
- export declare class NeoFaceID {
1106
- private appToken;
1107
- private signature?;
1108
- private sessionData?;
1109
- /**
1110
- * Creates a new NeoFaceID instance
1111
- * @param config Configuration object
1112
- * @throws NeoFaceError if signature format is invalid
1113
- */
1114
- constructor(config: NeoFaceIDConfig);
1115
- /**
1116
- * Validates the format of a signature
1117
- * HMAC-SHA256 produces a 64-character hexadecimal string
1118
- * @param signature The signature to validate
1119
- * @returns true if valid, false otherwise
1120
- */
1121
- private validateSignatureFormat;
1122
- /**
1123
- * Captures multiple face frames for biometric recognition
1124
- * @param options Capture options
1125
- * @returns Promise that resolves to an array of image blobs
1126
- * @throws NeoFaceError if capture fails
1127
- */
1128
- captureFaceFrames(options: CaptureFaceFramesOptions): Promise<Blob[]>;
1129
- /**
1130
- * Performs login recognition using biometric data
1131
- *
1132
- * This method is designed for external integrations that require
1133
- * signature validation and session management.
1134
- *
1135
- * @param options Recognition options
1136
- * @returns Promise that resolves to recognition result
1137
- * @throws NeoFaceError if recognition fails
1138
- *
1139
- * @example
1140
- * ```typescript
1141
- * const result = await sdk.loginRecognition({
1142
- * biometricData: await sdk.captureFaceFrames({
1143
- * numFrames: 5,
1144
- * livenessCheck: true
1145
- * }),
1146
- * typeOfIdentification: 'FACE',
1147
- * purpose: 'LOGIN',
1148
- * confidenceThreshold: 0.8
1149
- * });
1150
- *
1151
- * // Result includes signature and sessionId for callback validation
1152
- * console.log(result.signature, result.sessionId);
1153
- * ```
1154
- */
1155
- loginRecognition(options: LoginRecognitionOptions): Promise<LoginRecognitionResult>;
1156
- /**
1157
- * Register a new application for a consumer
1158
- *
1159
- * This method allows authenticated users to register new applications
1160
- * that will receive their own app_token for API access.
1161
- *
1162
- * @param jwtToken JWT authentication token from logged user
1163
- * @param consumerId Consumer ID (UUID) who will own the application
1164
- * @param applicationData Application registration data
1165
- * @returns Promise with registration result including app_token
1166
- * @throws NeoFaceError if registration fails
1167
- *
1168
- * @example
1169
- * ```typescript
1170
- * const sdk = new NeoFaceID({
1171
- * appToken: 'your-application-token'
1172
- * });
1173
- *
1174
- * const result = await sdk.registerApplication(
1175
- * userJwtToken,
1176
- * consumerUuid,
1177
- * {
1178
- * applicationName: 'My New App',
1179
- * domain: 'example.com',
1180
- * acceptOnlyEmailWithSameDomain: true
1181
- * }
1182
- * );
1183
- *
1184
- * // Use the generated app_token for the new application
1185
- * console.log('New App Token:', result.application.app_token);
1186
- * ```
1187
- */
1188
- registerApplication(jwtToken: string, consumerId: string, applicationData: ApplicationRegistrationData): Promise<ApplicationRegistrationResult>;
1189
- /**
1190
- * Performs Proof of Life verification
1191
- *
1192
- * This method records a video from the camera, sends it to the backend
1193
- * for liveness detection and face recognition, and returns the result
1194
- * with personal data filtered by purpose.
1195
- *
1196
- * The process is asynchronous:
1197
- * 1. Records video from the camera (default 3 seconds)
1198
- * 2. Converts video to base64 and sends to backend
1199
- * 3. Backend processes liveness detection and face recognition
1200
- * 4. Polls for task completion
1201
- * 5. Returns personal data of the identified person
1202
- *
1203
- * @param options Configuration options for the proof of life process
1204
- * @returns Promise that resolves to ProofOfLifeResult
1205
- * @throws NeoFaceError if verification fails
1206
- *
1207
- * @example
1208
- * ```typescript
1209
- * const sdk = new NeoFaceID({
1210
- * appToken: 'your-application-token'
1211
- * });
1212
- *
1213
- * const result = await sdk.proofOfLife({
1214
- * videoDurationMs: 3000, // 3 seconds
1215
- * onRecordingProgress: (progress) => {
1216
- * console.log(`Recording: ${progress}%`);
1217
- * },
1218
- * onTaskStatusChange: (status, progress) => {
1219
- * console.log(`Status: ${status}, Progress: ${progress}%`);
1220
- * }
1221
- * });
1222
- *
1223
- * if (result.success && result.isLive) {
1224
- * console.log('Person verified:', result.personalData);
1225
- * console.log('Liveness score:', result.livenessScore);
1226
- * console.log('Face recognition score:', result.faceRecognitionScore);
1227
- * }
1228
- * ```
1229
- */
1230
- /**
1231
- * Registers document images for an already-registered donor person.
1232
- *
1233
- * Opens the document capture UI (front + optional back), then submits
1234
- * the images to the backend for extraction via DocExt.
1235
- * The backend processes this asynchronously — use the returned `taskId`
1236
- * to poll status if needed.
1237
- *
1238
- * @param personId UUID of the donor's person record
1239
- * @param jwtToken JWT Bearer token of the authenticated donor
1240
- * @param options Optional capture configuration
1241
- * @returns Promise with task_id and processing status
1242
- * @throws NeoFaceError if capture is cancelled, validation fails, or API call fails
1243
- *
1244
- * @example
1245
- * ```typescript
1246
- * const sdk = new NeoFaceID({ appToken: 'your-token' });
1247
- *
1248
- * const result = await sdk.registerDocumentByImage(personId, userJwtToken);
1249
- * console.log('Task ID:', result.taskId); // poll for completion
1250
- * ```
1251
- */
1252
- registerDocumentByImage(personId: string, jwtToken: string, options?: RegisterDocumentByImageOptions): Promise<RegisterDocumentResult>;
1253
- proofOfLife(options?: ProofOfLifeOptions): Promise<ProofOfLifeResult>;
1254
- }
1255
-
1256
- /**
1257
- * Configuration for NeoFaceID SDK initialization
1258
- */
1259
- export declare interface NeoFaceIDConfig {
1260
- appToken: string;
1261
- baseUrl?: string;
1262
- signature?: string;
1263
- sessionData?: SessionData;
1264
- }
1265
-
1266
994
  declare interface OnboardingLinkDetails {
1267
995
  id: string;
1268
996
  token: string;
@@ -1333,18 +1061,42 @@ export declare interface PersonalDataItem {
1333
1061
  export declare function preloadFaceDetectionModels(): Promise<void>;
1334
1062
 
1335
1063
  /**
1336
- * Options for Proof of Life verification
1064
+ * Prova de vida: grava um vídeo curto da câmera, envia ao core e aguarda o
1065
+ * resultado da detecção de vivacidade e do reconhecimento.
1066
+ *
1067
+ * Substitui `new NeoFaceID({ appToken }).proofOfLife(options)`, removido na
1068
+ * 2.0.0. A migração é direta:
1069
+ *
1070
+ * ```ts
1071
+ * // antes
1072
+ * const sdk = new NeoFaceID({ appToken: TOKEN });
1073
+ * const r = await sdk.proofOfLife({ videoDurationMs: 3000 });
1074
+ *
1075
+ * // depois
1076
+ * const r = await proofOfLife({ applicationToken: TOKEN, videoDurationMs: 3000 });
1077
+ * ```
1078
+ *
1079
+ * `success: false` com `isLive: false` é desfecho, não exceção — a pessoa pode
1080
+ * simplesmente não ter passado na prova. Exceção fica para falha de câmera,
1081
+ * rede ou credencial.
1337
1082
  */
1083
+ export declare function proofOfLife(options?: ProofOfLifeOptions): Promise<ProofOfLifeResult>;
1084
+
1085
+ /** Opções de {@link proofOfLife}. */
1338
1086
  export declare interface ProofOfLifeOptions {
1339
- /** Duration of video recording in milliseconds (default: 3000) */
1087
+ /**
1088
+ * Token da aplicação. Se omitido, usa o informado em `init({ applicationToken })`.
1089
+ */
1090
+ applicationToken?: string;
1091
+ /** Duração da gravação, em milissegundos. Default 3000. */
1340
1092
  videoDurationMs?: number;
1341
- /** Maximum polling attempts for task status (default: 60) */
1093
+ /** Máximo de consultas ao status da task. Default 60. */
1342
1094
  maxPollingAttempts?: number;
1343
- /** Interval between polling attempts in ms (default: 1000) */
1095
+ /** Intervalo entre consultas, em milissegundos. Default 1000. */
1344
1096
  pollingIntervalMs?: number;
1345
- /** Callback for recording progress (0-100) */
1097
+ /** Progresso da gravação, de 0 a 100. */
1346
1098
  onRecordingProgress?: (progress: number) => void;
1347
- /** Callback for task status changes */
1099
+ /** Mudança de estado da task no core. */
1348
1100
  onTaskStatusChange?: (status: string, progress?: number) => void;
1349
1101
  }
1350
1102
 
@@ -1499,6 +1251,30 @@ export declare interface RefreshedSession {
1499
1251
  */
1500
1252
  export declare const refreshSession: (refreshToken: string, applicationToken: string) => Promise<RefreshedSession>;
1501
1253
 
1254
+ /**
1255
+ * Register a new application for a consumer
1256
+ * @param jwtToken JWT authentication token from logged user
1257
+ * @param consumerId Consumer ID (UUID) who will own the application
1258
+ * @param applicationData Application registration data
1259
+ * @returns Promise with registration result
1260
+ * @throws NeoFaceError if registration fails
1261
+ *
1262
+ * @example
1263
+ * ```typescript
1264
+ * const result = await registerApplication(
1265
+ * 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
1266
+ * 'consumer-uuid-123',
1267
+ * {
1268
+ * applicationName: 'My App',
1269
+ * domain: 'example.com',
1270
+ * acceptOnlyEmailWithSameDomain: true
1271
+ * }
1272
+ * );
1273
+ * console.log('App Token:', result.application.app_token);
1274
+ * ```
1275
+ */
1276
+ export declare const registerApplication: (jwtToken: string, consumerId: string, applicationData: ApplicationRegistrationData) => Promise<ApplicationRegistrationResult>;
1277
+
1502
1278
  /**
1503
1279
  * NEO-101: Register biometric data for an existing person
1504
1280
  *
@@ -1522,12 +1298,24 @@ export declare const registerBiometric: (personId: string, faceImage: Blob, appl
1522
1298
  }>;
1523
1299
 
1524
1300
  /**
1525
- * Options for registering a document by image capture
1301
+ * Abre a captura de documento (frente e, opcionalmente, verso) e envia as
1302
+ * imagens ao core para extração.
1303
+ *
1304
+ * Substitui `new NeoFaceID(...).registerDocumentByImage(...)`, removido na
1305
+ * 2.0.0. Difere de `startDocumentCapture()`, que só captura: esta função
1306
+ * também submete ao core. O processamento é assíncrono — use o `taskId`
1307
+ * devolvido para acompanhar.
1308
+ *
1309
+ * @param personId UUID da pessoa (doador já cadastrado).
1310
+ * @param jwtToken Bearer do doador autenticado.
1526
1311
  */
1312
+ export declare function registerDocumentByImage(personId: string, jwtToken: string, options?: RegisterDocumentByImageOptions): Promise<RegisterDocumentResult>;
1313
+
1314
+ /** Opções de {@link registerDocumentByImage}. */
1527
1315
  export declare interface RegisterDocumentByImageOptions {
1528
- /** Pre-select document type, skipping the selection screen */
1316
+ /** Pré-seleciona o tipo de documento, pulando a tela de escolha. */
1529
1317
  preSelectedDocument?: 'RG' | 'CNH' | 'CPF';
1530
- /** Use back camera for capture (default: true) */
1318
+ /** Usa a câmera traseira. Default `true`. */
1531
1319
  useBackCamera?: boolean;
1532
1320
  }
1533
1321
 
@@ -1603,7 +1391,7 @@ export declare const registerPersonWithoutFace: (personData: {
1603
1391
  /**
1604
1392
  * Data de lançamento da versão atual
1605
1393
  */
1606
- export declare const RELEASE_DATE = "2026-09-15";
1394
+ export declare const RELEASE_DATE = "2026-09-19";
1607
1395
 
1608
1396
  declare interface RequestChallengeWithSessionParams {
1609
1397
  applicationToken: string;
@@ -1908,6 +1696,42 @@ export declare function startBiometricRegistration(personData: {
1908
1696
  onCannotGesture?: () => void;
1909
1697
  }): void;
1910
1698
 
1699
+ /**
1700
+ * Abre o fluxo de inscrição de aparelho: mostra o código, aguarda o celular
1701
+ * lê-lo e confirma o vínculo.
1702
+ *
1703
+ * Exige uma pessoa autenticada — o core pede o Bearer do DONOR junto do
1704
+ * `X-App-Token`, e por isso a inscrição só existe no autosserviço.
1705
+ *
1706
+ * O QR carrega o **handle curto**, nunca o JWT: um código denso exige tela
1707
+ * grande e câmera boa, e o token inteiro ficaria exposto em qualquer foto da
1708
+ * tela. Quem resolve o handle é a plataforma Push, contra o core, por canal
1709
+ * interno — o navegador não participa dessa troca.
1710
+ *
1711
+ * @example
1712
+ * ```ts
1713
+ * const r = await startDeviceEnrollment({
1714
+ * userAccessToken: sessao.accessToken,
1715
+ * applicationToken: TOKEN,
1716
+ * });
1717
+ * if (r.status === 'enrolled') {
1718
+ * // r.deviceLabel pode ser null enquanto o Push não envia o rótulo
1719
+ * }
1720
+ * ```
1721
+ */
1722
+ export declare function startDeviceEnrollment(options: StartDeviceEnrollmentOptions): Promise<DeviceEnrollmentOutcome>;
1723
+
1724
+ export declare interface StartDeviceEnrollmentOptions {
1725
+ /**
1726
+ * Access token do DONOR autenticado. A inscrição só existe no autosserviço,
1727
+ * com a pessoa logada — o core exige este Bearer **junto** do `X-App-Token`.
1728
+ */
1729
+ userAccessToken: string;
1730
+ applicationToken: string;
1731
+ /** Nome do integrador (fallback: `init({ appName })`). */
1732
+ appName?: string;
1733
+ }
1734
+
1911
1735
  /**
1912
1736
  * Função auxiliar para iniciar a captura de documento
1913
1737
  */
@@ -2040,7 +1864,7 @@ export declare const validateToken: (applicationToken: string) => Promise<boolea
2040
1864
  * MINOR: Incrementado quando adicionamos funcionalidades mantendo compatibilidade
2041
1865
  * PATCH: Incrementado quando corrigimos bugs mantendo compatibilidade
2042
1866
  */
2043
- export declare const VERSION = "1.43.0";
1867
+ export declare const VERSION = "2.0.0";
2044
1868
 
2045
1869
  /**
2046
1870
  * Executa `fn(sessionId)`. Se o servidor devolver 410 (sessão consumida/expirada),