@velion-la/onboarding-sdk-react-native 1.2.0-beta.1 → 1.2.0-beta.11

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.
Files changed (76) hide show
  1. package/README.md +47 -17
  2. package/lib/commonjs/camera/DocumentCapture.js +57 -35
  3. package/lib/commonjs/camera/DocumentCapture.js.map +1 -1
  4. package/lib/commonjs/camera/LivenessCamera.js +240 -87
  5. package/lib/commonjs/camera/LivenessCamera.js.map +1 -1
  6. package/lib/commonjs/camera/MapAddressPicker.js +1 -1
  7. package/lib/commonjs/camera/MapAddressPicker.js.map +1 -1
  8. package/lib/commonjs/i18n/strings/en.js +1 -0
  9. package/lib/commonjs/i18n/strings/en.js.map +1 -1
  10. package/lib/commonjs/i18n/strings/es.js +1 -0
  11. package/lib/commonjs/i18n/strings/es.js.map +1 -1
  12. package/lib/commonjs/steps/DocumentsOcrStep.js +140 -20
  13. package/lib/commonjs/steps/DocumentsOcrStep.js.map +1 -1
  14. package/lib/commonjs/steps/LivenessMatchStep.js +361 -63
  15. package/lib/commonjs/steps/LivenessMatchStep.js.map +1 -1
  16. package/lib/commonjs/transport/irisWebSocket.js +38 -3
  17. package/lib/commonjs/transport/irisWebSocket.js.map +1 -1
  18. package/lib/commonjs/ui/icons/StepIcon.js +8 -3
  19. package/lib/commonjs/ui/icons/StepIcon.js.map +1 -1
  20. package/lib/commonjs/ui/overlays/LoadingOverlay.js +1 -1
  21. package/lib/commonjs/ui/overlays/LoadingOverlay.js.map +1 -1
  22. package/lib/commonjs/ui/overlays/RetryDialog.js +1 -1
  23. package/lib/commonjs/ui/overlays/RetryDialog.js.map +1 -1
  24. package/lib/commonjs/utils/jpegFromUri.js +54 -14
  25. package/lib/commonjs/utils/jpegFromUri.js.map +1 -1
  26. package/lib/module/camera/DocumentCapture.js +58 -36
  27. package/lib/module/camera/DocumentCapture.js.map +1 -1
  28. package/lib/module/camera/LivenessCamera.js +242 -89
  29. package/lib/module/camera/LivenessCamera.js.map +1 -1
  30. package/lib/module/camera/MapAddressPicker.js +1 -1
  31. package/lib/module/camera/MapAddressPicker.js.map +1 -1
  32. package/lib/module/i18n/strings/en.js +1 -0
  33. package/lib/module/i18n/strings/en.js.map +1 -1
  34. package/lib/module/i18n/strings/es.js +1 -0
  35. package/lib/module/i18n/strings/es.js.map +1 -1
  36. package/lib/module/steps/DocumentsOcrStep.js +140 -20
  37. package/lib/module/steps/DocumentsOcrStep.js.map +1 -1
  38. package/lib/module/steps/LivenessMatchStep.js +364 -66
  39. package/lib/module/steps/LivenessMatchStep.js.map +1 -1
  40. package/lib/module/transport/irisWebSocket.js +38 -3
  41. package/lib/module/transport/irisWebSocket.js.map +1 -1
  42. package/lib/module/ui/icons/StepIcon.js +8 -3
  43. package/lib/module/ui/icons/StepIcon.js.map +1 -1
  44. package/lib/module/ui/overlays/LoadingOverlay.js +1 -1
  45. package/lib/module/ui/overlays/LoadingOverlay.js.map +1 -1
  46. package/lib/module/ui/overlays/RetryDialog.js +1 -1
  47. package/lib/module/ui/overlays/RetryDialog.js.map +1 -1
  48. package/lib/module/utils/jpegFromUri.js +52 -14
  49. package/lib/module/utils/jpegFromUri.js.map +1 -1
  50. package/lib/typescript/camera/DocumentCapture.d.ts +15 -3
  51. package/lib/typescript/camera/DocumentCapture.d.ts.map +1 -1
  52. package/lib/typescript/camera/LivenessCamera.d.ts +101 -10
  53. package/lib/typescript/camera/LivenessCamera.d.ts.map +1 -1
  54. package/lib/typescript/i18n/strings/en.d.ts.map +1 -1
  55. package/lib/typescript/i18n/strings/es.d.ts +1 -0
  56. package/lib/typescript/i18n/strings/es.d.ts.map +1 -1
  57. package/lib/typescript/steps/DocumentsOcrStep.d.ts.map +1 -1
  58. package/lib/typescript/steps/LivenessMatchStep.d.ts.map +1 -1
  59. package/lib/typescript/transport/irisWebSocket.d.ts.map +1 -1
  60. package/lib/typescript/ui/icons/StepIcon.d.ts +7 -2
  61. package/lib/typescript/ui/icons/StepIcon.d.ts.map +1 -1
  62. package/lib/typescript/utils/jpegFromUri.d.ts +31 -10
  63. package/lib/typescript/utils/jpegFromUri.d.ts.map +1 -1
  64. package/package.json +20 -14
  65. package/src/camera/DocumentCapture.tsx +59 -41
  66. package/src/camera/LivenessCamera.tsx +283 -89
  67. package/src/camera/MapAddressPicker.tsx +1 -1
  68. package/src/i18n/strings/en.ts +2 -0
  69. package/src/i18n/strings/es.ts +2 -0
  70. package/src/steps/DocumentsOcrStep.tsx +160 -18
  71. package/src/steps/LivenessMatchStep.tsx +416 -89
  72. package/src/transport/irisWebSocket.ts +32 -2
  73. package/src/ui/icons/StepIcon.tsx +9 -3
  74. package/src/ui/overlays/LoadingOverlay.tsx +1 -1
  75. package/src/ui/overlays/RetryDialog.tsx +1 -1
  76. package/src/utils/jpegFromUri.ts +54 -16
@@ -15,7 +15,7 @@
15
15
  */
16
16
 
17
17
  import { useCallback, useEffect, useRef, useState } from 'react';
18
- import { ScrollView, StyleSheet, Text, View } from 'react-native';
18
+ import { Image, ScrollView, StyleSheet, Text, View } from 'react-native';
19
19
  // `expo-file-system` v19's `File` class wraps a `file://` path with a Blob-
20
20
  // compatible API (`arrayBuffer`, `size`, `delete`). We read the recorded mp4
21
21
  // to bytes in JS and PUT them with the global `fetch`. For the typical
@@ -41,7 +41,13 @@ import { StepIcon } from '../ui/icons/StepIcon';
41
41
  import { mixHex, useTheme } from '../ui/theme';
42
42
  import { getStrings } from '../i18n';
43
43
  import { log } from '../utils/log';
44
- import { readJpegFromUri } from '../utils/jpegFromUri';
44
+ import {
45
+ byteLengthOfUri,
46
+ readBytesFromUri,
47
+ readJpegFromUri,
48
+ type JpegFromUri,
49
+ } from '../utils/jpegFromUri';
50
+ import { bytesToBase64 } from '../utils/base64';
45
51
  import {
46
52
  buildSignedFrameEnvelope,
47
53
  importHmacKey,
@@ -58,14 +64,32 @@ import {
58
64
  LivenessCamera,
59
65
  type LivenessCameraHandle,
60
66
  type LivenessOvalCue,
67
+ type LivenessVideoFile,
68
+ type CapturedFrame,
69
+ ACTIVE_LIVENESS_CAMERA_VARIANT,
61
70
  } from '../camera/LivenessCamera';
62
- import type { VideoFile } from 'react-native-vision-camera';
71
+
63
72
  import type { ApiCaller } from '../transport/api';
64
73
  import type { StepDeps, StepModule } from './types';
65
74
 
66
75
  // Capture loop defaults tuned for the Iris orchestrator's frame cadence.
67
76
  const FRAME_MS_DEFAULT = 350;
68
77
  const FRAME_MS_TURN = 220;
78
+ /**
79
+ * BLINK needs a frame to land while the eyes are closed, a ~150–300 ms window
80
+ * (OSDKR-24). The web SDK paces it at 150 ms; at the default 350 ms an Edge 30
81
+ * Neo sent 12 frames in the 8 s window and the blink never registered. The
82
+ * capture pipeline still caps the real rate — this only stops the timer from
83
+ * adding idle gaps on top of it.
84
+ */
85
+ const FRAME_MS_BLINK = 150;
86
+ /**
87
+ * No frame is sent during the first second after SESSION_READY (OSDKR-24).
88
+ * Iris gates positioning on the mean sharpness of the whole session, so the
89
+ * frames taken while the user is still settling into the oval weigh on every
90
+ * later decision. The 1–2 s before the first CHALLENGE absorbs the wait.
91
+ */
92
+ const CAPTURE_WARMUP_MS = 1000;
69
93
  const PROGRESS_WATCHDOG_MS = 25_000;
70
94
  /**
71
95
  * Hard ceiling for the POST /liveness-verify call that runs after
@@ -75,7 +99,166 @@ const PROGRESS_WATCHDOG_MS = 25_000;
75
99
  */
76
100
  const LIVENESS_VERIFY_TIMEOUT_MS = 20_000;
77
101
  const FRAME_MAX_LONG_EDGE = 720;
78
- const FRAME_QUALITY = 0.55;
102
+ // Match the web SDK's canvas JPEG (~0.92) closely enough that MiniFAS does
103
+ // not treat block artefacts as a screen replay. 0.55 (the previous value)
104
+ // was the other half of the spoof-false-positive we saw after the v5
105
+ // migration: ZSL fallback JPEGs re-compressed this hard scored `screen ≈ 0.95`.
106
+ const FRAME_QUALITY = 0.85;
107
+
108
+ /** A captured frame waiting for the processor, and how long the camera took on it. */
109
+ interface QueuedFrame {
110
+ frame: CapturedFrame;
111
+ captureMs: number;
112
+ }
113
+
114
+ /** A frame scaled to the wire width and encoded as JPEG. */
115
+ interface EncodedFrame {
116
+ jpeg: JpegFromUri;
117
+ wireWidth: number;
118
+ wireHeight: number;
119
+ /** Upright capture size; only known up front for in-memory frames. */
120
+ captureSize?: { width: number; height: number } | undefined;
121
+ /** Orientation and mirroring `toImage()` applied (in-memory frames only). */
122
+ photoOrientation?: string | undefined;
123
+ photoMirrored?: boolean | undefined;
124
+ }
125
+
126
+ /**
127
+ * Releases the camera buffer an in-memory frame holds. A frame that is
128
+ * dropped instead of encoded must go through here, or CameraX runs out of
129
+ * buffers and the next capture stalls.
130
+ */
131
+ function releaseFrame(frame: CapturedFrame): void {
132
+ if (frame.kind !== 'memory') return;
133
+ try {
134
+ frame.photo.dispose();
135
+ } catch {
136
+ // Already released.
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Scales a captured frame to the wire width and encodes it as JPEG. An
142
+ * in-memory frame's camera buffer is released as soon as its pixels are
143
+ * copied out, whether encoding then succeeds or not.
144
+ */
145
+ async function encodeFrame(frame: CapturedFrame): Promise<EncodedFrame> {
146
+ // Iris reads yaw off UN-mirrored frames (OSDKR-23): a mirrored frame turns
147
+ // TURN_LEFT into TURN_RIGHT. The file path already delivers them
148
+ // un-mirrored — do not flip it. The in-memory path must undo the mirroring
149
+ // `toImage()` applies to front-camera photos (see below).
150
+ if (frame.kind === 'file') {
151
+ const compressed = await ImageManipulator.manipulateAsync(
152
+ frame.filePath.startsWith('file://')
153
+ ? frame.filePath
154
+ : `file://${frame.filePath}`,
155
+ [{ resize: { width: FRAME_MAX_LONG_EDGE } }],
156
+ { compress: FRAME_QUALITY, format: ImageManipulator.SaveFormat.JPEG },
157
+ );
158
+ const jpeg = await readJpegFromUri(compressed.uri);
159
+ return { jpeg, wireWidth: compressed.width, wireHeight: compressed.height };
160
+ }
161
+ const { photo } = frame;
162
+ const photoOrientation = photo.orientation;
163
+ const photoMirrored = photo.isMirrored;
164
+ let image: Awaited<ReturnType<typeof photo.toImageAsync>>;
165
+ try {
166
+ image = await photo.toImageAsync();
167
+ } finally {
168
+ releaseFrame(frame);
169
+ }
170
+ const captureSize = { width: image.width, height: image.height };
171
+ const wireWidth = FRAME_MAX_LONG_EDGE;
172
+ const wireHeight = Math.round((image.height * wireWidth) / image.width);
173
+ let wireImage: Awaited<ReturnType<typeof image.resizeAsync>>;
174
+ try {
175
+ wireImage = await image.resizeAsync(wireWidth, wireHeight);
176
+ } finally {
177
+ image.dispose();
178
+ }
179
+ // `toImage()` mirrors front-camera photos (`isMirrored`), which the file
180
+ // path never did. Left as is, an Edge 30 Neo user turning left moved the yaw
181
+ // by -36° and Iris scored TURN_LEFT at 0 for the whole window. Undo it on
182
+ // the small image, where it is cheap.
183
+ if (photoMirrored) {
184
+ const mirrored = wireImage;
185
+ try {
186
+ wireImage = await mirrored.mirrorHorizontallyAsync();
187
+ } finally {
188
+ mirrored.dispose();
189
+ }
190
+ }
191
+ let encoded: Awaited<ReturnType<typeof wireImage.toEncodedImageDataAsync>>;
192
+ try {
193
+ // Same encoder as the file path (`Bitmap.compress`), on its 0–100 scale.
194
+ encoded = await wireImage.toEncodedImageDataAsync(
195
+ 'jpg',
196
+ Math.round(FRAME_QUALITY * 100),
197
+ );
198
+ } finally {
199
+ wireImage.dispose();
200
+ }
201
+ // Copy out of the native-backed buffer before the image objects go away.
202
+ const bytes = new Uint8Array(encoded.buffer.slice(0));
203
+ return {
204
+ jpeg: { bytes, base64: bytesToBase64(bytes), byteLength: bytes.byteLength },
205
+ wireWidth,
206
+ wireHeight,
207
+ captureSize,
208
+ photoOrientation,
209
+ photoMirrored,
210
+ };
211
+ }
212
+
213
+ /**
214
+ * DIAGNOSTIC (OSDKR-24): logs the capture size CameraX negotiated next to the
215
+ * frame that went to Iris, and how long the camera and the processing took
216
+ * on it. Fire-and-forget — a failure here must never cost a frame.
217
+ */
218
+ async function logCaptureDiagnostics(sample: {
219
+ encoded: EncodedFrame;
220
+ source: CapturedFrame['kind'];
221
+ capturePath?: string | undefined;
222
+ captureMs: number;
223
+ processMs: number;
224
+ challenge: unknown;
225
+ }): Promise<void> {
226
+ try {
227
+ const { encoded } = sample;
228
+ let captureSize = encoded.captureSize;
229
+ let captureBytes: number | null = null;
230
+ if (!captureSize && sample.capturePath) {
231
+ const captureUri = sample.capturePath.startsWith('file://')
232
+ ? sample.capturePath
233
+ : `file://${sample.capturePath}`;
234
+ captureSize = await Image.getSize(captureUri);
235
+ captureBytes = byteLengthOfUri(captureUri);
236
+ }
237
+ if (!captureSize) return;
238
+ log.warn('[Liveness][diag] capture', {
239
+ variant: ACTIVE_LIVENESS_CAMERA_VARIANT,
240
+ source: sample.source,
241
+ captureWidth: captureSize.width,
242
+ captureHeight: captureSize.height,
243
+ captureBytes,
244
+ wireWidth: encoded.wireWidth,
245
+ wireHeight: encoded.wireHeight,
246
+ wireBytes: encoded.jpeg.byteLength,
247
+ // Short edge of the capture over the wire width. Below 1 the resize
248
+ // UPSCALED the capture.
249
+ captureToWire: Number(
250
+ (Math.min(captureSize.width, captureSize.height) / FRAME_MAX_LONG_EDGE).toFixed(2),
251
+ ),
252
+ captureMs: sample.captureMs,
253
+ processMs: sample.processMs,
254
+ photoOrientation: encoded.photoOrientation,
255
+ photoMirrored: encoded.photoMirrored,
256
+ challenge: sample.challenge,
257
+ });
258
+ } catch (err) {
259
+ log.warn('[Liveness][diag] capture size unavailable', err);
260
+ }
261
+ }
79
262
  /**
80
263
  * Hard ceiling for the video upload PUT to GCS that runs between SESSION_COMPLETE
81
264
  * and POST /liveness-verify. Long enough for a 5 MB upload on a slow mobile link
@@ -205,10 +388,31 @@ function LivenessMatchView({
205
388
  );
206
389
  const frameMsRef = useRef<number>(FRAME_MS_DEFAULT);
207
390
  const captureTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
208
- const inFlightRef = useRef(false);
391
+ // Capture and processing run as a two-stage pipeline (OSDKR-24): the camera
392
+ // takes frame N+1 while frame N is resized, signed and sent. On an Edge 30
393
+ // Neo the camera takes ~320 ms of a ~730 ms cycle and our processing the
394
+ // rest; running them back to back capped the loop at ~1.35 fps, against the
395
+ // 2.8–4.5 fps the challenges are paced for.
396
+ const captureInFlightRef = useRef(false);
397
+ const processingRef = useRef(false);
398
+ // At most one captured frame waits for the processor, and no new capture
399
+ // starts while one waits, so frames never queue up and go stale. An
400
+ // in-memory frame holds a camera buffer while it waits: dropping one must
401
+ // release it.
402
+ const pendingFrameRef = useRef<QueuedFrame | null>(null);
403
+ // Bumped by `stopCapture` so a capture or a processing pass still running
404
+ // when the loop stops is dropped instead of sent.
405
+ const captureGenerationRef = useRef(0);
406
+ // No capture starts before this timestamp. See CAPTURE_WARMUP_MS.
407
+ const captureNotBeforeRef = useRef(0);
209
408
  const framesSentRef = useRef(0);
210
409
  const watchdogRef = useRef<ReturnType<typeof setTimeout> | null>(null);
211
410
  const finalizingRef = useRef(false);
411
+ // Set when we are about to show the in-flow retry dialog. Iris often
412
+ // closes with 1000 in the same tick as the terminal WARNING, and that close
413
+ // can beat our own 4001 — without this flag the generic onClose would
414
+ // treat a handled rejection as "socket closed before the step finalized".
415
+ const closingForRetryRef = useRef(false);
212
416
  const toastTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
213
417
  // Tracks the toast currently on screen so we can extend its visibility when
214
418
  // the same message arrives again (instead of dismount/remount, which made
@@ -286,14 +490,25 @@ function LivenessMatchView({
286
490
  }
287
491
  }, []);
288
492
 
289
- const stopCapture = useCallback(() => {
493
+ const clearCaptureTimer = useCallback(() => {
290
494
  if (captureTimerRef.current) {
291
495
  clearInterval(captureTimerRef.current);
292
496
  captureTimerRef.current = null;
293
497
  }
294
- inFlightRef.current = false;
295
498
  }, []);
296
499
 
500
+ const stopCapture = useCallback(() => {
501
+ clearCaptureTimer();
502
+ captureGenerationRef.current += 1;
503
+ const pending = pendingFrameRef.current;
504
+ pendingFrameRef.current = null;
505
+ if (pending) releaseFrame(pending.frame);
506
+ // Also recovers from a camera or processing call that never settled: the
507
+ // next loop start must not stay blocked on it.
508
+ captureInFlightRef.current = false;
509
+ processingRef.current = false;
510
+ }, [clearCaptureTimer]);
511
+
297
512
  // ── Video upload pipeline (OSDKR-4) ─────────────────────────────────────
298
513
  // Everything below is best-effort: never throws into the caller; never
299
514
  // blocks liveness completion. The worst case is `videoOutcomeRef = 'failed'`
@@ -309,7 +524,7 @@ function LivenessMatchView({
309
524
  }, []);
310
525
 
311
526
  const uploadRecordedVideo = useCallback(
312
- async (video: VideoFile): Promise<void> => {
527
+ async (video: LivenessVideoFile): Promise<void> => {
313
528
  const target = videoUploadRef.current;
314
529
  videoTempPathRef.current = video.path;
315
530
  if (!target) {
@@ -341,29 +556,43 @@ function LivenessMatchView({
341
556
  });
342
557
  const t0 = Date.now();
343
558
  try {
344
- // Build a NATIVE React Native Blob from the `file://` URI: fetching
345
- // the local path returns a Response whose `.blob()` is the BlobModule
346
- // implementation that the bridge actually knows how to upload. Using
347
- // the expo-file-system `File` directly silently sends an empty body
348
- // (GCS responds 200 with a 0-byte object — exactly what we hit
349
- // before). Reading the bytes through the native Blob keeps the data
350
- // on the native side and uploads streamed from disk.
351
- const fileUri = video.path.startsWith('file://')
352
- ? video.path
353
- : `file://${video.path}`;
354
- const nativeBlob = await (await fetch(fileUri)).blob();
559
+ // Read the bytes with `expo-file-system`, NOT with `fetch(fileUri)`.
560
+ //
561
+ // This reverses what this code used to do, so it is worth spelling
562
+ // out. Under React Native's `fetch` the native Blob was the reliable
563
+ // body and passing bytes sent an empty one. Since Expo SDK 57 the
564
+ // global `fetch` is Expo's native HTTP client
565
+ // (`expo/src/winter/runtime.native.ts` → `install('fetch', ...)`),
566
+ // which does not handle the `file://` scheme: it answers with an empty
567
+ // body instead of failing, so reading the recording through it
568
+ // uploaded a 0-byte object while every status code reported success
569
+ // (OSDKR-22). Expo's `fetch` does accept any `ArrayBuffer.isView` as a
570
+ // request body, so the bytes go up directly.
571
+ const videoBytes = await readBytesFromUri(video.path);
355
572
  log.info('[Liveness] video upload body prepared', {
356
- blobSize: nativeBlob.size,
357
- blobType: nativeBlob.type,
573
+ bytes: videoBytes.byteLength,
358
574
  });
575
+ if (videoBytes.byteLength === 0) {
576
+ throw new Error('Recorded video read back as 0 bytes.');
577
+ }
359
578
  const result = await fetch(target.upload_url, {
360
579
  method: 'PUT',
361
580
  headers: { 'Content-Type': VIDEO_CONTENT_TYPE },
362
- body: nativeBlob,
581
+ body: videoBytes,
363
582
  });
364
583
  const elapsedMs = Date.now() - t0;
365
584
  if (result.ok) {
366
- log.info('[Liveness] video upload ok', { status: result.status, elapsedMs, sizeBytes });
585
+ // `sentBytes` is what we actually put on the wire; `sizeBytes` is
586
+ // the file size stat'd before reading. They must match — a mismatch,
587
+ // or an etag that repeats across sessions, means the body never
588
+ // reached the bucket (OSDKR-22).
589
+ log.info('[Liveness] video upload ok', {
590
+ status: result.status,
591
+ sentBytes: videoBytes.byteLength,
592
+ sizeBytes,
593
+ etag: result.headers.get('etag'),
594
+ elapsedMs,
595
+ });
367
596
  videoOutcomeRef.current = 'uploaded';
368
597
  videoMetaRef.current = {
369
598
  content_type: VIDEO_CONTENT_TYPE,
@@ -413,7 +642,17 @@ function LivenessMatchView({
413
642
  [deleteVideoTemp],
414
643
  );
415
644
 
416
- const startVideoRecordingIfEnabled = useCallback(() => {
645
+ const startVideoRecordingIfEnabled = useCallback(async () => {
646
+ // Idempotent on purpose: with the recorder now starting at
647
+ // POSITIONING_READY, the first CHALLENGE calls this again, and both paths
648
+ // are legitimate — positioning can also be skipped entirely.
649
+ //
650
+ // Without this guard the second call would replace the two Deferreds below
651
+ // while the first recording is still running. `LivenessCamera` returns
652
+ // early because it already holds a Recorder, so the fresh promises would
653
+ // never settle and the finalize path would await them forever — the
654
+ // "analyzing" hang from OSDKR-23, reintroduced through a different door.
655
+ if (videoOutcomeRef.current === 'recording') return;
417
656
  if (!videoUploadRef.current) {
418
657
  log.info('[Liveness] video skipped: no video_upload in liveness-init');
419
658
  return;
@@ -453,7 +692,7 @@ function LivenessMatchView({
453
692
  };
454
693
  });
455
694
  try {
456
- camera.startVideoRecording({
695
+ await camera.startVideoRecording({
457
696
  onRecordingFinished: (video) => {
458
697
  log.info('[Liveness] video recording finished', {
459
698
  path: video.path,
@@ -572,67 +811,117 @@ function LivenessMatchView({
572
811
  [deleteVideoTemp, onCancel, stopCapture, stopVideoRecordingIfActive, stopWatchdog],
573
812
  );
574
813
 
575
- const captureAndSend = useCallback(async () => {
576
- if (inFlightRef.current) return;
814
+ const processAndSendFrame = useCallback(
815
+ async (queued: QueuedFrame, generation: number): Promise<void> => {
816
+ processingRef.current = true;
817
+ const processStart = Date.now();
818
+ try {
819
+ const ws = wsRef.current;
820
+ if (!ws || !ws.isOpen()) {
821
+ releaseFrame(queued.frame);
822
+ return;
823
+ }
824
+ const encoded = await encodeFrame(queued.frame);
825
+ const { jpeg } = encoded;
826
+ // The loop stopped (or the socket closed) while this frame was being
827
+ // processed: drop it rather than send a frame from before the stop.
828
+ if (generation !== captureGenerationRef.current || !ws.isOpen()) return;
829
+ // DIAGNOSTIC (OSDKR-24): one line every 10th frame comparing what the
830
+ // camera captured with what went on the wire, plus how long each
831
+ // pipeline stage took. `warn` on purpose: `info` is silent in the
832
+ // release builds testers run.
833
+ if (framesSentRef.current % 10 === 0) {
834
+ void logCaptureDiagnostics({
835
+ encoded,
836
+ source: queued.frame.kind,
837
+ capturePath:
838
+ queued.frame.kind === 'file' ? queued.frame.filePath : undefined,
839
+ captureMs: queued.captureMs,
840
+ processMs: Date.now() - processStart,
841
+ challenge: currentChallengeRef.current ?? null,
842
+ });
843
+ }
844
+ const key = hmacRef.current;
845
+ if (key) {
846
+ const envelope = buildSignedFrameEnvelope({
847
+ key,
848
+ sessionId: livenessSessionIdRef.current ?? sessionId,
849
+ frameId: framesSentRef.current,
850
+ jpegBytes: jpeg.bytes,
851
+ jpegBase64: jpeg.base64,
852
+ });
853
+ ws.sendJson(envelope.json);
854
+ } else {
855
+ // Vision-camera + RN's WebSocket need an ArrayBuffer for binary frames.
856
+ // `Uint8Array.buffer` is a `SharedArrayBuffer` on some Hermes versions
857
+ // — slice into a fresh ArrayBuffer to be safe.
858
+ const ab = jpeg.bytes.buffer.slice(
859
+ jpeg.bytes.byteOffset,
860
+ jpeg.bytes.byteOffset + jpeg.bytes.byteLength,
861
+ ) as ArrayBuffer;
862
+ ws.sendBinary(ab);
863
+ }
864
+ framesSentRef.current += 1;
865
+ } catch (err) {
866
+ log.warn('[Liveness] frame send failed', err);
867
+ } finally {
868
+ // After a stop, `stopCapture` already reset the pipeline; a stale pass
869
+ // must not touch the state of the one that replaced it.
870
+ if (generation === captureGenerationRef.current) {
871
+ processingRef.current = false;
872
+ const next = pendingFrameRef.current;
873
+ if (next) {
874
+ pendingFrameRef.current = null;
875
+ void processAndSendFrame(next, generation);
876
+ }
877
+ }
878
+ }
879
+ },
880
+ [sessionId],
881
+ );
882
+
883
+ const captureTick = useCallback(async () => {
884
+ if (captureInFlightRef.current || pendingFrameRef.current) return;
885
+ if (Date.now() < captureNotBeforeRef.current) return;
577
886
  const ws = wsRef.current;
578
887
  if (!ws || !ws.isOpen()) return;
579
- inFlightRef.current = true;
888
+ const generation = captureGenerationRef.current;
889
+ captureInFlightRef.current = true;
890
+ const captureStart = Date.now();
891
+ let frame: CapturedFrame | null | undefined;
580
892
  try {
581
- const photo = await cameraRef.current?.takeFrame();
582
- if (!photo || !ws.isOpen()) return;
583
- // Front-camera frames come back mirrored (vision-camera's default for
584
- // front cam, which we keep so the recorded mp4 has a correct rotation
585
- // matrix — see the `isMirrored` comment in LivenessCamera). For Iris,
586
- // we want the un-mirrored yaw so TURN_LEFT/RIGHT challenges map to
587
- // real-world directions, so we flip the JPEG horizontally here before
588
- // signing and sending.
589
- const compressed = await ImageManipulator.manipulateAsync(
590
- photo.path.startsWith('file://') ? photo.path : `file://${photo.path}`,
591
- [
592
- { resize: { width: FRAME_MAX_LONG_EDGE } },
593
- { flip: ImageManipulator.FlipType.Horizontal },
594
- ],
595
- { compress: FRAME_QUALITY, format: ImageManipulator.SaveFormat.JPEG },
596
- );
597
- if (!ws.isOpen()) return;
598
- const jpeg = await readJpegFromUri(compressed.uri);
599
- const key = hmacRef.current;
600
- if (key) {
601
- const envelope = buildSignedFrameEnvelope({
602
- key,
603
- sessionId: livenessSessionIdRef.current ?? sessionId,
604
- frameId: framesSentRef.current,
605
- jpegBytes: jpeg.bytes,
606
- jpegBase64: jpeg.base64,
607
- });
608
- ws.sendJson(envelope.json);
609
- } else {
610
- // Vision-camera + RN's WebSocket need an ArrayBuffer for binary frames.
611
- // `Uint8Array.buffer` is a `SharedArrayBuffer` on some Hermes versions
612
- // — slice into a fresh ArrayBuffer to be safe.
613
- const ab = jpeg.bytes.buffer.slice(
614
- jpeg.bytes.byteOffset,
615
- jpeg.bytes.byteOffset + jpeg.bytes.byteLength,
616
- ) as ArrayBuffer;
617
- ws.sendBinary(ab);
618
- }
619
- framesSentRef.current += 1;
893
+ frame = await cameraRef.current?.takeFrame();
620
894
  } catch (err) {
621
- log.warn('[Liveness] frame send failed', err);
895
+ log.warn('[Liveness] frame capture failed', err);
622
896
  } finally {
623
- inFlightRef.current = false;
897
+ if (generation === captureGenerationRef.current) {
898
+ captureInFlightRef.current = false;
899
+ }
624
900
  }
625
- }, [sessionId]);
901
+ if (!frame) return;
902
+ if (generation !== captureGenerationRef.current) {
903
+ releaseFrame(frame);
904
+ return;
905
+ }
906
+ const queued: QueuedFrame = { frame, captureMs: Date.now() - captureStart };
907
+ if (processingRef.current) {
908
+ pendingFrameRef.current = queued;
909
+ } else {
910
+ void processAndSendFrame(queued, generation);
911
+ }
912
+ }, [processAndSendFrame]);
626
913
 
627
914
  const startCaptureLoop = useCallback(
628
915
  (ms: number) => {
629
- stopCapture();
916
+ // Only the pacing changes here: frames already in the pipeline keep
917
+ // going, so a challenge switching the fps does not cost a frame.
918
+ clearCaptureTimer();
630
919
  frameMsRef.current = ms;
631
920
  captureTimerRef.current = setInterval(() => {
632
- void captureAndSend();
921
+ void captureTick();
633
922
  }, ms);
634
923
  },
635
- [captureAndSend, stopCapture],
924
+ [captureTick, clearCaptureTimer],
636
925
  );
637
926
 
638
927
  const adjustFps = useCallback(
@@ -657,6 +946,7 @@ function LivenessMatchView({
657
946
 
658
947
  const presentTerminalRetry = useCallback(
659
948
  (code: string, message?: string) => {
949
+ closingForRetryRef.current = true;
660
950
  stopCapture();
661
951
  stopWatchdog();
662
952
  try {
@@ -705,11 +995,13 @@ function LivenessMatchView({
705
995
  // failed before the user understood what was being asked.
706
996
  setChallengeText(t.liveness.centerFace);
707
997
  showToast('success', t.liveness.getReady);
998
+ captureNotBeforeRef.current = Date.now() + CAPTURE_WARMUP_MS;
708
999
  startCaptureLoop(FRAME_MS_DEFAULT);
709
- // Start the local mp4 recording in parallel with the frame loop, if
710
- // the backend opted in via `video_upload` in /liveness-init. Pure
711
- // best-effort: any failure here is logged and never blocks liveness.
712
- startVideoRecordingIfEnabled();
1000
+ // Do not start the evidence recorder yet. MiniFAS and positioning
1001
+ // run on these first seconds; a photo+video session on Android
1002
+ // produced blurry stills (`LOW_SHARPNESS`) and a screen-replay
1003
+ // score. Recording starts on POSITIONING_READY (or the first
1004
+ // CHALLENGE if positioning is disabled).
713
1005
  resetWatchdog();
714
1006
  return;
715
1007
  }
@@ -731,7 +1023,9 @@ function LivenessMatchView({
731
1023
  adjustFps(
732
1024
  ch === 'TURN_LEFT' || ch === 'TURN_RIGHT'
733
1025
  ? FRAME_MS_TURN
734
- : FRAME_MS_DEFAULT,
1026
+ : ch === 'BLINK'
1027
+ ? FRAME_MS_BLINK
1028
+ : FRAME_MS_DEFAULT,
735
1029
  );
736
1030
  setChallengeText(challengeLabel(ch));
737
1031
  // Map distance challenges to an oval-size cue so the viewfinder
@@ -746,6 +1040,9 @@ function LivenessMatchView({
746
1040
  : 'NEUTRAL',
747
1041
  );
748
1042
  setProgress(0);
1043
+ // Positioning skipped or already passed — start the evidence
1044
+ // recorder if it is not running yet (idempotent).
1045
+ void startVideoRecordingIfEnabled();
749
1046
  resetWatchdog();
750
1047
  return;
751
1048
  }
@@ -803,11 +1100,23 @@ function LivenessMatchView({
803
1100
  // bar, neutral oval, persistent hint — and let the SAME challenge
804
1101
  // re-arrive on its own once the user is well positioned again.
805
1102
  if (msg.code === 'CHALLENGE_REPOSITION') {
1103
+ const abortedChallenge = currentChallengeRef.current;
806
1104
  currentChallengeRef.current = null;
807
1105
  adjustFps(FRAME_MS_DEFAULT);
808
1106
  setProgress(null);
809
1107
  setOvalCue('NEUTRAL');
810
- const repositionText = msg.message ?? t.liveness.repositioning;
1108
+ // A MOVE_FARTHER abort is the one case where the orchestrator's
1109
+ // generic "center your face and improve the lighting" sends the
1110
+ // user the wrong way (OSDKR-24). Moving away shrinks the face, and
1111
+ // with it the sharpness Iris measures, until the mid-challenge
1112
+ // check aborts; the user then has to come back closer before
1113
+ // positioning reopens. On an Edge 30 Neo they stayed at the far
1114
+ // distance for 43 s. Our own copy overrides the server text here
1115
+ // until IRIS-31 stops that abort at the source.
1116
+ const repositionText =
1117
+ abortedChallenge === 'MOVE_FARTHER'
1118
+ ? t.liveness.repositioningAfterMoveFarther
1119
+ : msg.message ?? t.liveness.repositioning;
811
1120
  setChallengeText(repositionText);
812
1121
  showToast('warning', repositionText);
813
1122
  resetWatchdog();
@@ -860,6 +1169,9 @@ function LivenessMatchView({
860
1169
  .concat(' — ', baseText)
861
1170
  : baseText;
862
1171
  showToast(isPositioningReady ? 'success' : 'warning', text);
1172
+ if (isPositioningReady) {
1173
+ void startVideoRecordingIfEnabled();
1174
+ }
863
1175
  resetWatchdog();
864
1176
  return;
865
1177
  }
@@ -998,6 +1310,7 @@ function LivenessMatchView({
998
1310
  setRetry(null);
999
1311
  setStatusText(t.liveness.connecting);
1000
1312
  finalizingRef.current = false;
1313
+ closingForRetryRef.current = false;
1001
1314
  framesSentRef.current = 0;
1002
1315
  currentChallengeRef.current = null;
1003
1316
  lastChallengeMetaRef.current = null;
@@ -1083,17 +1396,30 @@ function LivenessMatchView({
1083
1396
  // — this handler is registered via closure on a stale render,
1084
1397
  // so `retry` reads `null` even when we just called `setRetry`.
1085
1398
  // The close code is reliable: we always pair 4001 with the
1086
- // retry-dialog mount.
1087
- if (code === 4001) return;
1399
+ // retry-dialog mount. `closingForRetryRef` covers the race where
1400
+ // Iris's own 1000 arrives first (it always closes NORMAL after a
1401
+ // terminal WARNING).
1402
+ if (code === 4001 || closingForRetryRef.current) return;
1088
1403
  stopCapture();
1089
- stopWatchdog();
1090
- if (code === 1000) return;
1091
- failWith({
1092
- code: SdkErrorCode.LIVENESS_FAILED,
1093
- message: `Iris WebSocket closed before completion (code=${code}${
1094
- reason ? `, reason=${reason}` : ''
1095
- }).`,
1404
+
1405
+ // Reaching here means the socket closed and the step never
1406
+ // finalized, so we do not know how the session ended (OSDKR-23).
1407
+ //
1408
+ // A close code cannot tell us: Iris closes with 1000 after a
1409
+ // successful SESSION_COMPLETE, after CHALLENGE_NOT_CONFIRMED, and
1410
+ // after SPOOF_RISK_HIGH alike. It always sends the deciding message
1411
+ // immediately before closing, so a 1000 here means we lost it.
1412
+ //
1413
+ // This used to `stopWatchdog()` and then return on 1000, which left
1414
+ // the step on the "analyzing" overlay forever with every safety net
1415
+ // disarmed. Route the user into the same recovery a terminal warning
1416
+ // uses instead: the session did not complete as far as we can tell,
1417
+ // and offering a retry is both honest and actionable.
1418
+ log.warn('[Liveness] socket closed before the step finalized', {
1419
+ code,
1420
+ reason,
1096
1421
  });
1422
+ presentTerminalRetry('CONNECTION_CLOSED', t.liveness.terminalRetryFallback);
1097
1423
  },
1098
1424
  });
1099
1425
  } catch (err) {
@@ -1114,12 +1440,13 @@ function LivenessMatchView({
1114
1440
  failWith,
1115
1441
  handleWsMessage,
1116
1442
  locale,
1443
+ presentTerminalRetry,
1117
1444
  retry,
1118
1445
  sessionId,
1119
1446
  stopCapture,
1120
- stopWatchdog,
1121
1447
  t.liveness.connecting,
1122
1448
  t.liveness.preparingCamera,
1449
+ t.liveness.terminalRetryFallback,
1123
1450
  ]);
1124
1451
 
1125
1452
  // Re-run after a terminal retry — same cleanup as start, but reuses the