@velion-la/onboarding-sdk-react-native 1.2.0-beta.9 → 1.3.0-beta.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.
Files changed (33) hide show
  1. package/lib/commonjs/camera/LivenessCamera.js +151 -39
  2. package/lib/commonjs/camera/LivenessCamera.js.map +1 -1
  3. package/lib/commonjs/i18n/strings/en.js +1 -0
  4. package/lib/commonjs/i18n/strings/en.js.map +1 -1
  5. package/lib/commonjs/i18n/strings/es.js +1 -0
  6. package/lib/commonjs/i18n/strings/es.js.map +1 -1
  7. package/lib/commonjs/steps/LivenessMatchStep.js +314 -53
  8. package/lib/commonjs/steps/LivenessMatchStep.js.map +1 -1
  9. package/lib/commonjs/transport/irisWebSocket.js +15 -2
  10. package/lib/commonjs/transport/irisWebSocket.js.map +1 -1
  11. package/lib/module/camera/LivenessCamera.js +152 -40
  12. package/lib/module/camera/LivenessCamera.js.map +1 -1
  13. package/lib/module/i18n/strings/en.js +1 -0
  14. package/lib/module/i18n/strings/en.js.map +1 -1
  15. package/lib/module/i18n/strings/es.js +1 -0
  16. package/lib/module/i18n/strings/es.js.map +1 -1
  17. package/lib/module/steps/LivenessMatchStep.js +317 -56
  18. package/lib/module/steps/LivenessMatchStep.js.map +1 -1
  19. package/lib/module/transport/irisWebSocket.js +15 -2
  20. package/lib/module/transport/irisWebSocket.js.map +1 -1
  21. package/lib/typescript/camera/LivenessCamera.d.ts +78 -10
  22. package/lib/typescript/camera/LivenessCamera.d.ts.map +1 -1
  23. package/lib/typescript/i18n/strings/en.d.ts.map +1 -1
  24. package/lib/typescript/i18n/strings/es.d.ts +1 -0
  25. package/lib/typescript/i18n/strings/es.d.ts.map +1 -1
  26. package/lib/typescript/steps/LivenessMatchStep.d.ts.map +1 -1
  27. package/lib/typescript/transport/irisWebSocket.d.ts.map +1 -1
  28. package/package.json +1 -1
  29. package/src/camera/LivenessCamera.tsx +172 -38
  30. package/src/i18n/strings/en.ts +2 -0
  31. package/src/i18n/strings/es.ts +2 -0
  32. package/src/steps/LivenessMatchStep.tsx +362 -75
  33. package/src/transport/irisWebSocket.ts +13 -1
@@ -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 { readBytesFromUri, 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,
@@ -59,6 +65,8 @@ import {
59
65
  type LivenessCameraHandle,
60
66
  type LivenessOvalCue,
61
67
  type LivenessVideoFile,
68
+ type CapturedFrame,
69
+ ACTIVE_LIVENESS_CAMERA_VARIANT,
62
70
  } from '../camera/LivenessCamera';
63
71
 
64
72
  import type { ApiCaller } from '../transport/api';
@@ -67,6 +75,21 @@ import type { StepDeps, StepModule } from './types';
67
75
  // Capture loop defaults tuned for the Iris orchestrator's frame cadence.
68
76
  const FRAME_MS_DEFAULT = 350;
69
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;
70
93
  const PROGRESS_WATCHDOG_MS = 25_000;
71
94
  /**
72
95
  * Hard ceiling for the POST /liveness-verify call that runs after
@@ -76,7 +99,166 @@ const PROGRESS_WATCHDOG_MS = 25_000;
76
99
  */
77
100
  const LIVENESS_VERIFY_TIMEOUT_MS = 20_000;
78
101
  const FRAME_MAX_LONG_EDGE = 720;
79
- 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
+ }
80
262
  /**
81
263
  * Hard ceiling for the video upload PUT to GCS that runs between SESSION_COMPLETE
82
264
  * and POST /liveness-verify. Long enough for a 5 MB upload on a slow mobile link
@@ -206,10 +388,31 @@ function LivenessMatchView({
206
388
  );
207
389
  const frameMsRef = useRef<number>(FRAME_MS_DEFAULT);
208
390
  const captureTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
209
- 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);
210
408
  const framesSentRef = useRef(0);
211
409
  const watchdogRef = useRef<ReturnType<typeof setTimeout> | null>(null);
212
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);
213
416
  const toastTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
214
417
  // Tracks the toast currently on screen so we can extend its visibility when
215
418
  // the same message arrives again (instead of dismount/remount, which made
@@ -287,14 +490,25 @@ function LivenessMatchView({
287
490
  }
288
491
  }, []);
289
492
 
290
- const stopCapture = useCallback(() => {
493
+ const clearCaptureTimer = useCallback(() => {
291
494
  if (captureTimerRef.current) {
292
495
  clearInterval(captureTimerRef.current);
293
496
  captureTimerRef.current = null;
294
497
  }
295
- inFlightRef.current = false;
296
498
  }, []);
297
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
+
298
512
  // ── Video upload pipeline (OSDKR-4) ─────────────────────────────────────
299
513
  // Everything below is best-effort: never throws into the caller; never
300
514
  // blocks liveness completion. The worst case is `videoOutcomeRef = 'failed'`
@@ -429,6 +643,16 @@ function LivenessMatchView({
429
643
  );
430
644
 
431
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;
432
656
  if (!videoUploadRef.current) {
433
657
  log.info('[Liveness] video skipped: no video_upload in liveness-init');
434
658
  return;
@@ -587,77 +811,117 @@ function LivenessMatchView({
587
811
  [deleteVideoTemp, onCancel, stopCapture, stopVideoRecordingIfActive, stopWatchdog],
588
812
  );
589
813
 
590
- const captureAndSend = useCallback(async () => {
591
- 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;
592
886
  const ws = wsRef.current;
593
887
  if (!ws || !ws.isOpen()) return;
594
- inFlightRef.current = true;
888
+ const generation = captureGenerationRef.current;
889
+ captureInFlightRef.current = true;
890
+ const captureStart = Date.now();
891
+ let frame: CapturedFrame | null | undefined;
595
892
  try {
596
- const photo = await cameraRef.current?.takeFrame();
597
- if (!photo || !ws.isOpen()) return;
598
- // DO NOT add a horizontal flip here (OSDKR-23).
599
- //
600
- // There used to be one. Under vision-camera v4 the front camera's photo
601
- // output came out mirrored, and the flip undid that so the yaw Iris
602
- // measures matched real-world directions. Under v5 the captured photo is
603
- // already un-mirrored, so the same flip *introduced* the mirroring and
604
- // inverted the sign of every turn.
605
- //
606
- // The effect was not a near miss: Iris measured the turns perfectly and
607
- // scored both directions at exactly zero, because it expects a positive
608
- // yaw delta for TURN_LEFT and a negative one for TURN_RIGHT and received
609
- // the opposite. SMILE kept working throughout — it is symmetric, so
610
- // mirroring does not touch it, which is what isolated the cause.
611
- //
612
- // The preview stays mirrored (vision-camera's `mirrorMode: 'auto'`), so
613
- // the user still sees a natural selfie view. Only what we send to Iris
614
- // has to be in real-world orientation.
615
- const compressed = await ImageManipulator.manipulateAsync(
616
- photo.filePath.startsWith('file://')
617
- ? photo.filePath
618
- : `file://${photo.filePath}`,
619
- [{ resize: { width: FRAME_MAX_LONG_EDGE } }],
620
- { compress: FRAME_QUALITY, format: ImageManipulator.SaveFormat.JPEG },
621
- );
622
- if (!ws.isOpen()) return;
623
- const jpeg = await readJpegFromUri(compressed.uri);
624
- const key = hmacRef.current;
625
- if (key) {
626
- const envelope = buildSignedFrameEnvelope({
627
- key,
628
- sessionId: livenessSessionIdRef.current ?? sessionId,
629
- frameId: framesSentRef.current,
630
- jpegBytes: jpeg.bytes,
631
- jpegBase64: jpeg.base64,
632
- });
633
- ws.sendJson(envelope.json);
634
- } else {
635
- // Vision-camera + RN's WebSocket need an ArrayBuffer for binary frames.
636
- // `Uint8Array.buffer` is a `SharedArrayBuffer` on some Hermes versions
637
- // — slice into a fresh ArrayBuffer to be safe.
638
- const ab = jpeg.bytes.buffer.slice(
639
- jpeg.bytes.byteOffset,
640
- jpeg.bytes.byteOffset + jpeg.bytes.byteLength,
641
- ) as ArrayBuffer;
642
- ws.sendBinary(ab);
643
- }
644
- framesSentRef.current += 1;
893
+ frame = await cameraRef.current?.takeFrame();
645
894
  } catch (err) {
646
- log.warn('[Liveness] frame send failed', err);
895
+ log.warn('[Liveness] frame capture failed', err);
647
896
  } finally {
648
- inFlightRef.current = false;
897
+ if (generation === captureGenerationRef.current) {
898
+ captureInFlightRef.current = false;
899
+ }
649
900
  }
650
- }, [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]);
651
913
 
652
914
  const startCaptureLoop = useCallback(
653
915
  (ms: number) => {
654
- 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();
655
919
  frameMsRef.current = ms;
656
920
  captureTimerRef.current = setInterval(() => {
657
- void captureAndSend();
921
+ void captureTick();
658
922
  }, ms);
659
923
  },
660
- [captureAndSend, stopCapture],
924
+ [captureTick, clearCaptureTimer],
661
925
  );
662
926
 
663
927
  const adjustFps = useCallback(
@@ -682,6 +946,7 @@ function LivenessMatchView({
682
946
 
683
947
  const presentTerminalRetry = useCallback(
684
948
  (code: string, message?: string) => {
949
+ closingForRetryRef.current = true;
685
950
  stopCapture();
686
951
  stopWatchdog();
687
952
  try {
@@ -730,14 +995,13 @@ function LivenessMatchView({
730
995
  // failed before the user understood what was being asked.
731
996
  setChallengeText(t.liveness.centerFace);
732
997
  showToast('success', t.liveness.getReady);
998
+ captureNotBeforeRef.current = Date.now() + CAPTURE_WARMUP_MS;
733
999
  startCaptureLoop(FRAME_MS_DEFAULT);
734
- // Start the local mp4 recording in parallel with the frame loop, if
735
- // the backend opted in via `video_upload` in /liveness-init. Pure
736
- // best-effort: any failure here is logged and never blocks liveness.
737
- // Deliberately not awaited — creating the recorder is asynchronous
738
- // in v5 and the frame loop must not wait on it. The function
739
- // swallows its own errors, so the floating promise never rejects.
740
- void 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).
741
1005
  resetWatchdog();
742
1006
  return;
743
1007
  }
@@ -759,7 +1023,9 @@ function LivenessMatchView({
759
1023
  adjustFps(
760
1024
  ch === 'TURN_LEFT' || ch === 'TURN_RIGHT'
761
1025
  ? FRAME_MS_TURN
762
- : FRAME_MS_DEFAULT,
1026
+ : ch === 'BLINK'
1027
+ ? FRAME_MS_BLINK
1028
+ : FRAME_MS_DEFAULT,
763
1029
  );
764
1030
  setChallengeText(challengeLabel(ch));
765
1031
  // Map distance challenges to an oval-size cue so the viewfinder
@@ -774,6 +1040,9 @@ function LivenessMatchView({
774
1040
  : 'NEUTRAL',
775
1041
  );
776
1042
  setProgress(0);
1043
+ // Positioning skipped or already passed — start the evidence
1044
+ // recorder if it is not running yet (idempotent).
1045
+ void startVideoRecordingIfEnabled();
777
1046
  resetWatchdog();
778
1047
  return;
779
1048
  }
@@ -831,11 +1100,23 @@ function LivenessMatchView({
831
1100
  // bar, neutral oval, persistent hint — and let the SAME challenge
832
1101
  // re-arrive on its own once the user is well positioned again.
833
1102
  if (msg.code === 'CHALLENGE_REPOSITION') {
1103
+ const abortedChallenge = currentChallengeRef.current;
834
1104
  currentChallengeRef.current = null;
835
1105
  adjustFps(FRAME_MS_DEFAULT);
836
1106
  setProgress(null);
837
1107
  setOvalCue('NEUTRAL');
838
- 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;
839
1120
  setChallengeText(repositionText);
840
1121
  showToast('warning', repositionText);
841
1122
  resetWatchdog();
@@ -888,6 +1169,9 @@ function LivenessMatchView({
888
1169
  .concat(' — ', baseText)
889
1170
  : baseText;
890
1171
  showToast(isPositioningReady ? 'success' : 'warning', text);
1172
+ if (isPositioningReady) {
1173
+ void startVideoRecordingIfEnabled();
1174
+ }
891
1175
  resetWatchdog();
892
1176
  return;
893
1177
  }
@@ -1026,6 +1310,7 @@ function LivenessMatchView({
1026
1310
  setRetry(null);
1027
1311
  setStatusText(t.liveness.connecting);
1028
1312
  finalizingRef.current = false;
1313
+ closingForRetryRef.current = false;
1029
1314
  framesSentRef.current = 0;
1030
1315
  currentChallengeRef.current = null;
1031
1316
  lastChallengeMetaRef.current = null;
@@ -1111,8 +1396,10 @@ function LivenessMatchView({
1111
1396
  // — this handler is registered via closure on a stale render,
1112
1397
  // so `retry` reads `null` even when we just called `setRetry`.
1113
1398
  // The close code is reliable: we always pair 4001 with the
1114
- // retry-dialog mount.
1115
- 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;
1116
1403
  stopCapture();
1117
1404
 
1118
1405
  // Reaching here means the socket closed and the step never
@@ -139,7 +139,14 @@ export function openIrisWebSocket(opts: IrisOpenOptions): IrisConnection {
139
139
  // Logged before dispatch so the record exists even if the handler throws.
140
140
  // This is the line that answers "did SESSION_COMPLETE / the WARNING
141
141
  // actually arrive?", which nothing could answer before.
142
- log.info('[IrisWS] message', { type: parsed.type });
142
+ log.info('[IrisWS] message', {
143
+ type: parsed.type,
144
+ ...(parsed.code != null ? { code: parsed.code } : {}),
145
+ ...(parsed.message != null ? { message: parsed.message } : {}),
146
+ ...(parsed.consecutiveMisses != null
147
+ ? { consecutiveMisses: parsed.consecutiveMisses }
148
+ : {}),
149
+ });
143
150
 
144
151
  try {
145
152
  opts.onMessage(parsed);
@@ -201,4 +208,9 @@ export const TERMINAL_WARNING_CODES = new Set<string>([
201
208
  'SPOOF_RISK_HIGH',
202
209
  'SESSION_TERMINATED',
203
210
  'BIOMETRIC_LOCK',
211
+ // Iris sends this and immediately closes with 1000 when the session ran
212
+ // to the end without confirming every challenge. If we treat it as a
213
+ // toast, the close wins a race and the step looks like a hung socket.
214
+ 'CHALLENGE_NOT_CONFIRMED',
215
+ 'CHALLENGE_FAILED_TERMINAL',
204
216
  ]);