@idmission/websdk-core 0.2.0 → 0.6.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 (183) hide show
  1. package/README.md +19 -0
  2. package/dist/attestation/clientAttestation.d.ts +5 -0
  3. package/dist/attestation/clientAttestation.d.ts.map +1 -1
  4. package/dist/attestation/clientAttestation.js +4 -4
  5. package/dist/attestation/collectClientAttestation.d.ts +3 -1
  6. package/dist/attestation/collectClientAttestation.d.ts.map +1 -1
  7. package/dist/attestation/collectClientAttestation.js +4 -3
  8. package/dist/camera/acquireCamera.d.ts +5 -0
  9. package/dist/camera/acquireCamera.d.ts.map +1 -1
  10. package/dist/camera/acquireCamera.js +25 -5
  11. package/dist/captureProgress/actor.d.ts +30 -0
  12. package/dist/captureProgress/actor.d.ts.map +1 -0
  13. package/dist/captureProgress/actor.js +754 -0
  14. package/dist/captureProgress/encoder.d.ts +7 -0
  15. package/dist/captureProgress/encoder.d.ts.map +1 -0
  16. package/dist/captureProgress/encoder.js +195 -0
  17. package/dist/captureProgress/index.d.ts +4 -0
  18. package/dist/captureProgress/index.d.ts.map +1 -0
  19. package/dist/captureProgress/index.js +45 -0
  20. package/dist/captureProgress/internal.d.ts +3 -0
  21. package/dist/captureProgress/internal.d.ts.map +1 -0
  22. package/dist/captureProgress/internal.js +1 -0
  23. package/dist/captureProgress/protocol.d.ts +224 -0
  24. package/dist/captureProgress/protocol.d.ts.map +1 -0
  25. package/dist/captureProgress/protocol.js +106 -0
  26. package/dist/captureProgress/recorder.d.ts +32 -0
  27. package/dist/captureProgress/recorder.d.ts.map +1 -0
  28. package/dist/captureProgress/recorder.js +554 -0
  29. package/dist/captureProgress/transport.d.ts +33 -0
  30. package/dist/captureProgress/transport.d.ts.map +1 -0
  31. package/dist/captureProgress/transport.js +109 -0
  32. package/dist/captureProgress/types.d.ts +35 -0
  33. package/dist/captureProgress/types.d.ts.map +1 -0
  34. package/dist/captureProgress/types.js +27 -0
  35. package/dist/client/IdmissionClient.d.ts +88 -18
  36. package/dist/client/IdmissionClient.d.ts.map +1 -1
  37. package/dist/client/IdmissionClient.js +241 -105
  38. package/dist/client/approval.d.ts +15 -0
  39. package/dist/client/approval.d.ts.map +1 -0
  40. package/dist/client/approval.js +19 -0
  41. package/dist/client/artifacts.d.ts +20 -0
  42. package/dist/client/artifacts.d.ts.map +1 -1
  43. package/dist/client/documentFileMetadata.d.ts +13 -0
  44. package/dist/client/documentFileMetadata.d.ts.map +1 -0
  45. package/dist/client/documentFileMetadata.js +51 -0
  46. package/dist/client/index.d.ts +4 -1
  47. package/dist/client/index.d.ts.map +1 -1
  48. package/dist/client/index.js +2 -0
  49. package/dist/client/payload.d.ts +3 -0
  50. package/dist/client/payload.d.ts.map +1 -1
  51. package/dist/client/payload.js +1 -0
  52. package/dist/client/submissionMetadata.d.ts +4 -1
  53. package/dist/client/submissionMetadata.d.ts.map +1 -1
  54. package/dist/client/submissionMetadata.js +13 -8
  55. package/dist/client/types.d.ts +6 -0
  56. package/dist/client/types.d.ts.map +1 -1
  57. package/dist/client/validateSession.d.ts +2 -0
  58. package/dist/client/validateSession.d.ts.map +1 -1
  59. package/dist/client/validateSession.js +53 -24
  60. package/dist/documentCapture/autoCaptureEngine.d.ts.map +1 -1
  61. package/dist/documentCapture/autoCaptureEngine.js +27 -8
  62. package/dist/documentCapture/autoCaptureGeometry.d.ts +97 -7
  63. package/dist/documentCapture/autoCaptureGeometry.d.ts.map +1 -1
  64. package/dist/documentCapture/autoCaptureGeometry.js +87 -6
  65. package/dist/documentCapture/autoCaptureMetadata.d.ts +12 -4
  66. package/dist/documentCapture/autoCaptureMetadata.d.ts.map +1 -1
  67. package/dist/documentCapture/autoCaptureMetadata.js +8 -5
  68. package/dist/documentCapture/autoCaptureOptions.d.ts +4 -5
  69. package/dist/documentCapture/autoCaptureOptions.d.ts.map +1 -1
  70. package/dist/documentCapture/autoCaptureOptions.js +4 -5
  71. package/dist/documentCapture/controller.d.ts +5 -0
  72. package/dist/documentCapture/controller.d.ts.map +1 -1
  73. package/dist/documentCapture/controller.js +37 -21
  74. package/dist/documentCapture/index.d.ts +1 -1
  75. package/dist/documentCapture/index.d.ts.map +1 -1
  76. package/dist/documentCapture/index.js +1 -1
  77. package/dist/idCapture/controller.d.ts +4 -1
  78. package/dist/idCapture/controller.d.ts.map +1 -1
  79. package/dist/idCapture/controller.js +69 -10
  80. package/dist/idCapture/state.d.ts +1 -3
  81. package/dist/idCapture/state.d.ts.map +1 -1
  82. package/dist/idCapture/submit.d.ts.map +1 -1
  83. package/dist/idCapture/submit.js +35 -1
  84. package/dist/idCapture/types.d.ts +2 -0
  85. package/dist/idCapture/types.d.ts.map +1 -1
  86. package/dist/index.d.ts +2 -0
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +1 -0
  89. package/dist/liveness/challengeGeometry.d.ts +48 -17
  90. package/dist/liveness/challengeGeometry.d.ts.map +1 -1
  91. package/dist/liveness/challengeGeometry.js +101 -54
  92. package/dist/models/DocumentDetection.d.ts.map +1 -1
  93. package/dist/models/DocumentDetection.js +38 -2
  94. package/dist/models/defaults/DocumentDetectorLiteRT.d.ts +2 -2
  95. package/dist/models/defaults/DocumentDetectorLiteRT.d.ts.map +1 -1
  96. package/dist/models/defaults/DocumentDetectorLiteRT.js +27 -2
  97. package/dist/models/defaults/HandLandmarkLiteRT.d.ts +3 -0
  98. package/dist/models/defaults/HandLandmarkLiteRT.d.ts.map +1 -0
  99. package/dist/models/defaults/HandLandmarkLiteRT.js +5 -0
  100. package/dist/models/defaults/IrisLandmarkLiteRT.d.ts +3 -0
  101. package/dist/models/defaults/IrisLandmarkLiteRT.d.ts.map +1 -0
  102. package/dist/models/defaults/IrisLandmarkLiteRT.js +5 -0
  103. package/dist/models/defaults/PalmDetectionLiteRT.d.ts +3 -0
  104. package/dist/models/defaults/PalmDetectionLiteRT.d.ts.map +1 -0
  105. package/dist/models/defaults/PalmDetectionLiteRT.js +5 -0
  106. package/dist/models/defaults/PoaDocumentDetectorLiteRT.d.ts +2 -2
  107. package/dist/models/defaults/PoaDocumentDetectorLiteRT.d.ts.map +1 -1
  108. package/dist/models/defaults/PoaDocumentDetectorLiteRT.js +12 -8
  109. package/dist/models/defaults/index.d.ts +10 -1
  110. package/dist/models/defaults/index.d.ts.map +1 -1
  111. package/dist/models/defaults/index.js +12 -0
  112. package/dist/models/preloadModels.d.ts +4 -3
  113. package/dist/models/preloadModels.d.ts.map +1 -1
  114. package/dist/models/preloadModels.js +23 -3
  115. package/dist/models/providers/litert/FaceLandmarker.d.ts +8 -1
  116. package/dist/models/providers/litert/FaceLandmarker.d.ts.map +1 -1
  117. package/dist/models/providers/litert/FaceLandmarker.js +95 -3
  118. package/dist/models/providers/litert/HandOverFaceDetector.d.ts +27 -0
  119. package/dist/models/providers/litert/HandOverFaceDetector.d.ts.map +1 -0
  120. package/dist/models/providers/litert/HandOverFaceDetector.js +162 -0
  121. package/dist/models/providers/litert/blazeFacePrePost.js +4 -2
  122. package/dist/models/providers/litert/docDetectPrePost.d.ts.map +1 -1
  123. package/dist/models/providers/litert/docDetectPrePost.js +17 -5
  124. package/dist/models/providers/litert/handLandmarkPrePost.d.ts +20 -0
  125. package/dist/models/providers/litert/handLandmarkPrePost.d.ts.map +1 -0
  126. package/dist/models/providers/litert/handLandmarkPrePost.js +72 -0
  127. package/dist/models/providers/litert/handOverFace.d.ts +44 -0
  128. package/dist/models/providers/litert/handOverFace.d.ts.map +1 -0
  129. package/dist/models/providers/litert/handOverFace.js +139 -0
  130. package/dist/models/providers/litert/irisPrePost.d.ts +38 -0
  131. package/dist/models/providers/litert/irisPrePost.d.ts.map +1 -0
  132. package/dist/models/providers/litert/irisPrePost.js +101 -0
  133. package/dist/models/providers/litert/palmPrePost.d.ts +55 -0
  134. package/dist/models/providers/litert/palmPrePost.d.ts.map +1 -0
  135. package/dist/models/providers/litert/palmPrePost.js +151 -0
  136. package/dist/sdkVersions.d.ts +18 -0
  137. package/dist/sdkVersions.d.ts.map +1 -0
  138. package/dist/sdkVersions.js +8 -0
  139. package/dist/selfieCapture/captureQuality.d.ts +43 -0
  140. package/dist/selfieCapture/captureQuality.d.ts.map +1 -0
  141. package/dist/selfieCapture/captureQuality.js +87 -0
  142. package/dist/selfieCapture/challengeRunner.d.ts +9 -2
  143. package/dist/selfieCapture/challengeRunner.d.ts.map +1 -1
  144. package/dist/selfieCapture/challengeRunner.js +2 -5
  145. package/dist/selfieCapture/controller.d.ts +62 -1
  146. package/dist/selfieCapture/controller.d.ts.map +1 -1
  147. package/dist/selfieCapture/controller.js +470 -105
  148. package/dist/selfieCapture/faceTracking.d.ts +69 -1
  149. package/dist/selfieCapture/faceTracking.d.ts.map +1 -1
  150. package/dist/selfieCapture/faceTracking.js +134 -6
  151. package/dist/selfieCapture/guidance.d.ts +15 -0
  152. package/dist/selfieCapture/guidance.d.ts.map +1 -1
  153. package/dist/selfieCapture/guidance.js +23 -0
  154. package/dist/selfieCapture/index.d.ts +3 -2
  155. package/dist/selfieCapture/index.d.ts.map +1 -1
  156. package/dist/selfieCapture/index.js +1 -1
  157. package/dist/selfieCapture/livenessMachine.d.ts +2 -0
  158. package/dist/selfieCapture/livenessMachine.d.ts.map +1 -1
  159. package/dist/selfieCapture/livenessMachine.js +8 -0
  160. package/dist/selfieCapture/pipeline.d.ts +8 -0
  161. package/dist/selfieCapture/pipeline.d.ts.map +1 -1
  162. package/dist/selfieCapture/pipeline.js +2 -2
  163. package/dist/selfieCapture/reducer.d.ts +7 -0
  164. package/dist/selfieCapture/reducer.d.ts.map +1 -1
  165. package/dist/selfieCapture/reducer.js +45 -4
  166. package/dist/selfieCapture/state.d.ts +6 -0
  167. package/dist/selfieCapture/state.d.ts.map +1 -1
  168. package/dist/selfieCapture/state.js +1 -0
  169. package/dist/signature/frameDecode.d.ts.map +1 -1
  170. package/dist/signature/frameDecode.js +29 -0
  171. package/dist/signature/metadata.d.ts +10 -1
  172. package/dist/signature/metadata.d.ts.map +1 -1
  173. package/dist/signature/quality.d.ts +14 -6
  174. package/dist/signature/quality.d.ts.map +1 -1
  175. package/dist/signature/quality.js +13 -4
  176. package/dist/signatureCapture/controller.d.ts +2 -1
  177. package/dist/signatureCapture/controller.d.ts.map +1 -1
  178. package/dist/signatureCapture/controller.js +47 -2
  179. package/dist/signatureCapture/pipeline.d.ts.map +1 -1
  180. package/dist/signatureCapture/pipeline.js +6 -1
  181. package/dist/version.d.ts +1 -1
  182. package/dist/version.js +1 -1
  183. package/package.json +10 -2
@@ -1,3 +1,4 @@
1
+ import { createCaptureSink, registerCaptureController } from '../captureProgress/actor';
1
2
  // Vanilla-store selfie capture controller (iteration 4 plan 3). Mirrors
2
3
  // idCapture/controller.ts's anatomy: io seam with receiver-strict binds
3
4
  // (:251-273), colon-namespaced timer map (:404-428), cached-snapshot
@@ -13,10 +14,11 @@ import { CaptureAttachError } from '../idCapture/errors';
13
14
  import { waitForVideoReady } from '../models/helpers';
14
15
  import { createFrameLoop } from '../models/FrameLoop';
15
16
  import { createRunningAvg, detectBrightnessAndContrast } from './lighting';
17
+ import { captureQualityException, captureRecoveryState, faceReadyWithoutLighting, resolveLightingThresholds, validateCaptureRecovery, } from './captureQuality';
16
18
  import { cropToShoulders } from '../utils/cropping';
17
19
  import { createInitialSelfieCaptureState, } from './state';
18
20
  import { reduceSelfieCapture } from './reducer';
19
- import { isSatisfiedSelfieCode } from './guidance';
21
+ import { handOverFaceHeld, isSatisfiedSelfieCode, } from './guidance';
20
22
  import { createSelfiePipeline, DEFAULT_SELFIE_DETECTOR, } from './pipeline';
21
23
  import { createInitialLivenessMachineState, hasExceededLivenessFailureLimit, reduceLivenessMachine, LIVENESS_RESET_DELAY_MS, } from './livenessMachine';
22
24
  import { createChallengeRunner, DEFAULT_CHALLENGE_COUNT, DEFAULT_RESPONSE_WINDOW_MS, } from './challengeRunner';
@@ -80,6 +82,10 @@ export function createSelfieCaptureController(config = {}) {
80
82
  createPipeline: config.io?.createPipeline ?? createSelfiePipeline,
81
83
  createCanvas: config.io?.createCanvas ?? (() => document.createElement('canvas')),
82
84
  createFrameLoop: config.io?.createFrameLoop ?? createFrameLoop,
85
+ // Imported on first use, so a flow without the check never loads the
86
+ // hand models' code.
87
+ loadHandOverFaceDetector: config.io?.loadHandOverFaceDetector ??
88
+ (() => import('../models/providers/litert/HandOverFaceDetector').then((m) => m.loadHandOverFaceDetector())),
83
89
  };
84
90
  // Challenge enable gate, sdk2 FaceLivenessCapture :684-698: the feature
85
91
  // requires the face-landmarker detector (468-point mesh / named keypoints);
@@ -93,17 +99,44 @@ export function createSelfieCaptureController(config = {}) {
93
99
  }
94
100
  const challengeEnabled = config.liveness?.challenge?.enabled === true &&
95
101
  detectorKind === 'face-landmarker';
102
+ // Same misconfig handling for the hand-over-face check: its head box is
103
+ // calibrated on the face mesh's bbox, which docdetect's face box is not.
104
+ if (config.handOverFaceCheck?.enabled === true &&
105
+ detectorKind !== 'face-landmarker') {
106
+ warn("[selfieCapture] handOverFaceCheck.enabled requires detector='face-landmarker'; " +
107
+ `got '${detectorKind}'. Skipping the hand-over-face check.`);
108
+ }
109
+ const handCheckEnabled = config.handOverFaceCheck?.enabled === true &&
110
+ detectorKind === 'face-landmarker';
111
+ if (config.captureRecovery)
112
+ validateCaptureRecovery(config.captureRecovery);
96
113
  const internal = createStore(() => ({
97
114
  ...createInitialSelfieCaptureState({ thresholds: config.thresholds }),
98
115
  camera: { ready: false, isRearFacing: false, accessRequested: false },
99
116
  capturedAttempt: null,
100
117
  capturedImageUrl: null,
118
+ captureRecovery: null,
101
119
  liveness: config.liveness ? createInitialLivenessMachineState() : null,
102
120
  challenge: null,
103
121
  livenessTimedOut: false,
122
+ retryPending: false,
123
+ handOverFace: { status: 'off', lastCheck: null },
104
124
  }));
105
- function dispatch(event) {
106
- internal.setState((s) => ({ ...s, ...reduceSelfieCapture(s, event) }));
125
+ const progressBinding = createCaptureSink();
126
+ const progress = progressBinding.sink;
127
+ function dispatch(event, recovery) {
128
+ internal.setState((s) => {
129
+ const next = { ...s, ...reduceSelfieCapture(s, event) };
130
+ if (recovery) {
131
+ next.captureRecovery = {
132
+ ...recovery,
133
+ manualCaptureReady: recovery.manualCaptureAvailable &&
134
+ faceReadyWithoutLighting(next.prediction) &&
135
+ !handOverFaceHeld(next.handOverFaceAt, io.now().getTime()),
136
+ };
137
+ }
138
+ return next;
139
+ });
107
140
  }
108
141
  // --- timers (idCapture pattern, colon-namespaced) ---
109
142
  const timers = new Map();
@@ -195,7 +228,23 @@ export function createSelfieCaptureController(config = {}) {
195
228
  };
196
229
  }
197
230
  function publish() {
231
+ const previous = snapshot;
198
232
  snapshot = toPublicState(internal.getState());
233
+ if (snapshot.camera.ready && !previous?.camera.ready)
234
+ progress.observe({ kind: 'milestone', code: 'camera-ready' });
235
+ if (snapshot.models.ready && !previous?.models.ready)
236
+ progress.observe({ kind: 'milestone', code: 'models-ready' });
237
+ if (snapshot.phase === 'loading' && snapshot.camera.ready && snapshot.models.ready)
238
+ progress.observe({ kind: 'phase', phase: 'instructions', mode: 'automatic' });
239
+ if (snapshot.capturedSelfie && snapshot.capturedSelfie !== previous?.capturedSelfie)
240
+ progress.observe({ kind: 'milestone', code: 'selfie-captured' });
241
+ if (snapshot.phase === 'completed' && previous?.phase !== 'completed') {
242
+ progress.observe({ kind: 'milestone', code: 'capture-completed' });
243
+ progress.observe({ kind: 'phase-completed' });
244
+ }
245
+ if (snapshot.error && snapshot.error !== previous?.error)
246
+ progress.observe({ kind: 'failure', code: snapshot.error.code === 'CAMERA_PERMISSION_DENIED' ? 'camera-denied' : snapshot.error.code === 'MODEL_LOAD_FAILED' ? 'model-load' : 'capture-error', terminal: false });
247
+ progress.observe({ kind: 'held-guidance', guidance: { family: 'selfie', code: snapshot.guidance.code } });
199
248
  for (const cb of [...listeners]) {
200
249
  try {
201
250
  cb(snapshot);
@@ -235,6 +284,8 @@ export function createSelfieCaptureController(config = {}) {
235
284
  let attachingGeneration = -1;
236
285
  let videoEl = null;
237
286
  let cameraHandle = null;
287
+ // Set by releaseCamera(); tells retry() to re-acquire before capturing.
288
+ let cameraReleased = false;
238
289
  let pipeline = null;
239
290
  let pipelineLoaded = false;
240
291
  // Edge-detects the model aggregate's transition into 'error' so the cause is
@@ -262,6 +313,8 @@ export function createSelfieCaptureController(config = {}) {
262
313
  let operationStartedAt = null;
263
314
  let captureStartedAt = null;
264
315
  let lastHandledAt = 0;
316
+ let recoveryElapsedMs = 0;
317
+ let lastRecoveryFrameAt = null;
265
318
  const mirrorCanvas = io.createCanvas();
266
319
  const captureCanvas = io.createCanvas();
267
320
  const rawCanvas = io.createCanvas();
@@ -291,9 +344,11 @@ export function createSelfieCaptureController(config = {}) {
291
344
  };
292
345
  // Liveness mode narrows the forwarding gate to the machine states where
293
346
  // capture may proceed (sdk2 shouldCapture, FaceLivenessCapture.tsx:996-1003):
294
- // CAPTURING always; GUIDANCE_SATISFIED only on the challenge path (after a
295
- // passed challenge the flow re-enters capture from GUIDANCE_SATISFIED on a
296
- // remounted SelfieCapture in sdk2; here the same gate re-opens forwarding).
347
+ // CAPTURING and GUIDANCE_SATISFIED. sdk2 forwarded GUIDANCE_SATISFIED only on
348
+ // the challenge path (a passed challenge re-enters capture from it, on a
349
+ // remounted SelfieCapture in sdk2). Without a challenge the state used to
350
+ // last only inside one tick; the hand-over-face check now parks the machine
351
+ // there after dropping a frame, and the loop must keep forwarding to re-arm.
297
352
  function shouldForwardToReducer() {
298
353
  const s = internal.getState();
299
354
  if (trackingOnly)
@@ -304,7 +359,7 @@ export function createSelfieCaptureController(config = {}) {
304
359
  if (!machine)
305
360
  return true;
306
361
  return (machine.requestState === 'CAPTURING' ||
307
- (challengeEnabled && machine.requestState === 'GUIDANCE_SATISFIED'));
362
+ machine.requestState === 'GUIDANCE_SATISFIED');
308
363
  }
309
364
  // Overlay tracking (sdk2's ungated `debugPrediction` channel,
310
365
  // SelfieCapture.tsx:205-208): the states where the capture path has stopped
@@ -363,7 +418,13 @@ export function createSelfieCaptureController(config = {}) {
363
418
  lastHandledAt = atMs;
364
419
  mirrorCanvas.width = vw;
365
420
  mirrorCanvas.height = vh;
366
- const ctx = mirrorCanvas.getContext('2d');
421
+ // Ask the browser to keep this canvas GPU-backed (a hint, not a
422
+ // guarantee). The lighting sample calls getImageData on it every tick;
423
+ // with the option unset, Chrome answers those repeated readbacks by
424
+ // moving the canvas to software, which turns this full-frame video draw
425
+ // into a CPU color conversion that grows with camera resolution. Only the
426
+ // first getContext call's options take effect; this is it.
427
+ const ctx = mirrorCanvas.getContext('2d', { willReadFrequently: false });
367
428
  if (ctx && el.readyState === 4) {
368
429
  ctx.translate(vw, 0);
369
430
  ctx.scale(-1, 1);
@@ -396,6 +457,7 @@ export function createSelfieCaptureController(config = {}) {
396
457
  videoHeight: vh,
397
458
  frameCapturedAt: atMs,
398
459
  lighting: lightingSample,
460
+ trackThroughPoorLighting: config.captureRecovery !== undefined,
399
461
  };
400
462
  if (!shouldForwardToReducer()) {
401
463
  // Keep the mesh tracking the face for as long as the feed is shown --
@@ -408,10 +470,21 @@ export function createSelfieCaptureController(config = {}) {
408
470
  // replace the stored capture frame or enter the auto-capture machinery.
409
471
  if (!trackingOnly)
410
472
  copyCanvas(captureCanvas, mirrorCanvas);
473
+ let recovery;
474
+ if (!trackingOnly && config.captureRecovery) {
475
+ // Count active analyzed frames. Background tabs and a stalled camera
476
+ // cannot spend a long gap instantly relaxing every threshold on return.
477
+ if (lastRecoveryFrameAt !== null) {
478
+ recoveryElapsedMs += Math.max(0, Math.min(atMs - lastRecoveryFrameAt, 1000));
479
+ }
480
+ lastRecoveryFrameAt = atMs;
481
+ recovery = captureRecoveryState(config.captureRecovery, resolveLightingThresholds(internal.getState().thresholds), recoveryElapsedMs);
482
+ }
411
483
  dispatch({
412
484
  type: trackingOnly ? 'trackingFrameAnalyzed' : 'frameAnalyzed',
413
485
  frame,
414
- });
486
+ ...(recovery ? { lightingThresholds: recovery.effectiveThresholds } : {}),
487
+ }, recovery);
415
488
  if (trackingOnly)
416
489
  return;
417
490
  const post = internal.getState();
@@ -438,18 +511,22 @@ export function createSelfieCaptureController(config = {}) {
438
511
  machine.requestState === 'GUIDANCE_SATISFIED') {
439
512
  // wizard onFaceDetected (:185-189): latch once, never overwrite.
440
513
  captureStartedAt ||= io.now();
441
- if (!busy) {
514
+ // Not while the hold after a hand-over-face drop is on: the user is
515
+ // being asked to move their hand, and re-checking every ~100ms would
516
+ // spend the main thread on a hand that is still there.
517
+ if (!busy && !handOverFaceHeld(post.handOverFaceAt, atMs)) {
442
518
  busy = true;
443
- armTimer('capture:fire', AUTO_CAPTURE_FIRE_DELAY_MS, () => doCapture());
519
+ armTimer('capture:fire', AUTO_CAPTURE_FIRE_DELAY_MS, () => {
520
+ void fireCapture();
521
+ });
444
522
  dispatchLiveness({ type: 'selfieCaptureStarted' });
445
523
  }
446
524
  }
447
525
  }
448
526
  }
449
- // doCapture (contract item 5): shared by both the auto-fire timer and
450
- // captureNow() -- sdk2 stamps autoCapture: 'Y' even on the manual button
451
- // and never adds captureMode on this path (wizard :173-183, verbatim).
452
- function doCapture() {
527
+ // Recovery commits the analyzed frame and its quality decision together.
528
+ // Manual captures identify themselves in submission metadata.
529
+ function doCapture(mode = 'auto') {
453
530
  // Clear the armed auto-fire timer FIRST, unconditionally: doCapture is
454
531
  // reachable both from that timer and from captureNow() racing ahead of
455
532
  // it, and this is the single choke point where both paths converge. If
@@ -459,6 +536,9 @@ export function createSelfieCaptureController(config = {}) {
459
536
  // otherwise bypass the reducer's phase guard and clobber the committed
460
537
  // capture with data from a frame that's no longer current.
461
538
  clearTimer('capture:fire');
539
+ // And orphan a hand-over-face check still running for that timer: its
540
+ // outcome must not land after this commit.
541
+ pendingFire = null;
462
542
  if (trackingOnly || internal.getState().phase !== 'capturing')
463
543
  return;
464
544
  // Straggler guard (liveness mode): while the machine is off the capture
@@ -486,10 +566,17 @@ export function createSelfieCaptureController(config = {}) {
486
566
  const prediction = internal.getState().prediction;
487
567
  const dataUrl = cropToShoulders(rawCanvas, cropCanvas, resizeCanvas, imageData, prediction?.face ?? undefined, 0.92, 600);
488
568
  const now = io.now();
569
+ const qualityException = qualityExceptionFor(mode, {
570
+ brightness: prediction?.brightness,
571
+ range: prediction?.range,
572
+ variance: prediction?.variance,
573
+ });
489
574
  const attempt = {
490
- autoCapture: 'Y',
575
+ autoCapture: mode === 'auto' ? 'Y' : 'N',
491
576
  captureTime: now.getTime() - (captureStartedAt ?? now).getTime(),
492
577
  operationTime: now.getTime() - (operationStartedAt ?? now).getTime(),
578
+ ...(mode === 'manual' ? { captureMode: 'Manual' } : {}),
579
+ ...(qualityException ? { captureQualityException: qualityException } : {}),
493
580
  };
494
581
  internal.setState({ capturedAttempt: attempt, capturedImageUrl: dataUrl });
495
582
  // sdk2 doCapture (SelfieCapture.tsx:238-249) fires captureStarted before
@@ -497,6 +584,7 @@ export function createSelfieCaptureController(config = {}) {
497
584
  // latch already dispatched it), needed for the manual captureNow() path.
498
585
  dispatchLiveness({ type: 'selfieCaptureStarted' });
499
586
  dispatch({ type: 'selfieCaptured', dataUrl, capturedAt: now });
587
+ notifyCaptureQualityException(qualityException);
500
588
  // Machine handoff after the flow-reducer commit (contract point 3): the
501
589
  // CAPTURE_STARTED guard on livenessReady makes any straggler drop free.
502
590
  dispatchLiveness({
@@ -511,6 +599,110 @@ export function createSelfieCaptureController(config = {}) {
511
599
  // outcomes (PASSED, denial, kick-out) stop it; so does detach().
512
600
  busy = false;
513
601
  }
602
+ function qualityExceptionFor(mode, measurements) {
603
+ if (!config.captureRecovery)
604
+ return undefined;
605
+ const state = internal.getState();
606
+ const original = resolveLightingThresholds(state.thresholds);
607
+ const recovery = state.captureRecovery ??
608
+ captureRecoveryState(config.captureRecovery, original, recoveryElapsedMs);
609
+ return captureQualityException(mode === 'manual' ? 'manual_override' : 'relaxed_thresholds', measurements, original, recovery);
610
+ }
611
+ function notifyCaptureQualityException(exception) {
612
+ if (!exception)
613
+ return;
614
+ try {
615
+ config.onCaptureQualityException?.(exception);
616
+ }
617
+ catch (cause) {
618
+ warn('[SelfieCapture] capture-quality notification failed:', cause);
619
+ }
620
+ }
621
+ // --- hand-over-face check (config.handOverFaceCheck) ---
622
+ let handDetector = null;
623
+ // The capture awaiting a check. Whatever ends or replaces that attempt —
624
+ // detach(), a fresh capture loop, legacy captureNow() committing first — clears
625
+ // it, and the check's outcome is then dropped.
626
+ let pendingFire = null;
627
+ function setHandOverFace(patch) {
628
+ internal.setState((s) => ({
629
+ handOverFace: { ...s.handOverFace, ...patch },
630
+ }));
631
+ }
632
+ // Called when the face models report ready, so the check's ~4 MB never
633
+ // delays them and is never fetched for a flow whose models failed. Nothing
634
+ // waits on it: a capture that fires first is sent unchecked.
635
+ function loadHandDetector() {
636
+ if (!handCheckEnabled ||
637
+ !active ||
638
+ internal.getState().handOverFace.status !== 'off')
639
+ return;
640
+ const generation = attachGeneration;
641
+ setHandOverFace({ status: 'loading' });
642
+ // Started inside a promise so a loader that throws synchronously fails
643
+ // open like one that rejects, instead of escaping into attach().
644
+ Promise.resolve()
645
+ .then(() => io.loadHandOverFaceDetector())
646
+ .then((detector) => {
647
+ if (generation !== attachGeneration)
648
+ return detector.dispose();
649
+ handDetector = detector;
650
+ setHandOverFace({ status: 'active' });
651
+ }, (e) => {
652
+ if (generation !== attachGeneration)
653
+ return;
654
+ warn('[selfieCapture] hand-over-face check failed to load; selfies are sent unchecked', e);
655
+ setHandOverFace({ status: 'error' });
656
+ });
657
+ }
658
+ // Shared by the auto-capture timer and timed manual recovery. The check runs on
659
+ // the frame about to be sent: `busy` stays latched through the await, so
660
+ // neither `captureCanvas` nor `prediction` can advance, and the checked
661
+ // frame is the one doCapture sends.
662
+ async function fireCapture(mode = 'auto') {
663
+ const detector = handDetector;
664
+ const face = internal.getState().prediction?.face;
665
+ if (!detector || !face) {
666
+ if (internal.getState().handOverFace.status === 'loading') {
667
+ warn('[selfieCapture] hand-over-face check still loading; this selfie is sent unchecked');
668
+ }
669
+ return doCapture(mode);
670
+ }
671
+ const fire = {};
672
+ pendingFire = fire;
673
+ let check = null;
674
+ let failure = null;
675
+ try {
676
+ check = await detector.check(captureCanvas, face.box, config.handOverFaceCheck?.coverageThreshold);
677
+ }
678
+ catch (error) {
679
+ failure = { error };
680
+ }
681
+ if (pendingFire !== fire)
682
+ return;
683
+ pendingFire = null;
684
+ if (failure) {
685
+ // Fail open for the rest of the attach: a check that threw once is not
686
+ // trusted to hold a capture again.
687
+ warn('[selfieCapture] hand-over-face check failed; selfies are sent unchecked from here on', failure.error);
688
+ handDetector = null;
689
+ detector.dispose();
690
+ setHandOverFace({ status: 'error' });
691
+ }
692
+ if (check)
693
+ setHandOverFace({ lastCheck: check });
694
+ if (check?.handOverFace && config.handOverFaceCheck?.mode !== 'observe')
695
+ return rejectCapture();
696
+ doCapture(mode);
697
+ }
698
+ // Drops the covered frame instead of sending it. The machine steps back to
699
+ // GUIDANCE_SATISFIED (a passed challenge stays passed), and the hold the
700
+ // reducer starts keeps the next ready frame from re-arming at once.
701
+ function rejectCapture() {
702
+ busy = false;
703
+ dispatchLiveness({ type: 'captureRejected' });
704
+ dispatch({ type: 'handOverFaceDetected', at: io.now().getTime() });
705
+ }
514
706
  // Shared frame-loop construction: enterCapturing() (fresh loop on
515
707
  // start()/retry()) and setThrottleMs() (recreate a running loop with the
516
708
  // new throttle) both need the identical { throttleMs, now, setTimeout }
@@ -527,13 +719,20 @@ export function createSelfieCaptureController(config = {}) {
527
719
  // callers dispatch their own event ('captureStarted'/'retryRequested')
528
720
  // first, since the reducer already re-enters 'capturing' for both.
529
721
  function enterCapturing() {
722
+ progress.observe({ kind: 'phase', phase: 'selfie', mode: 'automatic' });
723
+ progress.observe({ kind: 'milestone', code: 'operation-entered' });
530
724
  trackingOnly = false;
531
725
  operationStartedAt = io.now();
532
726
  captureStartedAt = null;
533
727
  initialDelayOver = false;
534
728
  busy = false;
535
729
  lastHandledAt = 0;
730
+ recoveryElapsedMs = 0;
731
+ lastRecoveryFrameAt = null;
732
+ lighting.clear();
733
+ internal.setState({ captureRecovery: null });
536
734
  clearTimer('capture:fire');
735
+ pendingFire = null;
537
736
  frameLoop?.stop();
538
737
  frameLoop = spawnLoop();
539
738
  frameLoop.start();
@@ -577,11 +776,20 @@ export function createSelfieCaptureController(config = {}) {
577
776
  const stateChanged = next.requestState !== prev.requestState;
578
777
  // Challenge phase lifecycle (contract points 4/5; sdk2 :700-717).
579
778
  if (stateChanged && next.requestState === 'CHALLENGE') {
779
+ const recovery = internal.getState().captureRecovery;
780
+ if (recovery) {
781
+ internal.setState({ captureRecovery: { ...recovery, manualCaptureReady: false } });
782
+ }
580
783
  challengeResultConsumed = false;
581
784
  challengeRunner = createChallengeRunner({
582
785
  challengeCount: liveness.challenge?.challengeCount ?? DEFAULT_CHALLENGE_COUNT,
583
786
  responseWindowMs: liveness.challenge?.responseWindowMs ?? DEFAULT_RESPONSE_WINDOW_MS,
584
787
  rng: liveness.rng,
788
+ // The tracking step owns the per-eye baseline and has calibrated it
789
+ // since capture began; read live because that state is replaced every
790
+ // frame. onLivePrediction runs before a frame's tracking step, so the
791
+ // runner judges each frame against the frames before it.
792
+ earBaseline: () => internal.getState().tracking.earBaseline,
585
793
  });
586
794
  internal.setState({ challenge: challengeRunner.snapshot() });
587
795
  armTimer('challenge:tick', CHALLENGE_TICK_MS, onChallengeTick);
@@ -615,6 +823,7 @@ export function createSelfieCaptureController(config = {}) {
615
823
  // Re-enter the capture loop: fresh tracking via the flow reducer
616
824
  // (no-op by identity when the flow never left 'capturing', e.g.
617
825
  // after a challenge timeout where nothing was captured).
826
+ progress.retry('capture-error');
618
827
  dispatch({ type: 'retryRequested' });
619
828
  enterCapturing();
620
829
  });
@@ -726,6 +935,8 @@ export function createSelfieCaptureController(config = {}) {
726
935
  if (snap.finalized && !challengeResultConsumed) {
727
936
  challengeResultConsumed = true;
728
937
  const result = snap.result;
938
+ if (result.passed)
939
+ progress.observe({ kind: 'milestone', code: 'challenge-completed' });
729
940
  config.liveness?.onChallengeComplete?.(result);
730
941
  dispatchLiveness(result.passed
731
942
  ? { type: 'challengePassed' }
@@ -849,6 +1060,7 @@ export function createSelfieCaptureController(config = {}) {
849
1060
  return;
850
1061
  }
851
1062
  cameraHandle = acquired;
1063
+ cameraReleased = false;
852
1064
  internal.setState((s) => ({
853
1065
  camera: {
854
1066
  ready: true,
@@ -890,6 +1102,9 @@ export function createSelfieCaptureController(config = {}) {
890
1102
  runtime: config.runtime,
891
1103
  modelAssetPath: config.modelAssetPath,
892
1104
  modelLoadTimeoutMs: config.modelLoadTimeoutMs,
1105
+ // The iris model exists for the eyes-open gate, so it is fetched and
1106
+ // run only when the gate is on.
1107
+ eyeRefinement: config.thresholds?.requireEyesOpen ?? false,
893
1108
  videoReady: () => waitForVideoReady({ current: el }),
894
1109
  onStateChange: (aggregate) => {
895
1110
  // Same reason as the ID pipeline's onLifecycleChange: the reducer
@@ -904,6 +1119,10 @@ export function createSelfieCaptureController(config = {}) {
904
1119
  }
905
1120
  lastReportedLoadState = aggregate.loadState;
906
1121
  dispatch({ type: 'modelsProgressed', models: aggregate });
1122
+ // Face models ready, on whichever path got there (attach, camera
1123
+ // recovery, a deferred camera): only now fetch the hand check's.
1124
+ if (aggregate.ready)
1125
+ loadHandDetector();
907
1126
  },
908
1127
  setTimeout: io.setTimeout,
909
1128
  clearTimeout: io.clearTimeout,
@@ -926,6 +1145,7 @@ export function createSelfieCaptureController(config = {}) {
926
1145
  pipelineLoaded = true;
927
1146
  }
928
1147
  async function doAttach(el) {
1148
+ progress.observe({ kind: 'phase', phase: 'initializing', mode: 'automatic' });
929
1149
  const generation = attachGeneration;
930
1150
  // A detach() bumps attachGeneration, so an attach still in flight belongs to
931
1151
  // a session that no longer exists and must not block this one. Without the
@@ -988,7 +1208,107 @@ export function createSelfieCaptureController(config = {}) {
988
1208
  attaching = false;
989
1209
  }
990
1210
  }
991
- return {
1211
+ let cameraReacquisition = null;
1212
+ // sdk2's retry and exit both remount FaceLivenessCapture with a new `key`
1213
+ // (FaceLivenessWizard.tsx:394-409), which throws away that component's
1214
+ // whole reducer -- INCLUDING timesLivenessCheckFailed -- so the user gets a
1215
+ // fresh set of liveness attempts. Rebuilding the machine here is that
1216
+ // remount's equivalent; without it a retry from the lockout screen
1217
+ // re-entered capture with the failure budget still spent, and the next
1218
+ // failed check re-locked immediately.
1219
+ function resetLivenessAttempt() {
1220
+ clearTimer('liveness:reset');
1221
+ clearTimer('liveness:kickout');
1222
+ clearTimer('liveness:kickoutGrace');
1223
+ // The challenge runner and its tick are NOT reducer state, so the
1224
+ // setState below cannot reach them -- runLivenessEffects runs only from
1225
+ // dispatchLiveness. Leaving CHALLENGE otherwise left the discarded runner
1226
+ // ticking, still able to fire onChallengeComplete for an attempt the user
1227
+ // had abandoned.
1228
+ clearTimer('challenge:tick');
1229
+ challengeRunner = null;
1230
+ challengeResultConsumed = false;
1231
+ // Orphan any check still in flight: its verdict would otherwise land in
1232
+ // the machine built below (the reducer's livenessChecked case is
1233
+ // unguarded), and its single-flight latch would block the fresh attempt
1234
+ // from checking at all until it settled.
1235
+ livenessGeneration += 1;
1236
+ livenessCheckInFlight = false;
1237
+ internal.setState({
1238
+ liveness: createInitialLivenessMachineState(),
1239
+ challenge: null,
1240
+ livenessTimedOut: false,
1241
+ });
1242
+ }
1243
+ // retry()'s reset of the terminal attempt, run straight away or once a
1244
+ // released camera is back. Moving off the terminal phase and verdict is
1245
+ // what takes the view's terminal screen down.
1246
+ function spendRetry() {
1247
+ if (config.liveness)
1248
+ resetLivenessAttempt();
1249
+ progress.retry('capture-error');
1250
+ internal.setState({ retryPending: false });
1251
+ dispatch({ type: 'retryRequested' });
1252
+ }
1253
+ // retry()'s capture re-entry, run straight away or once a released camera
1254
+ // is back.
1255
+ function resumeCapture() {
1256
+ enterCapturing();
1257
+ // sdk2's retry remounts the component, so its useTimeout arms a fresh
1258
+ // countdown. Clearing the timer in retry() without re-arming left a
1259
+ // retried session with no overall kick-out at all.
1260
+ if (config.liveness)
1261
+ armKickout();
1262
+ }
1263
+ async function requestCamera() {
1264
+ if (!videoEl)
1265
+ throw new Error('requestCamera() requires attach() first');
1266
+ // Non-deferred mode (or a second call after the camera is already
1267
+ // held): no-op resolve, no re-acquisition.
1268
+ if (cameraHandle)
1269
+ return;
1270
+ // Both captured before the await, same reason as acquireCameraStep's:
1271
+ // a detach()+attach() during the acquisition replaces the session AND
1272
+ // reassigns `videoEl`, so the post-await work below would otherwise
1273
+ // run against the replacement — loading ITS pipeline, concurrently
1274
+ // with the attach that already owns that job.
1275
+ const generation = attachGeneration;
1276
+ const el = videoEl;
1277
+ try {
1278
+ await acquireCameraStep(el);
1279
+ }
1280
+ catch (e) {
1281
+ // Same normalization + single-truth store write as doAttach's catch
1282
+ // (error only, derivedPhase surfaces it publicly).
1283
+ const err = e instanceof CaptureAttachError
1284
+ ? e
1285
+ : new CaptureAttachError({
1286
+ code: 'CAMERA_UNAVAILABLE',
1287
+ recoverable: true,
1288
+ cause: e,
1289
+ });
1290
+ internal.setState({ error: toSelfieCaptureError(err) });
1291
+ throw err;
1292
+ }
1293
+ // The camera is back; the MODELS may not be. `doAttach` loads the
1294
+ // pipeline AFTER the camera, so an attach that died at the camera step
1295
+ // never reached it — and a `detach()` immediately before (React
1296
+ // replacing the <video>) has already disposed the one the previous
1297
+ // session built. Close the laptop lid mid-capture and reopen it and
1298
+ // that is exactly the sequence: macOS drops the camera,
1299
+ // `enumerateDevices()` returns nothing, the re-attach fails.
1300
+ //
1301
+ // Without this, recovery cleared the error and returned to 'loading'
1302
+ // with no pipeline behind it, so the overlay sat at "downloading 0%"
1303
+ // for ever — the same shape as the signature controller's retry bug.
1304
+ // Guarded on `pipelineLoaded` so the deferred-camera path, whose
1305
+ // attach DID load the models, never restarts a completed download.
1306
+ if (!active || generation !== attachGeneration)
1307
+ return;
1308
+ if (!pipelineLoaded)
1309
+ await loadPipelineStep(el);
1310
+ }
1311
+ return registerCaptureController({
992
1312
  async attach(el) {
993
1313
  if (attached)
994
1314
  throw new Error('attach() called while already attached');
@@ -1017,11 +1337,20 @@ export function createSelfieCaptureController(config = {}) {
1017
1337
  challengeRunner = null;
1018
1338
  challengeResultConsumed = false;
1019
1339
  livenessCheckInFlight = false;
1340
+ pendingFire = null;
1341
+ // Reloaded on the next attach; a load still in flight sees the bumped
1342
+ // generation and disposes what it built.
1343
+ handDetector?.dispose();
1344
+ handDetector = null;
1020
1345
  pipeline?.dispose();
1021
1346
  pipeline = null;
1022
1347
  pipelineLoaded = false;
1023
1348
  cameraHandle?.release();
1024
1349
  cameraHandle = null;
1350
+ cameraReleased = false;
1351
+ // A reacquisition still in flight belongs to this session; its stale
1352
+ // generation keeps it from resuming the next one.
1353
+ cameraReacquisition = null;
1025
1354
  videoEl = null;
1026
1355
  internal.setState((s) => ({
1027
1356
  ...createInitialSelfieCaptureState({ thresholds: config.thresholds }),
@@ -1035,9 +1364,12 @@ export function createSelfieCaptureController(config = {}) {
1035
1364
  },
1036
1365
  capturedAttempt: null,
1037
1366
  capturedImageUrl: null,
1367
+ captureRecovery: null,
1038
1368
  liveness: config.liveness ? createInitialLivenessMachineState() : null,
1039
1369
  challenge: null,
1040
1370
  livenessTimedOut: false,
1371
+ retryPending: false,
1372
+ handOverFace: { status: 'off', lastCheck: null },
1041
1373
  }));
1042
1374
  },
1043
1375
  getState() {
@@ -1052,54 +1384,7 @@ export function createSelfieCaptureController(config = {}) {
1052
1384
  };
1053
1385
  },
1054
1386
  actions: {
1055
- async requestCamera() {
1056
- if (!videoEl)
1057
- throw new Error('requestCamera() requires attach() first');
1058
- // Non-deferred mode (or a second call after the camera is already
1059
- // held): no-op resolve, no re-acquisition.
1060
- if (cameraHandle)
1061
- return;
1062
- // Both captured before the await, same reason as acquireCameraStep's:
1063
- // a detach()+attach() during the acquisition replaces the session AND
1064
- // reassigns `videoEl`, so the post-await work below would otherwise
1065
- // run against the replacement — loading ITS pipeline, concurrently
1066
- // with the attach that already owns that job.
1067
- const generation = attachGeneration;
1068
- const el = videoEl;
1069
- try {
1070
- await acquireCameraStep(el);
1071
- }
1072
- catch (e) {
1073
- // Same normalization + single-truth store write as doAttach's catch
1074
- // (error only, derivedPhase surfaces it publicly).
1075
- const err = e instanceof CaptureAttachError
1076
- ? e
1077
- : new CaptureAttachError({
1078
- code: 'CAMERA_UNAVAILABLE',
1079
- recoverable: true,
1080
- cause: e,
1081
- });
1082
- internal.setState({ error: toSelfieCaptureError(err) });
1083
- throw err;
1084
- }
1085
- // The camera is back; the MODELS may not be. `doAttach` loads the
1086
- // pipeline AFTER the camera, so an attach that died at the camera step
1087
- // never reached it — and a `detach()` immediately before (React
1088
- // replacing the <video>) has already disposed the one the previous
1089
- // session built. Close the laptop lid mid-capture and reopen it and
1090
- // that is exactly the sequence: macOS drops the camera,
1091
- // `enumerateDevices()` returns nothing, the re-attach fails.
1092
- //
1093
- // Without this, recovery cleared the error and returned to 'loading'
1094
- // with no pipeline behind it, so the overlay sat at "downloading 0%"
1095
- // for ever — the same shape as the signature controller's retry bug.
1096
- // Guarded on `pipelineLoaded` so the deferred-camera path, whose
1097
- // attach DID load the models, never restarts a completed download.
1098
- if (!active || generation !== attachGeneration)
1099
- return;
1100
- if (!pipelineLoaded)
1101
- await loadPipelineStep(el);
1102
- },
1387
+ requestCamera,
1103
1388
  start() {
1104
1389
  // Requires a live session, same as retry() below: enterCapturing()
1105
1390
  // spawns and STARTS a frame loop and arms timers, and detach() has
@@ -1122,6 +1407,8 @@ export function createSelfieCaptureController(config = {}) {
1122
1407
  armKickout();
1123
1408
  },
1124
1409
  captureNow() {
1410
+ // Recovery below uses a fresh analyzed frame. The legacy manual
1411
+ // fallback retains sdk2's live-video draw described here.
1125
1412
  // Manual capture button (sdk2 SelfieCapture.tsx:461-467): draws the
1126
1413
  // CURRENT live frame straight from the video element -- no
1127
1414
  // translate/scale mirror flip. That asymmetry vs. the auto/gated
@@ -1135,13 +1422,45 @@ export function createSelfieCaptureController(config = {}) {
1135
1422
  // bailing here also skips the pointless canvas draw).
1136
1423
  if (internal.getState().phase !== 'capturing')
1137
1424
  return;
1425
+ if (config.captureRecovery && internal.getState().models.loadState !== 'error') {
1426
+ const state = internal.getState();
1427
+ if ((state.liveness &&
1428
+ state.liveness.requestState !== 'CAPTURING' &&
1429
+ state.liveness.requestState !== 'GUIDANCE_SATISFIED' &&
1430
+ state.liveness.requestState !== 'CAPTURE_STARTED') ||
1431
+ !state.captureRecovery?.manualCaptureReady ||
1432
+ pendingFire !== null ||
1433
+ handOverFaceHeld(state.handOverFaceAt, io.now().getTime()) ||
1434
+ lastRecoveryFrameAt === null ||
1435
+ io.now().getTime() - lastRecoveryFrameAt > 1000)
1436
+ return;
1437
+ // Manual quality recovery must not skip a configured challenge.
1438
+ if (state.liveness?.requestState === 'CAPTURING') {
1439
+ setLastChallengeResult(null);
1440
+ dispatchLiveness({
1441
+ type: 'guidanceSatisfied',
1442
+ payload: { enterChallenge: challengeEnabled },
1443
+ });
1444
+ if (challengeEnabled)
1445
+ return;
1446
+ }
1447
+ // Use the fresh analyzed frame, whose face box and lighting values
1448
+ // match the image. Redrawing here would capture an unmeasured frame.
1449
+ clearTimer('capture:fire');
1450
+ busy = true;
1451
+ internal.setState({
1452
+ captureRecovery: { ...state.captureRecovery, manualCaptureReady: false },
1453
+ });
1454
+ void fireCapture('manual');
1455
+ return;
1456
+ }
1138
1457
  const el = videoEl;
1139
1458
  if (el) {
1140
1459
  captureCanvas.width = el.videoWidth;
1141
1460
  captureCanvas.height = el.videoHeight;
1142
1461
  captureCanvas.getContext('2d')?.drawImage(el, 0, 0);
1143
1462
  }
1144
- doCapture();
1463
+ doCapture('manual');
1145
1464
  },
1146
1465
  captureManually(imageDataUrl) {
1147
1466
  const state = internal.getState();
@@ -1157,11 +1476,14 @@ export function createSelfieCaptureController(config = {}) {
1157
1476
  return;
1158
1477
  }
1159
1478
  const now = io.now();
1479
+ const qualityException = qualityExceptionFor('manual', {});
1160
1480
  // sdk2's fallback capture is a user action with no detection behind
1161
1481
  // it, so the attempt is stamped 'N' (idCapture's runManualCapture
1162
1482
  // does the same for its own fallback path).
1163
1483
  const attempt = {
1164
1484
  autoCapture: 'N',
1485
+ captureMode: 'Manual',
1486
+ ...(qualityException ? { captureQualityException: qualityException } : {}),
1165
1487
  captureTime: now.getTime() - (captureStartedAt ?? now).getTime(),
1166
1488
  operationTime: now.getTime() - (operationStartedAt ?? now).getTime(),
1167
1489
  };
@@ -1174,6 +1496,7 @@ export function createSelfieCaptureController(config = {}) {
1174
1496
  dataUrl: imageDataUrl,
1175
1497
  capturedAt: now,
1176
1498
  });
1499
+ notifyCaptureQualityException(qualityException);
1177
1500
  },
1178
1501
  startTracking() {
1179
1502
  if (!active || !internal.getState().models.ready)
@@ -1184,13 +1507,14 @@ export function createSelfieCaptureController(config = {}) {
1184
1507
  lastHandledAt = 0;
1185
1508
  clearTimer('capture:initialDelay');
1186
1509
  clearTimer('capture:fire');
1510
+ // A hand-over-face check still running would otherwise capture its
1511
+ // stale frame once stopTracking() reopens the capture path.
1512
+ pendingFire = null;
1187
1513
  frameLoop?.stop();
1188
1514
  frameLoop = spawnLoop();
1189
1515
  frameLoop.start();
1190
1516
  },
1191
1517
  stopTracking() {
1192
- if (!trackingOnly)
1193
- return;
1194
1518
  trackingOnly = false;
1195
1519
  frameLoop?.stop();
1196
1520
  initialDelayOver = false;
@@ -1206,48 +1530,89 @@ export function createSelfieCaptureController(config = {}) {
1206
1530
  frameLoop.start();
1207
1531
  }
1208
1532
  },
1533
+ releaseCamera() {
1534
+ if (!cameraHandle)
1535
+ return;
1536
+ cameraHandle.release();
1537
+ cameraHandle = null;
1538
+ cameraReleased = true;
1539
+ internal.setState((s) => ({ camera: { ...s.camera, ready: false } }));
1540
+ },
1209
1541
  retry() {
1210
1542
  if (!active)
1211
1543
  return;
1212
- // sdk2's retry remounts FaceLivenessCapture with a new `key`
1213
- // (FaceLivenessWizard.tsx:402-409), which throws away that
1214
- // component's whole reducer -- INCLUDING timesLivenessCheckFailed --
1215
- // so the user gets a fresh set of liveness attempts. Rebuilding the
1216
- // machine here is that remount's equivalent; without it a retry from
1217
- // the lockout screen re-entered capture with the failure budget still
1218
- // spent, and the next failed check re-locked immediately.
1219
- if (config.liveness) {
1220
- clearTimer('liveness:reset');
1221
- clearTimer('liveness:kickout');
1222
- clearTimer('liveness:kickoutGrace');
1223
- // The challenge runner and its tick are NOT reducer state, so the
1224
- // setState below cannot reach them -- runLivenessEffects runs only
1225
- // from dispatchLiveness. Retrying out of CHALLENGE otherwise left
1226
- // the discarded runner ticking, still able to fire
1227
- // onChallengeComplete for an attempt the user had abandoned.
1228
- clearTimer('challenge:tick');
1229
- challengeRunner = null;
1230
- challengeResultConsumed = false;
1231
- // Orphan any check still in flight: its verdict would otherwise land
1232
- // in the machine built below (the reducer's livenessChecked case is
1233
- // unguarded), and its single-flight latch would block the fresh
1234
- // attempt from checking at all until it settled.
1235
- livenessGeneration += 1;
1236
- livenessCheckInFlight = false;
1237
- internal.setState({
1238
- liveness: createInitialLivenessMachineState(),
1239
- challenge: null,
1240
- livenessTimedOut: false,
1241
- });
1544
+ if (!cameraReleased) {
1545
+ spendRetry();
1546
+ resumeCapture();
1547
+ return;
1242
1548
  }
1243
- dispatch({ type: 'retryRequested' });
1244
- enterCapturing();
1245
- // sdk2's retry remounts the component, so its useTimeout arms a fresh
1246
- // countdown. Clearing the timer above without re-arming left a retried
1247
- // session with no overall kick-out at all.
1549
+ // The terminal screen handed the camera back: get it again BEFORE
1550
+ // leaving that screen, so the user never lands on a feed with no
1551
+ // stream, and the initial-delay gate and kick-out count from a live
1552
+ // feed. A second retry() while this is in flight joins it.
1553
+ if (cameraReacquisition)
1554
+ return;
1555
+ internal.setState({ retryPending: true });
1556
+ const generation = attachGeneration;
1557
+ // exitCapture() clears `retryPending` if it sent the user back to the
1558
+ // instructions while the camera was coming back.
1559
+ const stillPending = () => active &&
1560
+ generation === attachGeneration &&
1561
+ internal.getState().retryPending;
1562
+ const reacquisition = requestCamera()
1563
+ .then(() => {
1564
+ if (!stillPending())
1565
+ return;
1566
+ spendRetry();
1567
+ resumeCapture();
1568
+ }, () => {
1569
+ // Spend the attempt anyway so the terminal screen gives way to
1570
+ // the camera error screen, whose recovery re-enters through
1571
+ // 'loading'. 'retryRequested' clears `error`, so the one
1572
+ // requestCamera wrote goes back on after it.
1573
+ if (!stillPending())
1574
+ return;
1575
+ const { error } = internal.getState();
1576
+ spendRetry();
1577
+ internal.setState({ error });
1578
+ })
1579
+ .finally(() => {
1580
+ // detach() may have dropped this one and a newer one started.
1581
+ if (cameraReacquisition === reacquisition)
1582
+ cameraReacquisition = null;
1583
+ });
1584
+ cameraReacquisition = reacquisition;
1585
+ },
1586
+ exitCapture() {
1587
+ if (!active)
1588
+ return;
1589
+ const { phase } = internal.getState();
1590
+ if (phase === 'initializing' || phase === 'loading')
1591
+ return;
1592
+ // Every armed timer belongs to the abandoned attempt.
1593
+ clearAllTimers();
1594
+ frameLoop?.stop();
1595
+ frameLoop = null;
1596
+ trackingOnly = false;
1597
+ initialDelayOver = false;
1598
+ busy = false;
1599
+ pendingFire = null;
1248
1600
  if (config.liveness)
1249
- armKickout();
1601
+ resetLivenessAttempt();
1602
+ progress.retry('user-requested');
1603
+ internal.setState({
1604
+ capturedAttempt: null,
1605
+ capturedImageUrl: null,
1606
+ captureRecovery: null,
1607
+ retryPending: false,
1608
+ });
1609
+ dispatch({ type: 'exitRequested' });
1610
+ // The overlay waits on `camera.ready`, so a camera handed back by a
1611
+ // terminal screen has to come back for its continue to enable. A
1612
+ // failure lands in `error` (requestCamera's own write).
1613
+ if (cameraReleased && !cameraReacquisition)
1614
+ void requestCamera().catch(() => { });
1250
1615
  },
1251
1616
  },
1252
- };
1617
+ }, progressBinding);
1253
1618
  }