@velion-la/onboarding-sdk-react-native 1.0.0-beta.10

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 (614) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/LICENSE +12 -0
  3. package/README.md +888 -0
  4. package/app.plugin.js +101 -0
  5. package/lib/commonjs/camera/AddressSearchBar.js +304 -0
  6. package/lib/commonjs/camera/AddressSearchBar.js.map +1 -0
  7. package/lib/commonjs/camera/DocumentCapture.js +513 -0
  8. package/lib/commonjs/camera/DocumentCapture.js.map +1 -0
  9. package/lib/commonjs/camera/LivenessCamera.js +628 -0
  10. package/lib/commonjs/camera/LivenessCamera.js.map +1 -0
  11. package/lib/commonjs/camera/MapAddressPicker.js +331 -0
  12. package/lib/commonjs/camera/MapAddressPicker.js.map +1 -0
  13. package/lib/commonjs/core/VelionOnboarding.js +1113 -0
  14. package/lib/commonjs/core/VelionOnboarding.js.map +1 -0
  15. package/lib/commonjs/core/retryStepCopy.js +43 -0
  16. package/lib/commonjs/core/retryStepCopy.js.map +1 -0
  17. package/lib/commonjs/core/routingCommands.js +62 -0
  18. package/lib/commonjs/core/routingCommands.js.map +1 -0
  19. package/lib/commonjs/core/sessionDeclinedCopy.js +56 -0
  20. package/lib/commonjs/core/sessionDeclinedCopy.js.map +1 -0
  21. package/lib/commonjs/core/sessionStateMapper.js +200 -0
  22. package/lib/commonjs/core/sessionStateMapper.js.map +1 -0
  23. package/lib/commonjs/core/sseReasonMessages.js +450 -0
  24. package/lib/commonjs/core/sseReasonMessages.js.map +1 -0
  25. package/lib/commonjs/data/iso3166Alpha2Codes.json +1 -0
  26. package/lib/commonjs/data/iso3166CountryNames.json +251 -0
  27. package/lib/commonjs/i18n/index.js +30 -0
  28. package/lib/commonjs/i18n/index.js.map +1 -0
  29. package/lib/commonjs/i18n/strings/en.js +301 -0
  30. package/lib/commonjs/i18n/strings/en.js.map +1 -0
  31. package/lib/commonjs/i18n/strings/es.js +306 -0
  32. package/lib/commonjs/i18n/strings/es.js.map +1 -0
  33. package/lib/commonjs/index.js +225 -0
  34. package/lib/commonjs/index.js.map +1 -0
  35. package/lib/commonjs/package.json +1 -0
  36. package/lib/commonjs/steps/AddressInfoStep.js +662 -0
  37. package/lib/commonjs/steps/AddressInfoStep.js.map +1 -0
  38. package/lib/commonjs/steps/DocumentsOcrStep.js +405 -0
  39. package/lib/commonjs/steps/DocumentsOcrStep.js.map +1 -0
  40. package/lib/commonjs/steps/EconomicActivityStep.js +214 -0
  41. package/lib/commonjs/steps/EconomicActivityStep.js.map +1 -0
  42. package/lib/commonjs/steps/EmailContactStep.js +150 -0
  43. package/lib/commonjs/steps/EmailContactStep.js.map +1 -0
  44. package/lib/commonjs/steps/EmailOtpStep.js +225 -0
  45. package/lib/commonjs/steps/EmailOtpStep.js.map +1 -0
  46. package/lib/commonjs/steps/FaceMatchStep.js +169 -0
  47. package/lib/commonjs/steps/FaceMatchStep.js.map +1 -0
  48. package/lib/commonjs/steps/FingerprintStep.js +92 -0
  49. package/lib/commonjs/steps/FingerprintStep.js.map +1 -0
  50. package/lib/commonjs/steps/HumanBasicInfoStep.js +251 -0
  51. package/lib/commonjs/steps/HumanBasicInfoStep.js.map +1 -0
  52. package/lib/commonjs/steps/HumanExtendedInfoStep.js +275 -0
  53. package/lib/commonjs/steps/HumanExtendedInfoStep.js.map +1 -0
  54. package/lib/commonjs/steps/LegalBasicInfoStep.js +195 -0
  55. package/lib/commonjs/steps/LegalBasicInfoStep.js.map +1 -0
  56. package/lib/commonjs/steps/LegalExtendedInfoStep.js +173 -0
  57. package/lib/commonjs/steps/LegalExtendedInfoStep.js.map +1 -0
  58. package/lib/commonjs/steps/LivenessMatchStep.js +1184 -0
  59. package/lib/commonjs/steps/LivenessMatchStep.js.map +1 -0
  60. package/lib/commonjs/steps/PhoneContactStep.js +151 -0
  61. package/lib/commonjs/steps/PhoneContactStep.js.map +1 -0
  62. package/lib/commonjs/steps/PhoneOtpStep.js +224 -0
  63. package/lib/commonjs/steps/PhoneOtpStep.js.map +1 -0
  64. package/lib/commonjs/steps/SwornDeclarationStep.js +206 -0
  65. package/lib/commonjs/steps/SwornDeclarationStep.js.map +1 -0
  66. package/lib/commonjs/steps/TaxInfoStep.js +251 -0
  67. package/lib/commonjs/steps/TaxInfoStep.js.map +1 -0
  68. package/lib/commonjs/steps/TermsAndConditionsStep.js +245 -0
  69. package/lib/commonjs/steps/TermsAndConditionsStep.js.map +1 -0
  70. package/lib/commonjs/steps/_shared.js +61 -0
  71. package/lib/commonjs/steps/_shared.js.map +1 -0
  72. package/lib/commonjs/steps/types.js +6 -0
  73. package/lib/commonjs/steps/types.js.map +1 -0
  74. package/lib/commonjs/transport/api.js +176 -0
  75. package/lib/commonjs/transport/api.js.map +1 -0
  76. package/lib/commonjs/transport/irisWebSocket.js +121 -0
  77. package/lib/commonjs/transport/irisWebSocket.js.map +1 -0
  78. package/lib/commonjs/transport/secureUrl.js +50 -0
  79. package/lib/commonjs/transport/secureUrl.js.map +1 -0
  80. package/lib/commonjs/transport/sse.js +248 -0
  81. package/lib/commonjs/transport/sse.js.map +1 -0
  82. package/lib/commonjs/types/index.js +458 -0
  83. package/lib/commonjs/types/index.js.map +1 -0
  84. package/lib/commonjs/ui/MapFallbackBoundary.js +42 -0
  85. package/lib/commonjs/ui/MapFallbackBoundary.js.map +1 -0
  86. package/lib/commonjs/ui/StepShell.js +251 -0
  87. package/lib/commonjs/ui/StepShell.js.map +1 -0
  88. package/lib/commonjs/ui/VelionOnboardingScreen.js +276 -0
  89. package/lib/commonjs/ui/VelionOnboardingScreen.js.map +1 -0
  90. package/lib/commonjs/ui/forms/index.js +38 -0
  91. package/lib/commonjs/ui/forms/index.js.map +1 -0
  92. package/lib/commonjs/ui/forms/useInlineValidation.js +88 -0
  93. package/lib/commonjs/ui/forms/useInlineValidation.js.map +1 -0
  94. package/lib/commonjs/ui/forms/validators.js +34 -0
  95. package/lib/commonjs/ui/forms/validators.js.map +1 -0
  96. package/lib/commonjs/ui/icons/HomeHeartIcon.js +38 -0
  97. package/lib/commonjs/ui/icons/HomeHeartIcon.js.map +1 -0
  98. package/lib/commonjs/ui/icons/StepIcon.js +59 -0
  99. package/lib/commonjs/ui/icons/StepIcon.js.map +1 -0
  100. package/lib/commonjs/ui/overlays/AnalyzingOverlay.js +284 -0
  101. package/lib/commonjs/ui/overlays/AnalyzingOverlay.js.map +1 -0
  102. package/lib/commonjs/ui/overlays/LoadingOverlay.js +108 -0
  103. package/lib/commonjs/ui/overlays/LoadingOverlay.js.map +1 -0
  104. package/lib/commonjs/ui/overlays/ProgressBar.js +101 -0
  105. package/lib/commonjs/ui/overlays/ProgressBar.js.map +1 -0
  106. package/lib/commonjs/ui/overlays/RetryDialog.js +125 -0
  107. package/lib/commonjs/ui/overlays/RetryDialog.js.map +1 -0
  108. package/lib/commonjs/ui/overlays/index.js +33 -0
  109. package/lib/commonjs/ui/overlays/index.js.map +1 -0
  110. package/lib/commonjs/ui/primitives/BackButton.js +75 -0
  111. package/lib/commonjs/ui/primitives/BackButton.js.map +1 -0
  112. package/lib/commonjs/ui/primitives/Banner.js +81 -0
  113. package/lib/commonjs/ui/primitives/Banner.js.map +1 -0
  114. package/lib/commonjs/ui/primitives/Button.js +142 -0
  115. package/lib/commonjs/ui/primitives/Button.js.map +1 -0
  116. package/lib/commonjs/ui/primitives/Card.js +50 -0
  117. package/lib/commonjs/ui/primitives/Card.js.map +1 -0
  118. package/lib/commonjs/ui/primitives/Checkbox.js +139 -0
  119. package/lib/commonjs/ui/primitives/Checkbox.js.map +1 -0
  120. package/lib/commonjs/ui/primitives/CountrySelect.js +288 -0
  121. package/lib/commonjs/ui/primitives/CountrySelect.js.map +1 -0
  122. package/lib/commonjs/ui/primitives/DatePicker.js +245 -0
  123. package/lib/commonjs/ui/primitives/DatePicker.js.map +1 -0
  124. package/lib/commonjs/ui/primitives/Input.js +101 -0
  125. package/lib/commonjs/ui/primitives/Input.js.map +1 -0
  126. package/lib/commonjs/ui/primitives/SearchableSingleSelectList.js +162 -0
  127. package/lib/commonjs/ui/primitives/SearchableSingleSelectList.js.map +1 -0
  128. package/lib/commonjs/ui/primitives/Select.js +209 -0
  129. package/lib/commonjs/ui/primitives/Select.js.map +1 -0
  130. package/lib/commonjs/ui/primitives/Spinner.js +25 -0
  131. package/lib/commonjs/ui/primitives/Spinner.js.map +1 -0
  132. package/lib/commonjs/ui/primitives/index.js +89 -0
  133. package/lib/commonjs/ui/primitives/index.js.map +1 -0
  134. package/lib/commonjs/ui/primitives/searchableSingleSelectFilter.js +31 -0
  135. package/lib/commonjs/ui/primitives/searchableSingleSelectFilter.js.map +1 -0
  136. package/lib/commonjs/ui/theme/ThemeProvider.js +74 -0
  137. package/lib/commonjs/ui/theme/ThemeProvider.js.map +1 -0
  138. package/lib/commonjs/ui/theme/index.js +68 -0
  139. package/lib/commonjs/ui/theme/index.js.map +1 -0
  140. package/lib/commonjs/ui/theme/tokens.js +154 -0
  141. package/lib/commonjs/ui/theme/tokens.js.map +1 -0
  142. package/lib/commonjs/utils/EventEmitter.js +144 -0
  143. package/lib/commonjs/utils/EventEmitter.js.map +1 -0
  144. package/lib/commonjs/utils/base64.js +53 -0
  145. package/lib/commonjs/utils/base64.js.map +1 -0
  146. package/lib/commonjs/utils/deviceFingerprint.js +132 -0
  147. package/lib/commonjs/utils/deviceFingerprint.js.map +1 -0
  148. package/lib/commonjs/utils/documentTypeOptions.js +35 -0
  149. package/lib/commonjs/utils/documentTypeOptions.js.map +1 -0
  150. package/lib/commonjs/utils/googleMapsPreflight.js +88 -0
  151. package/lib/commonjs/utils/googleMapsPreflight.js.map +1 -0
  152. package/lib/commonjs/utils/hmac.js +58 -0
  153. package/lib/commonjs/utils/hmac.js.map +1 -0
  154. package/lib/commonjs/utils/iso3166Countries.js +98 -0
  155. package/lib/commonjs/utils/iso3166Countries.js.map +1 -0
  156. package/lib/commonjs/utils/jpegFromUri.js +44 -0
  157. package/lib/commonjs/utils/jpegFromUri.js.map +1 -0
  158. package/lib/commonjs/utils/keepAwake.js +58 -0
  159. package/lib/commonjs/utils/keepAwake.js.map +1 -0
  160. package/lib/commonjs/utils/log.js +42 -0
  161. package/lib/commonjs/utils/log.js.map +1 -0
  162. package/lib/commonjs/utils/osGeocoder.js +70 -0
  163. package/lib/commonjs/utils/osGeocoder.js.map +1 -0
  164. package/lib/commonjs/utils/parseGoogleAddressComponents.js +74 -0
  165. package/lib/commonjs/utils/parseGoogleAddressComponents.js.map +1 -0
  166. package/lib/commonjs/utils/personNameNormalize.js +24 -0
  167. package/lib/commonjs/utils/personNameNormalize.js.map +1 -0
  168. package/lib/commonjs/utils/sdkError.js +34 -0
  169. package/lib/commonjs/utils/sdkError.js.map +1 -0
  170. package/lib/commonjs/utils/sdkVersion.js +13 -0
  171. package/lib/commonjs/utils/sdkVersion.js.map +1 -0
  172. package/lib/commonjs/utils/stepConfig.js +65 -0
  173. package/lib/commonjs/utils/stepConfig.js.map +1 -0
  174. package/lib/commonjs/utils/taxInfoConfig.js +19 -0
  175. package/lib/commonjs/utils/taxInfoConfig.js.map +1 -0
  176. package/lib/commonjs/utils/useSafeAreaInsets.js +41 -0
  177. package/lib/commonjs/utils/useSafeAreaInsets.js.map +1 -0
  178. package/lib/commonjs/utils/velionExtra.js +48 -0
  179. package/lib/commonjs/utils/velionExtra.js.map +1 -0
  180. package/lib/module/camera/AddressSearchBar.js +299 -0
  181. package/lib/module/camera/AddressSearchBar.js.map +1 -0
  182. package/lib/module/camera/DocumentCapture.js +508 -0
  183. package/lib/module/camera/DocumentCapture.js.map +1 -0
  184. package/lib/module/camera/LivenessCamera.js +623 -0
  185. package/lib/module/camera/LivenessCamera.js.map +1 -0
  186. package/lib/module/camera/MapAddressPicker.js +326 -0
  187. package/lib/module/camera/MapAddressPicker.js.map +1 -0
  188. package/lib/module/core/VelionOnboarding.js +1109 -0
  189. package/lib/module/core/VelionOnboarding.js.map +1 -0
  190. package/lib/module/core/retryStepCopy.js +39 -0
  191. package/lib/module/core/retryStepCopy.js.map +1 -0
  192. package/lib/module/core/routingCommands.js +57 -0
  193. package/lib/module/core/routingCommands.js.map +1 -0
  194. package/lib/module/core/sessionDeclinedCopy.js +52 -0
  195. package/lib/module/core/sessionDeclinedCopy.js.map +1 -0
  196. package/lib/module/core/sessionStateMapper.js +189 -0
  197. package/lib/module/core/sessionStateMapper.js.map +1 -0
  198. package/lib/module/core/sseReasonMessages.js +446 -0
  199. package/lib/module/core/sseReasonMessages.js.map +1 -0
  200. package/lib/module/data/iso3166Alpha2Codes.json +1 -0
  201. package/lib/module/data/iso3166CountryNames.json +251 -0
  202. package/lib/module/i18n/index.js +25 -0
  203. package/lib/module/i18n/index.js.map +1 -0
  204. package/lib/module/i18n/strings/en.js +297 -0
  205. package/lib/module/i18n/strings/en.js.map +1 -0
  206. package/lib/module/i18n/strings/es.js +302 -0
  207. package/lib/module/i18n/strings/es.js.map +1 -0
  208. package/lib/module/index.js +36 -0
  209. package/lib/module/index.js.map +1 -0
  210. package/lib/module/steps/AddressInfoStep.js +658 -0
  211. package/lib/module/steps/AddressInfoStep.js.map +1 -0
  212. package/lib/module/steps/DocumentsOcrStep.js +399 -0
  213. package/lib/module/steps/DocumentsOcrStep.js.map +1 -0
  214. package/lib/module/steps/EconomicActivityStep.js +209 -0
  215. package/lib/module/steps/EconomicActivityStep.js.map +1 -0
  216. package/lib/module/steps/EmailContactStep.js +145 -0
  217. package/lib/module/steps/EmailContactStep.js.map +1 -0
  218. package/lib/module/steps/EmailOtpStep.js +220 -0
  219. package/lib/module/steps/EmailOtpStep.js.map +1 -0
  220. package/lib/module/steps/FaceMatchStep.js +164 -0
  221. package/lib/module/steps/FaceMatchStep.js.map +1 -0
  222. package/lib/module/steps/FingerprintStep.js +87 -0
  223. package/lib/module/steps/FingerprintStep.js.map +1 -0
  224. package/lib/module/steps/HumanBasicInfoStep.js +246 -0
  225. package/lib/module/steps/HumanBasicInfoStep.js.map +1 -0
  226. package/lib/module/steps/HumanExtendedInfoStep.js +270 -0
  227. package/lib/module/steps/HumanExtendedInfoStep.js.map +1 -0
  228. package/lib/module/steps/LegalBasicInfoStep.js +190 -0
  229. package/lib/module/steps/LegalBasicInfoStep.js.map +1 -0
  230. package/lib/module/steps/LegalExtendedInfoStep.js +168 -0
  231. package/lib/module/steps/LegalExtendedInfoStep.js.map +1 -0
  232. package/lib/module/steps/LivenessMatchStep.js +1177 -0
  233. package/lib/module/steps/LivenessMatchStep.js.map +1 -0
  234. package/lib/module/steps/PhoneContactStep.js +146 -0
  235. package/lib/module/steps/PhoneContactStep.js.map +1 -0
  236. package/lib/module/steps/PhoneOtpStep.js +219 -0
  237. package/lib/module/steps/PhoneOtpStep.js.map +1 -0
  238. package/lib/module/steps/SwornDeclarationStep.js +203 -0
  239. package/lib/module/steps/SwornDeclarationStep.js.map +1 -0
  240. package/lib/module/steps/TaxInfoStep.js +246 -0
  241. package/lib/module/steps/TaxInfoStep.js.map +1 -0
  242. package/lib/module/steps/TermsAndConditionsStep.js +240 -0
  243. package/lib/module/steps/TermsAndConditionsStep.js.map +1 -0
  244. package/lib/module/steps/_shared.js +52 -0
  245. package/lib/module/steps/_shared.js.map +1 -0
  246. package/lib/module/steps/types.js +4 -0
  247. package/lib/module/steps/types.js.map +1 -0
  248. package/lib/module/transport/api.js +173 -0
  249. package/lib/module/transport/api.js.map +1 -0
  250. package/lib/module/transport/irisWebSocket.js +115 -0
  251. package/lib/module/transport/irisWebSocket.js.map +1 -0
  252. package/lib/module/transport/secureUrl.js +45 -0
  253. package/lib/module/transport/secureUrl.js.map +1 -0
  254. package/lib/module/transport/sse.js +242 -0
  255. package/lib/module/transport/sse.js.map +1 -0
  256. package/lib/module/types/index.js +532 -0
  257. package/lib/module/types/index.js.map +1 -0
  258. package/lib/module/ui/MapFallbackBoundary.js +37 -0
  259. package/lib/module/ui/MapFallbackBoundary.js.map +1 -0
  260. package/lib/module/ui/StepShell.js +246 -0
  261. package/lib/module/ui/StepShell.js.map +1 -0
  262. package/lib/module/ui/VelionOnboardingScreen.js +273 -0
  263. package/lib/module/ui/VelionOnboardingScreen.js.map +1 -0
  264. package/lib/module/ui/forms/index.js +5 -0
  265. package/lib/module/ui/forms/index.js.map +1 -0
  266. package/lib/module/ui/forms/useInlineValidation.js +84 -0
  267. package/lib/module/ui/forms/useInlineValidation.js.map +1 -0
  268. package/lib/module/ui/forms/validators.js +27 -0
  269. package/lib/module/ui/forms/validators.js.map +1 -0
  270. package/lib/module/ui/icons/HomeHeartIcon.js +33 -0
  271. package/lib/module/ui/icons/HomeHeartIcon.js.map +1 -0
  272. package/lib/module/ui/icons/StepIcon.js +55 -0
  273. package/lib/module/ui/icons/StepIcon.js.map +1 -0
  274. package/lib/module/ui/overlays/AnalyzingOverlay.js +279 -0
  275. package/lib/module/ui/overlays/AnalyzingOverlay.js.map +1 -0
  276. package/lib/module/ui/overlays/LoadingOverlay.js +104 -0
  277. package/lib/module/ui/overlays/LoadingOverlay.js.map +1 -0
  278. package/lib/module/ui/overlays/ProgressBar.js +97 -0
  279. package/lib/module/ui/overlays/ProgressBar.js.map +1 -0
  280. package/lib/module/ui/overlays/RetryDialog.js +121 -0
  281. package/lib/module/ui/overlays/RetryDialog.js.map +1 -0
  282. package/lib/module/ui/overlays/index.js +6 -0
  283. package/lib/module/ui/overlays/index.js.map +1 -0
  284. package/lib/module/ui/primitives/BackButton.js +71 -0
  285. package/lib/module/ui/primitives/BackButton.js.map +1 -0
  286. package/lib/module/ui/primitives/Banner.js +77 -0
  287. package/lib/module/ui/primitives/Banner.js.map +1 -0
  288. package/lib/module/ui/primitives/Button.js +138 -0
  289. package/lib/module/ui/primitives/Button.js.map +1 -0
  290. package/lib/module/ui/primitives/Card.js +46 -0
  291. package/lib/module/ui/primitives/Card.js.map +1 -0
  292. package/lib/module/ui/primitives/Checkbox.js +136 -0
  293. package/lib/module/ui/primitives/Checkbox.js.map +1 -0
  294. package/lib/module/ui/primitives/CountrySelect.js +284 -0
  295. package/lib/module/ui/primitives/CountrySelect.js.map +1 -0
  296. package/lib/module/ui/primitives/DatePicker.js +241 -0
  297. package/lib/module/ui/primitives/DatePicker.js.map +1 -0
  298. package/lib/module/ui/primitives/Input.js +97 -0
  299. package/lib/module/ui/primitives/Input.js.map +1 -0
  300. package/lib/module/ui/primitives/SearchableSingleSelectList.js +153 -0
  301. package/lib/module/ui/primitives/SearchableSingleSelectList.js.map +1 -0
  302. package/lib/module/ui/primitives/Select.js +205 -0
  303. package/lib/module/ui/primitives/Select.js.map +1 -0
  304. package/lib/module/ui/primitives/Spinner.js +21 -0
  305. package/lib/module/ui/primitives/Spinner.js.map +1 -0
  306. package/lib/module/ui/primitives/index.js +14 -0
  307. package/lib/module/ui/primitives/index.js.map +1 -0
  308. package/lib/module/ui/primitives/searchableSingleSelectFilter.js +27 -0
  309. package/lib/module/ui/primitives/searchableSingleSelectFilter.js.map +1 -0
  310. package/lib/module/ui/theme/ThemeProvider.js +67 -0
  311. package/lib/module/ui/theme/ThemeProvider.js.map +1 -0
  312. package/lib/module/ui/theme/index.js +5 -0
  313. package/lib/module/ui/theme/index.js.map +1 -0
  314. package/lib/module/ui/theme/tokens.js +145 -0
  315. package/lib/module/ui/theme/tokens.js.map +1 -0
  316. package/lib/module/utils/EventEmitter.js +139 -0
  317. package/lib/module/utils/EventEmitter.js.map +1 -0
  318. package/lib/module/utils/base64.js +47 -0
  319. package/lib/module/utils/base64.js.map +1 -0
  320. package/lib/module/utils/deviceFingerprint.js +129 -0
  321. package/lib/module/utils/deviceFingerprint.js.map +1 -0
  322. package/lib/module/utils/documentTypeOptions.js +31 -0
  323. package/lib/module/utils/documentTypeOptions.js.map +1 -0
  324. package/lib/module/utils/googleMapsPreflight.js +84 -0
  325. package/lib/module/utils/googleMapsPreflight.js.map +1 -0
  326. package/lib/module/utils/hmac.js +53 -0
  327. package/lib/module/utils/hmac.js.map +1 -0
  328. package/lib/module/utils/iso3166Countries.js +92 -0
  329. package/lib/module/utils/iso3166Countries.js.map +1 -0
  330. package/lib/module/utils/jpegFromUri.js +40 -0
  331. package/lib/module/utils/jpegFromUri.js.map +1 -0
  332. package/lib/module/utils/keepAwake.js +53 -0
  333. package/lib/module/utils/keepAwake.js.map +1 -0
  334. package/lib/module/utils/log.js +37 -0
  335. package/lib/module/utils/log.js.map +1 -0
  336. package/lib/module/utils/osGeocoder.js +65 -0
  337. package/lib/module/utils/osGeocoder.js.map +1 -0
  338. package/lib/module/utils/parseGoogleAddressComponents.js +69 -0
  339. package/lib/module/utils/parseGoogleAddressComponents.js.map +1 -0
  340. package/lib/module/utils/personNameNormalize.js +20 -0
  341. package/lib/module/utils/personNameNormalize.js.map +1 -0
  342. package/lib/module/utils/sdkError.js +29 -0
  343. package/lib/module/utils/sdkError.js.map +1 -0
  344. package/lib/module/utils/sdkVersion.js +9 -0
  345. package/lib/module/utils/sdkVersion.js.map +1 -0
  346. package/lib/module/utils/stepConfig.js +59 -0
  347. package/lib/module/utils/stepConfig.js.map +1 -0
  348. package/lib/module/utils/taxInfoConfig.js +15 -0
  349. package/lib/module/utils/taxInfoConfig.js.map +1 -0
  350. package/lib/module/utils/useSafeAreaInsets.js +37 -0
  351. package/lib/module/utils/useSafeAreaInsets.js.map +1 -0
  352. package/lib/module/utils/velionExtra.js +44 -0
  353. package/lib/module/utils/velionExtra.js.map +1 -0
  354. package/lib/typescript/camera/AddressSearchBar.d.ts +37 -0
  355. package/lib/typescript/camera/AddressSearchBar.d.ts.map +1 -0
  356. package/lib/typescript/camera/DocumentCapture.d.ts +34 -0
  357. package/lib/typescript/camera/DocumentCapture.d.ts.map +1 -0
  358. package/lib/typescript/camera/LivenessCamera.d.ts +67 -0
  359. package/lib/typescript/camera/LivenessCamera.d.ts.map +1 -0
  360. package/lib/typescript/camera/MapAddressPicker.d.ts +57 -0
  361. package/lib/typescript/camera/MapAddressPicker.d.ts.map +1 -0
  362. package/lib/typescript/core/VelionOnboarding.d.ts +169 -0
  363. package/lib/typescript/core/VelionOnboarding.d.ts.map +1 -0
  364. package/lib/typescript/core/retryStepCopy.d.ts +27 -0
  365. package/lib/typescript/core/retryStepCopy.d.ts.map +1 -0
  366. package/lib/typescript/core/routingCommands.d.ts +39 -0
  367. package/lib/typescript/core/routingCommands.d.ts.map +1 -0
  368. package/lib/typescript/core/sessionDeclinedCopy.d.ts +16 -0
  369. package/lib/typescript/core/sessionDeclinedCopy.d.ts.map +1 -0
  370. package/lib/typescript/core/sessionStateMapper.d.ts +52 -0
  371. package/lib/typescript/core/sessionStateMapper.d.ts.map +1 -0
  372. package/lib/typescript/core/sseReasonMessages.d.ts +20 -0
  373. package/lib/typescript/core/sseReasonMessages.d.ts.map +1 -0
  374. package/lib/typescript/i18n/index.d.ts +13 -0
  375. package/lib/typescript/i18n/index.d.ts.map +1 -0
  376. package/lib/typescript/i18n/strings/en.d.ts +3 -0
  377. package/lib/typescript/i18n/strings/en.d.ts.map +1 -0
  378. package/lib/typescript/i18n/strings/es.d.ts +297 -0
  379. package/lib/typescript/i18n/strings/es.d.ts.map +1 -0
  380. package/lib/typescript/index.d.ts +26 -0
  381. package/lib/typescript/index.d.ts.map +1 -0
  382. package/lib/typescript/steps/AddressInfoStep.d.ts +26 -0
  383. package/lib/typescript/steps/AddressInfoStep.d.ts.map +1 -0
  384. package/lib/typescript/steps/DocumentsOcrStep.d.ts +26 -0
  385. package/lib/typescript/steps/DocumentsOcrStep.d.ts.map +1 -0
  386. package/lib/typescript/steps/EconomicActivityStep.d.ts +29 -0
  387. package/lib/typescript/steps/EconomicActivityStep.d.ts.map +1 -0
  388. package/lib/typescript/steps/EmailContactStep.d.ts +15 -0
  389. package/lib/typescript/steps/EmailContactStep.d.ts.map +1 -0
  390. package/lib/typescript/steps/EmailOtpStep.d.ts +21 -0
  391. package/lib/typescript/steps/EmailOtpStep.d.ts.map +1 -0
  392. package/lib/typescript/steps/FaceMatchStep.d.ts +27 -0
  393. package/lib/typescript/steps/FaceMatchStep.d.ts.map +1 -0
  394. package/lib/typescript/steps/FingerprintStep.d.ts +25 -0
  395. package/lib/typescript/steps/FingerprintStep.d.ts.map +1 -0
  396. package/lib/typescript/steps/HumanBasicInfoStep.d.ts +25 -0
  397. package/lib/typescript/steps/HumanBasicInfoStep.d.ts.map +1 -0
  398. package/lib/typescript/steps/HumanExtendedInfoStep.d.ts +23 -0
  399. package/lib/typescript/steps/HumanExtendedInfoStep.d.ts.map +1 -0
  400. package/lib/typescript/steps/LegalBasicInfoStep.d.ts +17 -0
  401. package/lib/typescript/steps/LegalBasicInfoStep.d.ts.map +1 -0
  402. package/lib/typescript/steps/LegalExtendedInfoStep.d.ts +17 -0
  403. package/lib/typescript/steps/LegalExtendedInfoStep.d.ts.map +1 -0
  404. package/lib/typescript/steps/LivenessMatchStep.d.ts +26 -0
  405. package/lib/typescript/steps/LivenessMatchStep.d.ts.map +1 -0
  406. package/lib/typescript/steps/PhoneContactStep.d.ts +15 -0
  407. package/lib/typescript/steps/PhoneContactStep.d.ts.map +1 -0
  408. package/lib/typescript/steps/PhoneOtpStep.d.ts +19 -0
  409. package/lib/typescript/steps/PhoneOtpStep.d.ts.map +1 -0
  410. package/lib/typescript/steps/SwornDeclarationStep.d.ts +20 -0
  411. package/lib/typescript/steps/SwornDeclarationStep.d.ts.map +1 -0
  412. package/lib/typescript/steps/TaxInfoStep.d.ts +19 -0
  413. package/lib/typescript/steps/TaxInfoStep.d.ts.map +1 -0
  414. package/lib/typescript/steps/TermsAndConditionsStep.d.ts +21 -0
  415. package/lib/typescript/steps/TermsAndConditionsStep.d.ts.map +1 -0
  416. package/lib/typescript/steps/_shared.d.ts +22 -0
  417. package/lib/typescript/steps/_shared.d.ts.map +1 -0
  418. package/lib/typescript/steps/types.d.ts +89 -0
  419. package/lib/typescript/steps/types.d.ts.map +1 -0
  420. package/lib/typescript/transport/api.d.ts +35 -0
  421. package/lib/typescript/transport/api.d.ts.map +1 -0
  422. package/lib/typescript/transport/irisWebSocket.d.ts +72 -0
  423. package/lib/typescript/transport/irisWebSocket.d.ts.map +1 -0
  424. package/lib/typescript/transport/secureUrl.d.ts +14 -0
  425. package/lib/typescript/transport/secureUrl.d.ts.map +1 -0
  426. package/lib/typescript/transport/sse.d.ts +54 -0
  427. package/lib/typescript/transport/sse.d.ts.map +1 -0
  428. package/lib/typescript/types/index.d.ts +1219 -0
  429. package/lib/typescript/types/index.d.ts.map +1 -0
  430. package/lib/typescript/ui/MapFallbackBoundary.d.ts +28 -0
  431. package/lib/typescript/ui/MapFallbackBoundary.d.ts.map +1 -0
  432. package/lib/typescript/ui/StepShell.d.ts +29 -0
  433. package/lib/typescript/ui/StepShell.d.ts.map +1 -0
  434. package/lib/typescript/ui/VelionOnboardingScreen.d.ts +26 -0
  435. package/lib/typescript/ui/VelionOnboardingScreen.d.ts.map +1 -0
  436. package/lib/typescript/ui/forms/index.d.ts +3 -0
  437. package/lib/typescript/ui/forms/index.d.ts.map +1 -0
  438. package/lib/typescript/ui/forms/useInlineValidation.d.ts +30 -0
  439. package/lib/typescript/ui/forms/useInlineValidation.d.ts.map +1 -0
  440. package/lib/typescript/ui/forms/validators.d.ts +11 -0
  441. package/lib/typescript/ui/forms/validators.d.ts.map +1 -0
  442. package/lib/typescript/ui/icons/HomeHeartIcon.d.ts +14 -0
  443. package/lib/typescript/ui/icons/HomeHeartIcon.d.ts.map +1 -0
  444. package/lib/typescript/ui/icons/StepIcon.d.ts +26 -0
  445. package/lib/typescript/ui/icons/StepIcon.d.ts.map +1 -0
  446. package/lib/typescript/ui/overlays/AnalyzingOverlay.d.ts +24 -0
  447. package/lib/typescript/ui/overlays/AnalyzingOverlay.d.ts.map +1 -0
  448. package/lib/typescript/ui/overlays/LoadingOverlay.d.ts +19 -0
  449. package/lib/typescript/ui/overlays/LoadingOverlay.d.ts.map +1 -0
  450. package/lib/typescript/ui/overlays/ProgressBar.d.ts +32 -0
  451. package/lib/typescript/ui/overlays/ProgressBar.d.ts.map +1 -0
  452. package/lib/typescript/ui/overlays/RetryDialog.d.ts +17 -0
  453. package/lib/typescript/ui/overlays/RetryDialog.d.ts.map +1 -0
  454. package/lib/typescript/ui/overlays/index.d.ts +4 -0
  455. package/lib/typescript/ui/overlays/index.d.ts.map +1 -0
  456. package/lib/typescript/ui/primitives/BackButton.d.ts +20 -0
  457. package/lib/typescript/ui/primitives/BackButton.d.ts.map +1 -0
  458. package/lib/typescript/ui/primitives/Banner.d.ts +11 -0
  459. package/lib/typescript/ui/primitives/Banner.d.ts.map +1 -0
  460. package/lib/typescript/ui/primitives/Button.d.ts +27 -0
  461. package/lib/typescript/ui/primitives/Button.d.ts.map +1 -0
  462. package/lib/typescript/ui/primitives/Card.d.ts +10 -0
  463. package/lib/typescript/ui/primitives/Card.d.ts.map +1 -0
  464. package/lib/typescript/ui/primitives/Checkbox.d.ts +25 -0
  465. package/lib/typescript/ui/primitives/Checkbox.d.ts.map +1 -0
  466. package/lib/typescript/ui/primitives/CountrySelect.d.ts +31 -0
  467. package/lib/typescript/ui/primitives/CountrySelect.d.ts.map +1 -0
  468. package/lib/typescript/ui/primitives/DatePicker.d.ts +42 -0
  469. package/lib/typescript/ui/primitives/DatePicker.d.ts.map +1 -0
  470. package/lib/typescript/ui/primitives/Input.d.ts +17 -0
  471. package/lib/typescript/ui/primitives/Input.d.ts.map +1 -0
  472. package/lib/typescript/ui/primitives/SearchableSingleSelectList.d.ts +33 -0
  473. package/lib/typescript/ui/primitives/SearchableSingleSelectList.d.ts.map +1 -0
  474. package/lib/typescript/ui/primitives/Select.d.ts +26 -0
  475. package/lib/typescript/ui/primitives/Select.d.ts.map +1 -0
  476. package/lib/typescript/ui/primitives/Spinner.d.ts +10 -0
  477. package/lib/typescript/ui/primitives/Spinner.d.ts.map +1 -0
  478. package/lib/typescript/ui/primitives/index.d.ts +12 -0
  479. package/lib/typescript/ui/primitives/index.d.ts.map +1 -0
  480. package/lib/typescript/ui/primitives/searchableSingleSelectFilter.d.ts +25 -0
  481. package/lib/typescript/ui/primitives/searchableSingleSelectFilter.d.ts.map +1 -0
  482. package/lib/typescript/ui/theme/ThemeProvider.d.ts +23 -0
  483. package/lib/typescript/ui/theme/ThemeProvider.d.ts.map +1 -0
  484. package/lib/typescript/ui/theme/index.d.ts +3 -0
  485. package/lib/typescript/ui/theme/index.d.ts.map +1 -0
  486. package/lib/typescript/ui/theme/tokens.d.ts +42 -0
  487. package/lib/typescript/ui/theme/tokens.d.ts.map +1 -0
  488. package/lib/typescript/utils/EventEmitter.d.ts +98 -0
  489. package/lib/typescript/utils/EventEmitter.d.ts.map +1 -0
  490. package/lib/typescript/utils/base64.d.ts +19 -0
  491. package/lib/typescript/utils/base64.d.ts.map +1 -0
  492. package/lib/typescript/utils/deviceFingerprint.d.ts +42 -0
  493. package/lib/typescript/utils/deviceFingerprint.d.ts.map +1 -0
  494. package/lib/typescript/utils/documentTypeOptions.d.ts +13 -0
  495. package/lib/typescript/utils/documentTypeOptions.d.ts.map +1 -0
  496. package/lib/typescript/utils/googleMapsPreflight.d.ts +52 -0
  497. package/lib/typescript/utils/googleMapsPreflight.d.ts.map +1 -0
  498. package/lib/typescript/utils/hmac.d.ts +39 -0
  499. package/lib/typescript/utils/hmac.d.ts.map +1 -0
  500. package/lib/typescript/utils/iso3166Countries.d.ts +27 -0
  501. package/lib/typescript/utils/iso3166Countries.d.ts.map +1 -0
  502. package/lib/typescript/utils/jpegFromUri.d.ts +29 -0
  503. package/lib/typescript/utils/jpegFromUri.d.ts.map +1 -0
  504. package/lib/typescript/utils/keepAwake.d.ts +16 -0
  505. package/lib/typescript/utils/keepAwake.d.ts.map +1 -0
  506. package/lib/typescript/utils/log.d.ts +18 -0
  507. package/lib/typescript/utils/log.d.ts.map +1 -0
  508. package/lib/typescript/utils/osGeocoder.d.ts +38 -0
  509. package/lib/typescript/utils/osGeocoder.d.ts.map +1 -0
  510. package/lib/typescript/utils/parseGoogleAddressComponents.d.ts +43 -0
  511. package/lib/typescript/utils/parseGoogleAddressComponents.d.ts.map +1 -0
  512. package/lib/typescript/utils/personNameNormalize.d.ts +10 -0
  513. package/lib/typescript/utils/personNameNormalize.d.ts.map +1 -0
  514. package/lib/typescript/utils/sdkError.d.ts +14 -0
  515. package/lib/typescript/utils/sdkError.d.ts.map +1 -0
  516. package/lib/typescript/utils/sdkVersion.d.ts +7 -0
  517. package/lib/typescript/utils/sdkVersion.d.ts.map +1 -0
  518. package/lib/typescript/utils/stepConfig.d.ts +8 -0
  519. package/lib/typescript/utils/stepConfig.d.ts.map +1 -0
  520. package/lib/typescript/utils/taxInfoConfig.d.ts +7 -0
  521. package/lib/typescript/utils/taxInfoConfig.d.ts.map +1 -0
  522. package/lib/typescript/utils/useSafeAreaInsets.d.ts +26 -0
  523. package/lib/typescript/utils/useSafeAreaInsets.d.ts.map +1 -0
  524. package/lib/typescript/utils/velionExtra.d.ts +24 -0
  525. package/lib/typescript/utils/velionExtra.d.ts.map +1 -0
  526. package/package.json +107 -0
  527. package/src/camera/AddressSearchBar.tsx +363 -0
  528. package/src/camera/DocumentCapture.tsx +514 -0
  529. package/src/camera/LivenessCamera.tsx +706 -0
  530. package/src/camera/MapAddressPicker.tsx +391 -0
  531. package/src/core/VelionOnboarding.ts +1291 -0
  532. package/src/core/retryStepCopy.ts +54 -0
  533. package/src/core/routingCommands.ts +63 -0
  534. package/src/core/sessionDeclinedCopy.ts +76 -0
  535. package/src/core/sessionStateMapper.ts +232 -0
  536. package/src/core/sseReasonMessages.ts +531 -0
  537. package/src/data/iso3166Alpha2Codes.json +1 -0
  538. package/src/data/iso3166CountryNames.json +251 -0
  539. package/src/i18n/index.ts +26 -0
  540. package/src/i18n/strings/en.ts +335 -0
  541. package/src/i18n/strings/es.ts +337 -0
  542. package/src/index.ts +146 -0
  543. package/src/steps/AddressInfoStep.tsx +744 -0
  544. package/src/steps/DocumentsOcrStep.tsx +481 -0
  545. package/src/steps/EconomicActivityStep.tsx +230 -0
  546. package/src/steps/EmailContactStep.tsx +165 -0
  547. package/src/steps/EmailOtpStep.tsx +256 -0
  548. package/src/steps/FaceMatchStep.tsx +176 -0
  549. package/src/steps/FingerprintStep.tsx +99 -0
  550. package/src/steps/HumanBasicInfoStep.tsx +286 -0
  551. package/src/steps/HumanExtendedInfoStep.tsx +362 -0
  552. package/src/steps/LegalBasicInfoStep.tsx +214 -0
  553. package/src/steps/LegalExtendedInfoStep.tsx +184 -0
  554. package/src/steps/LivenessMatchStep.tsx +1351 -0
  555. package/src/steps/PhoneContactStep.tsx +166 -0
  556. package/src/steps/PhoneOtpStep.tsx +255 -0
  557. package/src/steps/SwornDeclarationStep.tsx +237 -0
  558. package/src/steps/TaxInfoStep.tsx +288 -0
  559. package/src/steps/TermsAndConditionsStep.tsx +269 -0
  560. package/src/steps/_shared.ts +69 -0
  561. package/src/steps/types.ts +93 -0
  562. package/src/transport/api.ts +257 -0
  563. package/src/transport/irisWebSocket.ts +186 -0
  564. package/src/transport/secureUrl.ts +47 -0
  565. package/src/transport/sse.ts +310 -0
  566. package/src/types/index.ts +1421 -0
  567. package/src/ui/MapFallbackBoundary.tsx +46 -0
  568. package/src/ui/StepShell.tsx +273 -0
  569. package/src/ui/VelionOnboardingScreen.tsx +297 -0
  570. package/src/ui/forms/index.ts +12 -0
  571. package/src/ui/forms/useInlineValidation.ts +115 -0
  572. package/src/ui/forms/validators.ts +29 -0
  573. package/src/ui/icons/HomeHeartIcon.tsx +34 -0
  574. package/src/ui/icons/StepIcon.tsx +78 -0
  575. package/src/ui/overlays/AnalyzingOverlay.tsx +323 -0
  576. package/src/ui/overlays/LoadingOverlay.tsx +115 -0
  577. package/src/ui/overlays/ProgressBar.tsx +106 -0
  578. package/src/ui/overlays/RetryDialog.tsx +128 -0
  579. package/src/ui/overlays/index.ts +3 -0
  580. package/src/ui/primitives/BackButton.tsx +65 -0
  581. package/src/ui/primitives/Banner.tsx +81 -0
  582. package/src/ui/primitives/Button.tsx +164 -0
  583. package/src/ui/primitives/Card.tsx +55 -0
  584. package/src/ui/primitives/Checkbox.tsx +153 -0
  585. package/src/ui/primitives/CountrySelect.tsx +356 -0
  586. package/src/ui/primitives/DatePicker.tsx +266 -0
  587. package/src/ui/primitives/Input.tsx +110 -0
  588. package/src/ui/primitives/SearchableSingleSelectList.tsx +195 -0
  589. package/src/ui/primitives/Select.tsx +259 -0
  590. package/src/ui/primitives/Spinner.tsx +17 -0
  591. package/src/ui/primitives/index.ts +16 -0
  592. package/src/ui/primitives/searchableSingleSelectFilter.ts +38 -0
  593. package/src/ui/theme/ThemeProvider.tsx +102 -0
  594. package/src/ui/theme/index.ts +17 -0
  595. package/src/ui/theme/tokens.ts +159 -0
  596. package/src/utils/EventEmitter.ts +155 -0
  597. package/src/utils/base64.ts +44 -0
  598. package/src/utils/deviceFingerprint.ts +184 -0
  599. package/src/utils/documentTypeOptions.ts +31 -0
  600. package/src/utils/googleMapsPreflight.ts +89 -0
  601. package/src/utils/hmac.ts +61 -0
  602. package/src/utils/iso3166Countries.ts +111 -0
  603. package/src/utils/jpegFromUri.ts +42 -0
  604. package/src/utils/keepAwake.ts +62 -0
  605. package/src/utils/log.ts +37 -0
  606. package/src/utils/osGeocoder.ts +75 -0
  607. package/src/utils/parseGoogleAddressComponents.ts +123 -0
  608. package/src/utils/personNameNormalize.ts +17 -0
  609. package/src/utils/sdkError.ts +40 -0
  610. package/src/utils/sdkVersion.ts +6 -0
  611. package/src/utils/stepConfig.ts +75 -0
  612. package/src/utils/taxInfoConfig.ts +14 -0
  613. package/src/utils/useSafeAreaInsets.ts +37 -0
  614. package/src/utils/velionExtra.ts +46 -0
@@ -0,0 +1,1351 @@
1
+ /**
2
+ * LIVENESS_MATCH — Iris-driven active liveness over WebSocket.
3
+ *
4
+ * Flow:
5
+ * 1. POST /liveness-init → { liveness_session_id, websocket_url, expires_at,
6
+ * challenges, connection_token, frame_integrity_key_base64 }.
7
+ * 2. Optionally import the HMAC key for frame integrity.
8
+ * 3. Open vision-camera (front), connect WS with ?token & ?lang.
9
+ * 4. SESSION_READY → start frame capture loop (interval-driven), watchdog 25s.
10
+ * 5. Process CHALLENGE / CHALLENGE_PROGRESS / CHALLENGE_COMPLETE / WARNING /
11
+ * ERROR / SESSION_COMPLETE.
12
+ * 6. Terminal WARNING (SPOOF_RISK_HIGH, …) → in-flow retry dialog (re-init
13
+ * + fresh WS) without bailing the whole flow.
14
+ * 7. SESSION_COMPLETE → POST /liveness-verify → resolve the step.
15
+ */
16
+
17
+ import { useCallback, useEffect, useRef, useState } from 'react';
18
+ import { ScrollView, StyleSheet, Text, View } from 'react-native';
19
+ // `expo-file-system` v19's `File` class wraps a `file://` path with a Blob-
20
+ // compatible API (`arrayBuffer`, `size`, `delete`). We read the recorded mp4
21
+ // to bytes in JS and PUT them with the global `fetch`. For the typical
22
+ // 1–5 MB session video this is well within the bridge budget; if the
23
+ // recorded files grow significantly we can switch to a streaming uploader
24
+ // without changing the call sites.
25
+ import { File as FsFile } from 'expo-file-system';
26
+ import * as ImageManipulator from 'expo-image-manipulator';
27
+ import {
28
+ SdkErrorCode,
29
+ type LivenessSessionResponse,
30
+ type LivenessVerifyVideoMeta,
31
+ type LivenessVideoRef,
32
+ type SdkError,
33
+ type VideoUpload,
34
+ } from '../types';
35
+ import { Banner } from '../ui/primitives/Banner';
36
+ import { Button } from '../ui/primitives/Button';
37
+ import { AnalyzingOverlay } from '../ui/overlays/AnalyzingOverlay';
38
+ import { RetryDialog } from '../ui/overlays/RetryDialog';
39
+ import { StepShell } from '../ui/StepShell';
40
+ import { StepIcon } from '../ui/icons/StepIcon';
41
+ import { mixHex, useTheme } from '../ui/theme';
42
+ import { getStrings } from '../i18n';
43
+ import { log } from '../utils/log';
44
+ import { readJpegFromUri } from '../utils/jpegFromUri';
45
+ import {
46
+ buildSignedFrameEnvelope,
47
+ importHmacKey,
48
+ type HmacKey,
49
+ } from '../utils/hmac';
50
+ import {
51
+ TERMINAL_WARNING_CODES,
52
+ openIrisWebSocket,
53
+ type IrisChallenge,
54
+ type IrisConnection,
55
+ type IrisServerMessage,
56
+ } from '../transport/irisWebSocket';
57
+ import {
58
+ LivenessCamera,
59
+ type LivenessCameraHandle,
60
+ type LivenessOvalCue,
61
+ } from '../camera/LivenessCamera';
62
+ import type { VideoFile } from 'react-native-vision-camera';
63
+ import type { ApiCaller } from '../transport/api';
64
+ import type { StepDeps, StepModule } from './types';
65
+
66
+ // Capture loop defaults tuned for the Iris orchestrator's frame cadence.
67
+ const FRAME_MS_DEFAULT = 350;
68
+ const FRAME_MS_TURN = 220;
69
+ const PROGRESS_WATCHDOG_MS = 25_000;
70
+ /**
71
+ * Hard ceiling for the POST /liveness-verify call that runs after
72
+ * SESSION_COMPLETE. The progress watchdog is already off by then, so an
73
+ * unbounded fetch (the dev network shows recurring HTTP/2 stream resets)
74
+ * would strand the user on the analyzing overlay forever.
75
+ */
76
+ const LIVENESS_VERIFY_TIMEOUT_MS = 20_000;
77
+ const FRAME_MAX_LONG_EDGE = 720;
78
+ const FRAME_QUALITY = 0.55;
79
+ /**
80
+ * Hard ceiling for the video upload PUT to GCS that runs between SESSION_COMPLETE
81
+ * and POST /liveness-verify. Long enough for a 5 MB upload on a slow mobile link
82
+ * but short enough that a stalled connection can't keep the user on the
83
+ * analyzing overlay indefinitely. On timeout we fall back to verify-without-body.
84
+ */
85
+ /**
86
+ * Hard ceiling for the video upload PUT to GCS that runs between
87
+ * SESSION_COMPLETE and POST /liveness-verify. The signed URL TTL is 10 min,
88
+ * so 60 s leaves comfortable headroom for a typical 1–5 MB session video
89
+ * over a slow mobile uplink. On timeout we fall back to verify-without-body.
90
+ */
91
+ const VIDEO_UPLOAD_TIMEOUT_MS = 60_000;
92
+ // Upper bound for vision-camera to deliver `onRecordingFinished` after
93
+ // `stopRecording()` resolves. Observed ~50–200 ms in practice; we set the
94
+ // cap generously so a slow flush on older Androids doesn't strand the
95
+ // failure path waiting for a signal that's just running late.
96
+ const RECORDING_FINISH_TIMEOUT_MS = 3_000;
97
+ const VIDEO_CONTENT_TYPE = 'video/mp4';
98
+
99
+ /** Returns the first 80 chars of a URL — enough to spot the bucket without dumping the V4 signature. */
100
+ function truncateUrl(url: string): string {
101
+ return url.length <= 80 ? url : `${url.slice(0, 80)}…`;
102
+ }
103
+
104
+ export class LivenessMatchStep implements StepModule {
105
+ private resolveStep!: () => void;
106
+ private rejectStep!: (err: SdkError) => void;
107
+ private destroyed = false;
108
+
109
+ constructor(private readonly deps: StepDeps) {}
110
+
111
+ run(): Promise<void> {
112
+ return new Promise((resolve, reject) => {
113
+ this.resolveStep = resolve;
114
+ this.rejectStep = reject;
115
+ this.deps.ui.setNode(
116
+ <LivenessMatchView
117
+ api={this.deps.api}
118
+ sessionId={this.deps.sessionId}
119
+ locale={this.deps.locale}
120
+ calibrationLabel={this.deps.livenessCalibrationLabel}
121
+ showIntro
122
+ showBackButton
123
+ onVideoUploaded={this.deps.onLivenessVideoUploaded}
124
+ onComplete={() => {
125
+ if (this.destroyed) return;
126
+ this.deps.ui.setNode(null);
127
+ this.resolveStep();
128
+ }}
129
+ onCancel={(err) => {
130
+ if (this.destroyed) return;
131
+ this.deps.ui.setNode(null);
132
+ this.rejectStep(err);
133
+ }}
134
+ />,
135
+ );
136
+ });
137
+ }
138
+
139
+ destroy(): void {
140
+ this.destroyed = true;
141
+ this.deps.ui.setNode(null);
142
+ }
143
+ }
144
+
145
+ interface ViewProps {
146
+ api: ApiCaller;
147
+ sessionId: string;
148
+ locale: string;
149
+ /** Optional Iris calibration label forwarded to /liveness-init body. */
150
+ calibrationLabel?: string | undefined;
151
+ showIntro: boolean;
152
+ showBackButton: boolean;
153
+ /** Best-effort: fires only on a successful video upload (HTTP 200 from GCS). */
154
+ onVideoUploaded?: ((ref: LivenessVideoRef) => void) | undefined;
155
+ onComplete: () => void;
156
+ onCancel: (err: SdkError) => void;
157
+ }
158
+
159
+ type Phase = 'intro' | 'capturing' | 'finalizing';
160
+
161
+ function LivenessMatchView({
162
+ api,
163
+ sessionId,
164
+ locale,
165
+ calibrationLabel,
166
+ showIntro,
167
+ showBackButton,
168
+ onVideoUploaded,
169
+ onComplete,
170
+ onCancel,
171
+ }: ViewProps) {
172
+ const t = getStrings(locale);
173
+ const theme = useTheme();
174
+ const cameraRef = useRef<LivenessCameraHandle>(null);
175
+
176
+ const [phase, setPhase] = useState<Phase>(showIntro ? 'intro' : 'capturing');
177
+ const [statusText, setStatusText] = useState<string | null>(null);
178
+ const [challengeText, setChallengeText] = useState<string | null>(null);
179
+ const [ovalCue, setOvalCue] = useState<LivenessOvalCue>('NEUTRAL');
180
+ const [toast, setToast] = useState<
181
+ | {
182
+ kind: 'success' | 'warning';
183
+ message: string;
184
+ }
185
+ | null
186
+ >(null);
187
+ const [progress, setProgress] = useState<number | null>(null);
188
+ const [retry, setRetry] = useState<{ message: string; code: string } | null>(null);
189
+ const [bannerError, setBannerError] = useState<string | null>(null);
190
+
191
+ // Long-lived state that the capture loop / WS handlers need without
192
+ // triggering re-renders: kept in refs.
193
+ const wsRef = useRef<IrisConnection | null>(null);
194
+ const hmacRef = useRef<HmacKey | null>(null);
195
+ const livenessSessionIdRef = useRef<string | null>(null);
196
+ const currentChallengeRef = useRef<IrisChallenge | null>(null);
197
+ // Tracks the position of the active challenge inside the session sequence
198
+ // so we can recognise the LAST challenge completing and switch to the
199
+ // "Analyzing" overlay immediately, instead of letting the user stare at
200
+ // the camera with the last instruction frozen on screen for the seconds
201
+ // it takes the worker to drain its queue and the orchestrator to emit
202
+ // SESSION_COMPLETE.
203
+ const lastChallengeMetaRef = useRef<{ index: number; total: number } | null>(
204
+ null,
205
+ );
206
+ const frameMsRef = useRef<number>(FRAME_MS_DEFAULT);
207
+ const captureTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
208
+ const inFlightRef = useRef(false);
209
+ const framesSentRef = useRef(0);
210
+ const watchdogRef = useRef<ReturnType<typeof setTimeout> | null>(null);
211
+ const finalizingRef = useRef(false);
212
+ const toastTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
213
+ // Tracks the toast currently on screen so we can extend its visibility when
214
+ // the same message arrives again (instead of dismount/remount, which made
215
+ // warnings flash in <2s and the user couldn't read them).
216
+ const activeToastRef = useRef<{ kind: 'success' | 'warning'; message: string } | null>(null);
217
+
218
+ // ── Video recording state (OSDKR-4) ─────────────────────────────────────
219
+ // `videoUploadRef` holds the signed URL returned by /liveness-init when the
220
+ // backend enabled video capture for this session. `null` → skip recording.
221
+ const videoUploadRef = useRef<VideoUpload | null>(null);
222
+ // Current state of the video pipeline. Best-effort: any value other than
223
+ // `'uploaded'` ends up calling /liveness-verify WITHOUT a body — liveness
224
+ // still completes normally.
225
+ type VideoOutcome = 'none' | 'recording' | 'failed' | 'uploaded';
226
+ const videoOutcomeRef = useRef<VideoOutcome>('none');
227
+ // Filled in when the GCS PUT returns 200; consumed by the verify call.
228
+ const videoMetaRef = useRef<LivenessVerifyVideoMeta | null>(null);
229
+ // Resolves when the upload (success or failure path) is fully settled. The
230
+ // SESSION_COMPLETE handler awaits this with a bounded timeout before calling
231
+ // /liveness-verify so the metadata, if any, makes it into the body.
232
+ const videoUploadPromiseRef = useRef<Promise<void> | null>(null);
233
+ // Resolves as soon as vision-camera fires `onRecordingFinished` (i.e. when
234
+ // the mp4 file is fully written and `uploadRecordedVideo` has been kicked
235
+ // off — fetch is in flight but not yet complete). `failWith` awaits this with
236
+ // a short timeout so the upload's underlying fetch is *started* before the
237
+ // step is torn down. After the unmount the fetch closure keeps its own refs
238
+ // alive and the PUT to GCS completes in the background.
239
+ const videoRecordingFinishedPromiseRef = useRef<Promise<void> | null>(null);
240
+ // Local file system path of the temp mp4. Tracked so the unmount cleanup
241
+ // can delete it if the user backs out before the upload finished.
242
+ const videoTempPathRef = useRef<string | null>(null);
243
+ // Cached so `failWith` / unmount can invoke the callback with the prop
244
+ // captured at start, even if the host re-renders.
245
+ const onVideoUploadedRef = useRef<typeof onVideoUploaded>(onVideoUploaded);
246
+ useEffect(() => {
247
+ onVideoUploadedRef.current = onVideoUploaded;
248
+ }, [onVideoUploaded]);
249
+
250
+ // Each toast stays on screen at least this long. The orchestrator can spam
251
+ // WARNINGs (POSITIONING_REQUIRED, SPOOF_RISK_HIGH, …) several times per
252
+ // second; without a floor the user literally cannot read them.
253
+ const TOAST_MIN_DURATION_MS = 3200;
254
+
255
+ const showToast = useCallback(
256
+ (kind: 'success' | 'warning', message: string) => {
257
+ const active = activeToastRef.current;
258
+ if (active && active.kind === kind && active.message === message) {
259
+ // Identical toast already visible — just refresh the timer so it
260
+ // stays up while warnings keep arriving. Do NOT touch `setToast`:
261
+ // a new object would re-trigger the entry animation and flicker.
262
+ if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
263
+ toastTimerRef.current = setTimeout(() => {
264
+ setToast(null);
265
+ activeToastRef.current = null;
266
+ }, TOAST_MIN_DURATION_MS);
267
+ return;
268
+ }
269
+ // Different content: replace and guarantee the new toast its own
270
+ // minimum window.
271
+ activeToastRef.current = { kind, message };
272
+ setToast({ kind, message });
273
+ if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
274
+ toastTimerRef.current = setTimeout(() => {
275
+ setToast(null);
276
+ activeToastRef.current = null;
277
+ }, TOAST_MIN_DURATION_MS);
278
+ },
279
+ [],
280
+ );
281
+
282
+ const stopWatchdog = useCallback(() => {
283
+ if (watchdogRef.current) {
284
+ clearTimeout(watchdogRef.current);
285
+ watchdogRef.current = null;
286
+ }
287
+ }, []);
288
+
289
+ const stopCapture = useCallback(() => {
290
+ if (captureTimerRef.current) {
291
+ clearInterval(captureTimerRef.current);
292
+ captureTimerRef.current = null;
293
+ }
294
+ inFlightRef.current = false;
295
+ }, []);
296
+
297
+ // ── Video upload pipeline (OSDKR-4) ─────────────────────────────────────
298
+ // Everything below is best-effort: never throws into the caller; never
299
+ // blocks liveness completion. The worst case is `videoOutcomeRef = 'failed'`
300
+ // and verify being called without a body.
301
+ const deleteVideoTemp = useCallback((path: string | null) => {
302
+ if (!path) return;
303
+ try {
304
+ // `File.delete()` is synchronous in expo-file-system v19.
305
+ new FsFile(path).delete();
306
+ } catch {
307
+ // Best-effort cleanup; we can't do much if rm fails.
308
+ }
309
+ }, []);
310
+
311
+ const uploadRecordedVideo = useCallback(
312
+ async (video: VideoFile): Promise<void> => {
313
+ const target = videoUploadRef.current;
314
+ videoTempPathRef.current = video.path;
315
+ if (!target) {
316
+ log.warn('[Liveness] video upload skipped: no signed URL in init response');
317
+ videoOutcomeRef.current = 'failed';
318
+ deleteVideoTemp(video.path);
319
+ videoTempPathRef.current = null;
320
+ return;
321
+ }
322
+ const durationMs =
323
+ typeof video.duration === 'number' && isFinite(video.duration)
324
+ ? Math.round(video.duration * 1000)
325
+ : null;
326
+ let sizeBytes: number | null = null;
327
+ let file: FsFile | null = null;
328
+ try {
329
+ file = new FsFile(video.path);
330
+ sizeBytes = typeof file.size === 'number' ? file.size : null;
331
+ } catch (err) {
332
+ log.warn('[Liveness] could not stat video file before upload', err);
333
+ }
334
+ log.info('[Liveness] video upload starting', {
335
+ url: truncateUrl(target.upload_url),
336
+ method: target.method,
337
+ contentType: VIDEO_CONTENT_TYPE,
338
+ path: video.path,
339
+ sizeBytes,
340
+ durationMs,
341
+ });
342
+ const t0 = Date.now();
343
+ 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();
355
+ log.info('[Liveness] video upload body prepared', {
356
+ blobSize: nativeBlob.size,
357
+ blobType: nativeBlob.type,
358
+ });
359
+ const result = await fetch(target.upload_url, {
360
+ method: 'PUT',
361
+ headers: { 'Content-Type': VIDEO_CONTENT_TYPE },
362
+ body: nativeBlob,
363
+ });
364
+ const elapsedMs = Date.now() - t0;
365
+ if (result.ok) {
366
+ log.info('[Liveness] video upload ok', { status: result.status, elapsedMs, sizeBytes });
367
+ videoOutcomeRef.current = 'uploaded';
368
+ videoMetaRef.current = {
369
+ content_type: VIDEO_CONTENT_TYPE,
370
+ duration_ms: durationMs,
371
+ };
372
+ // Invoke the host callback BEFORE cleanup so the path stays valid
373
+ // for any synchronous host work (rare, but cheap to guarantee).
374
+ try {
375
+ onVideoUploadedRef.current?.({
376
+ upload_url: target.upload_url,
377
+ content_type: VIDEO_CONTENT_TYPE,
378
+ duration_ms: durationMs,
379
+ size_bytes: sizeBytes,
380
+ });
381
+ } catch (err) {
382
+ log.warn('[Liveness] onLivenessVideoUploaded threw', err);
383
+ }
384
+ } else {
385
+ // Try to extract the GCS error XML — its body tells us exactly which
386
+ // permission / signature param failed (otherwise we are blind).
387
+ let responseSnippet = '';
388
+ try {
389
+ responseSnippet = (await result.text()).slice(0, 400);
390
+ } catch {
391
+ /* body not readable; status alone is the signal */
392
+ }
393
+ log.warn('[Liveness] video upload non-200', {
394
+ status: result.status,
395
+ elapsedMs,
396
+ sizeBytes,
397
+ body: responseSnippet,
398
+ });
399
+ videoOutcomeRef.current = 'failed';
400
+ }
401
+ } catch (err) {
402
+ log.warn('[Liveness] video upload error', {
403
+ elapsedMs: Date.now() - t0,
404
+ sizeBytes,
405
+ err,
406
+ });
407
+ videoOutcomeRef.current = 'failed';
408
+ } finally {
409
+ deleteVideoTemp(video.path);
410
+ videoTempPathRef.current = null;
411
+ }
412
+ },
413
+ [deleteVideoTemp],
414
+ );
415
+
416
+ const startVideoRecordingIfEnabled = useCallback(() => {
417
+ if (!videoUploadRef.current) {
418
+ log.info('[Liveness] video skipped: no video_upload in liveness-init');
419
+ return;
420
+ }
421
+ const camera = cameraRef.current;
422
+ if (!camera) {
423
+ log.warn('[Liveness] video skipped: LivenessCamera ref not ready at SESSION_READY');
424
+ return;
425
+ }
426
+ log.info('[Liveness] video recording starting', {
427
+ uploadUrl: truncateUrl(videoUploadRef.current.upload_url),
428
+ expiresAt: videoUploadRef.current.expires_at,
429
+ });
430
+ // Pre-assign the upload promise BEFORE calling startRecording. vision-camera
431
+ // dispatches `onRecordingFinished` on a separate microtask from the
432
+ // `stopRecording()` resolution, so a "set the promise inside the callback"
433
+ // pattern races SESSION_COMPLETE — the verify POST fires before
434
+ // `uploadRecordedVideo` is even invoked, and the body ends up empty.
435
+ // The Deferred resolves once the recording's success/error path is fully
436
+ // settled (including the upload PUT and the cleanup).
437
+ let settle: () => void = () => {};
438
+ let settled = false;
439
+ videoUploadPromiseRef.current = new Promise<void>((resolve) => {
440
+ settle = () => {
441
+ if (settled) return;
442
+ settled = true;
443
+ resolve();
444
+ };
445
+ });
446
+ let signalRecordingFinished: () => void = () => {};
447
+ let recordingFinishedSettled = false;
448
+ videoRecordingFinishedPromiseRef.current = new Promise<void>((resolve) => {
449
+ signalRecordingFinished = () => {
450
+ if (recordingFinishedSettled) return;
451
+ recordingFinishedSettled = true;
452
+ resolve();
453
+ };
454
+ });
455
+ try {
456
+ camera.startVideoRecording({
457
+ onRecordingFinished: (video) => {
458
+ log.info('[Liveness] video recording finished', {
459
+ path: video.path,
460
+ durationSec: video.duration,
461
+ });
462
+ // Signal `failWith` (and anyone else waiting for the file to be
463
+ // ready) BEFORE awaiting the upload. The fetch closure keeps the
464
+ // upload alive past any unmount, so it's safe to let the component
465
+ // tear down once the recording-finished signal has fired.
466
+ uploadRecordedVideo(video).finally(() => {
467
+ settle();
468
+ });
469
+ signalRecordingFinished();
470
+ },
471
+ onRecordingError: (err) => {
472
+ log.warn('[Liveness] video recording error', err);
473
+ videoOutcomeRef.current = 'failed';
474
+ signalRecordingFinished();
475
+ settle();
476
+ },
477
+ });
478
+ log.info('[Liveness] video recording started');
479
+ videoOutcomeRef.current = 'recording';
480
+ } catch (err) {
481
+ log.warn('[Liveness] failed to start video recording', err);
482
+ videoOutcomeRef.current = 'failed';
483
+ // No callback will ever fire → unblock anyone awaiting either Deferred.
484
+ signalRecordingFinished();
485
+ settle();
486
+ }
487
+ }, [uploadRecordedVideo]);
488
+
489
+ const stopVideoRecordingIfActive = useCallback(async () => {
490
+ if (videoOutcomeRef.current !== 'recording') {
491
+ log.info('[Liveness] video stop skipped', { outcome: videoOutcomeRef.current });
492
+ return;
493
+ }
494
+ const camera = cameraRef.current;
495
+ if (!camera) {
496
+ log.warn('[Liveness] video stop skipped: LivenessCamera ref gone');
497
+ return;
498
+ }
499
+ log.info('[Liveness] video recording stopping');
500
+ try {
501
+ // Returns when vision-camera flushed the file; the upload Deferred
502
+ // (set in startVideoRecordingIfEnabled) is what actually tells us when
503
+ // the PUT + cleanup are done — the SESSION_COMPLETE handler awaits it.
504
+ await camera.stopVideoRecording();
505
+ log.info('[Liveness] video recording stop resolved (onRecordingFinished will follow)');
506
+ } catch (err) {
507
+ log.warn('[Liveness] failed to stop video recording', err);
508
+ videoOutcomeRef.current = 'failed';
509
+ }
510
+ }, []);
511
+
512
+ const failWith = useCallback(
513
+ (err: SdkError) => {
514
+ stopWatchdog();
515
+ stopCapture();
516
+ // OSDKR-4 requirement: the video must upload on EVERY outcome,
517
+ // including LIVENESS_FAILED, so back-office reviewers can audit
518
+ // what happened in declined sessions. To make that work we need
519
+ // `onRecordingFinished` to fire *before* the component unmounts —
520
+ // once the file is flushed and `uploadRecordedVideo` has kicked
521
+ // off, the fetch closure carries the upload through to completion
522
+ // on its own, no matter how quickly the UI is torn down.
523
+ //
524
+ // We don't wait for the GCS PUT to complete (that can take
525
+ // seconds and the user shouldn't sit on the error screen for it),
526
+ // just for the recording-finished signal.
527
+ const recordingWasActive = videoOutcomeRef.current === 'recording';
528
+ const finish = () => {
529
+ if (videoTempPathRef.current && !recordingWasActive) {
530
+ // Only delete the temp file when there was no recording in
531
+ // flight; otherwise `uploadRecordedVideo` is responsible for
532
+ // deleting it after the PUT settles.
533
+ const path = videoTempPathRef.current;
534
+ videoTempPathRef.current = null;
535
+ void deleteVideoTemp(path);
536
+ }
537
+ try {
538
+ wsRef.current?.close(1000, 'fail');
539
+ } catch {
540
+ /* ignore */
541
+ }
542
+ wsRef.current = null;
543
+ onCancel(err);
544
+ };
545
+ if (!recordingWasActive) {
546
+ finish();
547
+ return;
548
+ }
549
+ const finishedPromise = videoRecordingFinishedPromiseRef.current;
550
+ void (async () => {
551
+ await stopVideoRecordingIfActive();
552
+ if (finishedPromise) {
553
+ // Bound the wait so a misbehaving recorder can't strand the
554
+ // user on the camera screen forever. `RECORDING_FINISH_TIMEOUT_MS`
555
+ // is conservative — vision-camera typically lands the callback
556
+ // tens of milliseconds after stopRecording resolves.
557
+ let finishTimer: ReturnType<typeof setTimeout> | null = null;
558
+ const timeoutPromise = new Promise<void>((resolve) => {
559
+ finishTimer = setTimeout(() => {
560
+ log.warn(
561
+ '[Liveness] recording-finished signal timed out — proceeding to fail without ensuring the upload kicked off',
562
+ );
563
+ resolve();
564
+ }, RECORDING_FINISH_TIMEOUT_MS);
565
+ });
566
+ await Promise.race([finishedPromise, timeoutPromise]);
567
+ if (finishTimer) clearTimeout(finishTimer);
568
+ }
569
+ finish();
570
+ })();
571
+ },
572
+ [deleteVideoTemp, onCancel, stopCapture, stopVideoRecordingIfActive, stopWatchdog],
573
+ );
574
+
575
+ const captureAndSend = useCallback(async () => {
576
+ if (inFlightRef.current) return;
577
+ const ws = wsRef.current;
578
+ if (!ws || !ws.isOpen()) return;
579
+ inFlightRef.current = true;
580
+ 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;
620
+ } catch (err) {
621
+ log.warn('[Liveness] frame send failed', err);
622
+ } finally {
623
+ inFlightRef.current = false;
624
+ }
625
+ }, [sessionId]);
626
+
627
+ const startCaptureLoop = useCallback(
628
+ (ms: number) => {
629
+ stopCapture();
630
+ frameMsRef.current = ms;
631
+ captureTimerRef.current = setInterval(() => {
632
+ void captureAndSend();
633
+ }, ms);
634
+ },
635
+ [captureAndSend, stopCapture],
636
+ );
637
+
638
+ const adjustFps = useCallback(
639
+ (ms: number) => {
640
+ if (frameMsRef.current === ms) return;
641
+ if (captureTimerRef.current) {
642
+ startCaptureLoop(ms);
643
+ } else {
644
+ frameMsRef.current = ms;
645
+ }
646
+ },
647
+ [startCaptureLoop],
648
+ );
649
+
650
+ const challengeLabel = useCallback(
651
+ (id: IrisChallenge | null): string => {
652
+ if (!id) return '';
653
+ return t.liveness.challenge[id] ?? '';
654
+ },
655
+ [t.liveness.challenge],
656
+ );
657
+
658
+ const presentTerminalRetry = useCallback(
659
+ (code: string, message?: string) => {
660
+ stopCapture();
661
+ stopWatchdog();
662
+ try {
663
+ wsRef.current?.close(4001, 'terminal_warning_retry_pending');
664
+ } catch {
665
+ /* ignore */
666
+ }
667
+ wsRef.current = null;
668
+ setRetry({ code, message: message?.trim() || t.liveness.terminalRetryFallback });
669
+ },
670
+ [stopCapture, stopWatchdog, t.liveness.terminalRetryFallback],
671
+ );
672
+
673
+ const resetWatchdog = useCallback(() => {
674
+ stopWatchdog();
675
+ watchdogRef.current = setTimeout(() => {
676
+ log.warn('[Liveness] progress watchdog fired');
677
+ // The watchdog used to be a hard fail — onCancel → step rejects →
678
+ // orchestrator surfaces the error and exits the whole liveness step.
679
+ // That left the user with no in-flow recovery: they had to restart
680
+ // the entire onboarding. The Iris-side "no progress in N seconds" is
681
+ // usually a recoverable user-side issue (lighting, framing, not
682
+ // looking at the camera), so we treat it the same way as a terminal
683
+ // WARNING: tear down the WS, show the retry dialog, and let the user
684
+ // restart the verification without leaving the step.
685
+ presentTerminalRetry('NO_PROGRESS', t.liveness.noProgressMessage);
686
+ }, PROGRESS_WATCHDOG_MS);
687
+ }, [presentTerminalRetry, stopWatchdog, t.liveness.noProgressMessage]);
688
+
689
+ const handleWsMessage = useCallback(
690
+ (msg: IrisServerMessage) => {
691
+ switch (msg.type) {
692
+ case 'SESSION_READY': {
693
+ setStatusText(null);
694
+ // The ~1-2 s gap between SESSION_READY and the first CHALLENGE is
695
+ // where users decide their posture for the whole session. We use
696
+ // it for two pieces of guidance, layered:
697
+ // - A short "Heads up — starting now" toast above the oval so
698
+ // they're not caught looking away when (e.g.) the BLINK window
699
+ // opens.
700
+ // - A persistent `challengeText` ("Center your face in the oval")
701
+ // anchored above the oval so they keep adjusting until the
702
+ // first real challenge arrives and overwrites it. Without
703
+ // this, every Android calibration session started with the
704
+ // face at ~25 % of the frame width and SMILE / MOVE_FARTHER
705
+ // failed before the user understood what was being asked.
706
+ setChallengeText(t.liveness.centerFace);
707
+ showToast('success', t.liveness.getReady);
708
+ 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();
713
+ resetWatchdog();
714
+ return;
715
+ }
716
+ case 'CHALLENGE': {
717
+ const ch = (msg.challenge ?? null) as IrisChallenge | null;
718
+ currentChallengeRef.current = ch;
719
+ // Stash the sequence position so CHALLENGE_COMPLETE can tell
720
+ // whether this was the LAST challenge and switch to the analyzing
721
+ // overlay immediately instead of waiting for SESSION_COMPLETE.
722
+ if (
723
+ typeof msg.sequenceIndex === 'number' &&
724
+ typeof msg.totalChallenges === 'number'
725
+ ) {
726
+ lastChallengeMetaRef.current = {
727
+ index: msg.sequenceIndex,
728
+ total: msg.totalChallenges,
729
+ };
730
+ }
731
+ adjustFps(
732
+ ch === 'TURN_LEFT' || ch === 'TURN_RIGHT'
733
+ ? FRAME_MS_TURN
734
+ : FRAME_MS_DEFAULT,
735
+ );
736
+ setChallengeText(challengeLabel(ch));
737
+ // Map distance challenges to an oval-size cue so the viewfinder
738
+ // shape reinforces the instruction (grows for closer, returns to
739
+ // neutral for farther). All other challenges keep the neutral
740
+ // oval — the dim mask shouldn't move under a turn / smile / blink.
741
+ setOvalCue(
742
+ ch === 'MOVE_CLOSER'
743
+ ? 'MOVE_CLOSER'
744
+ : ch === 'MOVE_FARTHER'
745
+ ? 'MOVE_FARTHER'
746
+ : 'NEUTRAL',
747
+ );
748
+ setProgress(0);
749
+ resetWatchdog();
750
+ return;
751
+ }
752
+ case 'CHALLENGE_PROGRESS': {
753
+ if (typeof msg.confidence === 'number') {
754
+ setProgress(msg.confidence);
755
+ }
756
+ resetWatchdog();
757
+ return;
758
+ }
759
+ case 'CHALLENGE_COMPLETE': {
760
+ setProgress(1);
761
+ currentChallengeRef.current = null;
762
+ adjustFps(FRAME_MS_DEFAULT);
763
+ // Reset the oval back to neutral after each challenge so the
764
+ // next CHALLENGE (or finalize) doesn't inherit a "zoomed" oval.
765
+ setOvalCue('NEUTRAL');
766
+ // Last challenge of the sequence completed → switch to the
767
+ // "Analyzing your video" overlay right away. SESSION_COMPLETE
768
+ // can take several seconds to land while the worker drains
769
+ // its queue; without this the user would stare at the camera
770
+ // and the stale instruction the whole time.
771
+ //
772
+ // CRITICAL: the video recording MUST be stopped before the phase
773
+ // change. Switching phase unmounts <LivenessCamera>, which makes
774
+ // vision-camera tear down the recording mid-flush — the
775
+ // `onRecordingFinished` callback never fires and the upload
776
+ // promise stays pending until the 60 s timeout. We stop first,
777
+ // then unmount.
778
+ const meta = lastChallengeMetaRef.current;
779
+ if (meta && meta.index >= meta.total - 1) {
780
+ log.info('[Liveness] last challenge complete — preparing to finalize', {
781
+ index: meta.index,
782
+ total: meta.total,
783
+ videoOutcome: videoOutcomeRef.current,
784
+ });
785
+ stopCapture();
786
+ (async () => {
787
+ await stopVideoRecordingIfActive();
788
+ log.info('[Liveness] last challenge: switching phase to finalizing');
789
+ setPhase('finalizing');
790
+ })();
791
+ }
792
+ resetWatchdog();
793
+ return;
794
+ }
795
+ case 'WARNING': {
796
+ if (msg.code && TERMINAL_WARNING_CODES.has(msg.code)) {
797
+ presentTerminalRetry(msg.code, msg.message);
798
+ return;
799
+ }
800
+ // The orchestrator aborted the running challenge because capture
801
+ // quality dropped mid-gesture (face drifted too far, lighting
802
+ // fell). Drop back to positioning-style guidance — no progress
803
+ // bar, neutral oval, persistent hint — and let the SAME challenge
804
+ // re-arrive on its own once the user is well positioned again.
805
+ if (msg.code === 'CHALLENGE_REPOSITION') {
806
+ currentChallengeRef.current = null;
807
+ adjustFps(FRAME_MS_DEFAULT);
808
+ setProgress(null);
809
+ setOvalCue('NEUTRAL');
810
+ const repositionText = msg.message ?? t.liveness.repositioning;
811
+ setChallengeText(repositionText);
812
+ showToast('warning', repositionText);
813
+ resetWatchdog();
814
+ return;
815
+ }
816
+ const isPositioningReady = msg.code === 'POSITIONING_READY';
817
+ // Per-code SDK-side fallback used when the orchestrator forwarded a
818
+ // code but no localised text (e.g. older orchestrator versions, or
819
+ // the rare WS message that drops the body). The orchestrator's own
820
+ // text is preferred — it always wins when present — so the user sees
821
+ // the server's exact wording in the session's locale.
822
+ const FALLBACK_BY_CODE: Record<string, string> = {
823
+ TOO_FAR: t.liveness.warningTooFar,
824
+ TOO_CLOSE: t.liveness.warningTooClose,
825
+ MOVE_CLOSER_HINT: t.liveness.warningMoveCloserHint,
826
+ MOVE_FARTHER_HINT: t.liveness.warningMoveFartherHint,
827
+ };
828
+ // Timeout fallback is dynamic: the orchestrator now sends a
829
+ // challenge-specific message ("No pudimos reconocer el giro hacia
830
+ // la izquierda"), but if it ever drops it the SDK rebuilds the
831
+ // same text from the locally tracked active challenge.
832
+ let timeoutFallback: string | undefined;
833
+ if (msg.code === 'CHALLENGE_TIMEOUT') {
834
+ const ch = currentChallengeRef.current;
835
+ switch (ch) {
836
+ case 'TURN_LEFT': timeoutFallback = t.liveness.timeoutTurnLeft; break;
837
+ case 'TURN_RIGHT': timeoutFallback = t.liveness.timeoutTurnRight; break;
838
+ case 'BLINK': timeoutFallback = t.liveness.timeoutBlink; break;
839
+ case 'SMILE': timeoutFallback = t.liveness.timeoutSmile; break;
840
+ case 'MOVE_CLOSER': timeoutFallback = t.liveness.timeoutMoveCloser; break;
841
+ case 'MOVE_FARTHER': timeoutFallback = t.liveness.timeoutMoveFarther; break;
842
+ default: timeoutFallback = t.liveness.timeoutGeneric;
843
+ }
844
+ }
845
+ const codedFallback =
846
+ timeoutFallback ??
847
+ (msg.code ? FALLBACK_BY_CODE[msg.code] : undefined) ??
848
+ t.liveness.warningGeneric;
849
+ // Prefer the server-localised message — it's situationally
850
+ // accurate ("El fondo tiene mucho movimiento o reflejos. Pasá a
851
+ // un fondo neutro y plano"). Drop to the SDK fallback only when
852
+ // the orchestrator did not provide one.
853
+ const baseText = msg.message ?? codedFallback;
854
+ const text = isPositioningReady
855
+ ? t.liveness.positioningReady
856
+ : typeof msg.consecutiveMisses === 'number' &&
857
+ msg.consecutiveMisses >= 3
858
+ ? t.liveness.warningConsecutiveMisses
859
+ .replace('{n}', String(msg.consecutiveMisses))
860
+ .concat(' — ', baseText)
861
+ : baseText;
862
+ showToast(isPositioningReady ? 'success' : 'warning', text);
863
+ resetWatchdog();
864
+ return;
865
+ }
866
+ case 'ERROR': {
867
+ failWith({
868
+ code: SdkErrorCode.LIVENESS_FAILED,
869
+ message:
870
+ msg.message ?? msg.code ?? 'Iris reported an error during liveness.',
871
+ });
872
+ return;
873
+ }
874
+ case 'SESSION_COMPLETE': {
875
+ stopWatchdog();
876
+ if (finalizingRef.current) return;
877
+ finalizingRef.current = true;
878
+ stopCapture();
879
+ try {
880
+ wsRef.current?.close(1000, 'session_complete');
881
+ } catch {
882
+ /* ignore */
883
+ }
884
+ wsRef.current = null;
885
+ // IMPORTANT: do NOT setPhase('finalizing') yet. Switching phase
886
+ // unmounts LivenessCamera, which cancels the in-flight video
887
+ // recording mid-flush and prevents `onRecordingFinished` from
888
+ // firing — the upload would never start. We stop the recording
889
+ // first (camera still mounted, ref valid), then transition phase
890
+ // and run the verify pipeline.
891
+ (async () => {
892
+ // ── Settle the video pipeline before /liveness-verify ─────────
893
+ // Best-effort: stop the recording (if still running), then await
894
+ // the upload promise with a hard timeout. Whatever the outcome
895
+ // (uploaded / failed / timeout), we proceed to verify — the body
896
+ // is only attached when the upload actually succeeded.
897
+ await stopVideoRecordingIfActive();
898
+ // Safe to unmount LivenessCamera now: the recording has been
899
+ // flushed and `onRecordingFinished` has been scheduled.
900
+ setPhase('finalizing');
901
+ if (videoUploadPromiseRef.current) {
902
+ log.info('[Liveness] awaiting video upload settle', {
903
+ timeoutMs: VIDEO_UPLOAD_TIMEOUT_MS,
904
+ });
905
+ const uploadPromise = videoUploadPromiseRef.current;
906
+ let uploadTimer: ReturnType<typeof setTimeout> | null = null;
907
+ const timeoutPromise = new Promise<void>((resolve) => {
908
+ uploadTimer = setTimeout(() => {
909
+ log.warn('[Liveness] video upload timed out — verify will go without body');
910
+ videoOutcomeRef.current = 'failed';
911
+ resolve();
912
+ }, VIDEO_UPLOAD_TIMEOUT_MS);
913
+ });
914
+ await Promise.race([uploadPromise, timeoutPromise]);
915
+ if (uploadTimer) clearTimeout(uploadTimer);
916
+ }
917
+ const verifyBody =
918
+ videoOutcomeRef.current === 'uploaded' && videoMetaRef.current
919
+ ? { video: videoMetaRef.current }
920
+ : {};
921
+ log.info('[Liveness] POST /liveness-verify', {
922
+ outcome: videoOutcomeRef.current,
923
+ hasBody: 'video' in verifyBody,
924
+ });
925
+
926
+ // Bound the verify call with an explicit timeout. SESSION_COMPLETE
927
+ // already turned the progress watchdog off, so if this POST hangs
928
+ // (the dev network shows recurring HTTP/2 INTERNAL_ERROR resets)
929
+ // nothing else would rescue the user — the app would sit on the
930
+ // analyzing overlay forever. On timeout we abort and route through
931
+ // failWith so the retry dialog is shown.
932
+ const verifyController = new AbortController();
933
+ const verifyTimeout = setTimeout(
934
+ () => verifyController.abort(),
935
+ LIVENESS_VERIFY_TIMEOUT_MS,
936
+ );
937
+ try {
938
+ await api.post(
939
+ `/sessions/${sessionId}/liveness-verify`,
940
+ verifyBody,
941
+ { signal: verifyController.signal },
942
+ );
943
+ clearTimeout(verifyTimeout);
944
+ onComplete();
945
+ } catch (err) {
946
+ clearTimeout(verifyTimeout);
947
+ const aborted =
948
+ verifyController.signal.aborted ||
949
+ (err != null &&
950
+ typeof err === 'object' &&
951
+ 'name' in err &&
952
+ (err as { name?: unknown }).name === 'AbortError');
953
+ const message = aborted
954
+ ? 'The verification request timed out. Check your connection and try again.'
955
+ : err && typeof err === 'object' && 'message' in err
956
+ ? String((err as { message?: unknown }).message)
957
+ : 'Failed to notify the backend that liveness completed.';
958
+ failWith({
959
+ code: aborted
960
+ ? SdkErrorCode.NETWORK_ERROR
961
+ : SdkErrorCode.LIVENESS_FAILED,
962
+ message,
963
+ cause: err,
964
+ });
965
+ }
966
+ })();
967
+ return;
968
+ }
969
+ default:
970
+ return;
971
+ }
972
+ },
973
+ [
974
+ adjustFps,
975
+ api,
976
+ challengeLabel,
977
+ failWith,
978
+ onComplete,
979
+ presentTerminalRetry,
980
+ resetWatchdog,
981
+ sessionId,
982
+ showToast,
983
+ startCaptureLoop,
984
+ startVideoRecordingIfEnabled,
985
+ stopCapture,
986
+ stopVideoRecordingIfActive,
987
+ stopWatchdog,
988
+ t.liveness.getReady,
989
+ t.liveness.positioningReady,
990
+ t.liveness.repositioning,
991
+ t.liveness.warningConsecutiveMisses,
992
+ t.liveness.warningGeneric,
993
+ ],
994
+ );
995
+
996
+ const startVerification = useCallback(async () => {
997
+ setBannerError(null);
998
+ setRetry(null);
999
+ setStatusText(t.liveness.connecting);
1000
+ finalizingRef.current = false;
1001
+ framesSentRef.current = 0;
1002
+ currentChallengeRef.current = null;
1003
+ lastChallengeMetaRef.current = null;
1004
+ frameMsRef.current = FRAME_MS_DEFAULT;
1005
+ hmacRef.current = null;
1006
+
1007
+ let init: LivenessSessionResponse;
1008
+ try {
1009
+ // `calibration_label` is the wire name expected by the backend
1010
+ // (snake_case mirroring iris-test's `/sessions` POST). Only sent when
1011
+ // the host explicitly enables calibration via VelionConfig.
1012
+ const body: Record<string, unknown> = {};
1013
+ if (calibrationLabel && calibrationLabel.length > 0) {
1014
+ body.calibration_label = calibrationLabel;
1015
+ }
1016
+ init = await api.post<LivenessSessionResponse>(
1017
+ `/sessions/${sessionId}/liveness-init`,
1018
+ body,
1019
+ );
1020
+ } catch (err) {
1021
+ failWith({
1022
+ code: SdkErrorCode.LIVENESS_INIT_FAILED,
1023
+ message:
1024
+ (err && typeof err === 'object' && 'message' in err
1025
+ ? String((err as { message?: unknown }).message)
1026
+ : '') || 'Failed to create the Iris liveness session.',
1027
+ cause: err,
1028
+ });
1029
+ return;
1030
+ }
1031
+ if (!init.liveness_session_id || !init.websocket_url) {
1032
+ failWith({
1033
+ code: SdkErrorCode.LIVENESS_INIT_FAILED,
1034
+ message: 'liveness-init response missing required fields.',
1035
+ });
1036
+ return;
1037
+ }
1038
+ livenessSessionIdRef.current = init.liveness_session_id;
1039
+ if (init.frame_integrity_key_base64) {
1040
+ try {
1041
+ hmacRef.current = importHmacKey(init.frame_integrity_key_base64);
1042
+ } catch (err) {
1043
+ log.warn('[Liveness] failed to import HMAC key', err);
1044
+ hmacRef.current = null;
1045
+ }
1046
+ }
1047
+ // Reset the video pipeline state for this attempt (the host may retry).
1048
+ // We honour `video_upload` even when the host did not register the
1049
+ // `onLivenessVideoUploaded` callback — the upload still happens, only
1050
+ // the host notification is skipped. `outcome` stays `'none'` until
1051
+ // `startVideoRecordingIfEnabled` confirms the recording actually started;
1052
+ // see that callback for why we cannot trust `init.video_upload` alone.
1053
+ videoUploadRef.current = init.video_upload ?? null;
1054
+ videoOutcomeRef.current = 'none';
1055
+ videoMetaRef.current = null;
1056
+ videoUploadPromiseRef.current = null;
1057
+ videoRecordingFinishedPromiseRef.current = null;
1058
+ videoTempPathRef.current = null;
1059
+ if (init.video_upload) {
1060
+ log.info('[Liveness] init.video_upload received', {
1061
+ url: truncateUrl(init.video_upload.upload_url),
1062
+ expiresAt: init.video_upload.expires_at,
1063
+ method: init.video_upload.method,
1064
+ });
1065
+ } else {
1066
+ log.info('[Liveness] init.video_upload absent — recording disabled for this session');
1067
+ }
1068
+
1069
+ setStatusText(t.liveness.preparingCamera);
1070
+ let connection: IrisConnection;
1071
+ try {
1072
+ connection = openIrisWebSocket({
1073
+ websocketUrl: init.websocket_url,
1074
+ connectionToken: init.connection_token,
1075
+ locale,
1076
+ onOpen: () => setStatusText(t.liveness.connecting),
1077
+ onMessage: handleWsMessage,
1078
+ onClose: (code, reason) => {
1079
+ if (finalizingRef.current) return;
1080
+ // Code 4001 is the close we send ourselves from
1081
+ // `presentTerminalRetry` to tear down the WS before showing the
1082
+ // retry dialog. Checking the React state `retry` here is unsafe
1083
+ // — this handler is registered via closure on a stale render,
1084
+ // so `retry` reads `null` even when we just called `setRetry`.
1085
+ // The close code is reliable: we always pair 4001 with the
1086
+ // retry-dialog mount.
1087
+ if (code === 4001) return;
1088
+ 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
+ }).`,
1096
+ });
1097
+ },
1098
+ });
1099
+ } catch (err) {
1100
+ failWith({
1101
+ code: SdkErrorCode.LIVENESS_FAILED,
1102
+ message:
1103
+ err instanceof Error
1104
+ ? err.message
1105
+ : 'Failed to open the Iris WebSocket.',
1106
+ cause: err,
1107
+ });
1108
+ return;
1109
+ }
1110
+ wsRef.current = connection;
1111
+ }, [
1112
+ api,
1113
+ calibrationLabel,
1114
+ failWith,
1115
+ handleWsMessage,
1116
+ locale,
1117
+ retry,
1118
+ sessionId,
1119
+ stopCapture,
1120
+ stopWatchdog,
1121
+ t.liveness.connecting,
1122
+ t.liveness.preparingCamera,
1123
+ ]);
1124
+
1125
+ // Re-run after a terminal retry — same cleanup as start, but reuses the
1126
+ // mounted camera (no DOM teardown).
1127
+ const restartVerification = useCallback(async () => {
1128
+ setRetry(null);
1129
+ setProgress(null);
1130
+ setChallengeText(null);
1131
+ setOvalCue('NEUTRAL');
1132
+ await startVerification();
1133
+ }, [startVerification]);
1134
+
1135
+ // Effect: when the user enters the capture phase (intro skipped or
1136
+ // confirmed), run the start sequence.
1137
+ //
1138
+ // NOTE: this effect must NOT tear down the WebSocket in its cleanup.
1139
+ // Its dependency is `[phase]`, so the cleanup runs on every phase change
1140
+ // — including capturing → finalizing. Closing the WS there killed it
1141
+ // ~250 ms after the last CHALLENGE_COMPLETE, i.e. *before* Iris emitted
1142
+ // SESSION_COMPLETE (~440 ms later), so the SDK never received it and
1143
+ // never sent /liveness-verify. Session teardown lives in the unmount-only
1144
+ // effect below.
1145
+ useEffect(() => {
1146
+ if (phase !== 'capturing') return;
1147
+ void startVerification();
1148
+ // We intentionally only re-run when phase flips into capturing — the
1149
+ // first start; the retry path is handled by `restartVerification`.
1150
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1151
+ }, [phase]);
1152
+
1153
+ // Effect: real component teardown. Runs once, on unmount only — so the
1154
+ // WebSocket survives in-flow phase changes (capturing → finalizing) and
1155
+ // stays open long enough to receive SESSION_COMPLETE. The SESSION_COMPLETE
1156
+ // / fail / terminal-retry handlers already close the WS explicitly when
1157
+ // the flow ends normally; this is the safety net for an actual unmount.
1158
+ useEffect(() => {
1159
+ return () => {
1160
+ stopCapture();
1161
+ stopWatchdog();
1162
+ if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
1163
+ // Best-effort video pipeline shutdown on unmount. Stop the recording
1164
+ // if it's still running (vision-camera deletes its temp file when the
1165
+ // <Camera> tears down anyway, but we explicitly stop to flush). Then
1166
+ // delete any temp file we own, so a backed-out user doesn't leak
1167
+ // storage.
1168
+ if (videoOutcomeRef.current === 'recording') {
1169
+ void stopVideoRecordingIfActive();
1170
+ }
1171
+ const leftoverPath = videoTempPathRef.current;
1172
+ videoTempPathRef.current = null;
1173
+ if (leftoverPath) {
1174
+ void deleteVideoTemp(leftoverPath);
1175
+ }
1176
+ try {
1177
+ wsRef.current?.close(1000, 'unmount');
1178
+ } catch {
1179
+ /* ignore */
1180
+ }
1181
+ wsRef.current = null;
1182
+ };
1183
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1184
+ }, []);
1185
+
1186
+ if (retry) {
1187
+ return (
1188
+ <RetryDialog
1189
+ title={t.liveness.terminalRetryTitle}
1190
+ message={retry.message}
1191
+ retryLabel={t.liveness.terminalRetryButton}
1192
+ cancelLabel={t.liveness.terminalCancelButton}
1193
+ onRetry={() => {
1194
+ void restartVerification();
1195
+ }}
1196
+ onCancel={() => {
1197
+ setRetry(null);
1198
+ onCancel({
1199
+ code: SdkErrorCode.LIVENESS_FAILED,
1200
+ message: retry.message,
1201
+ });
1202
+ }}
1203
+ />
1204
+ );
1205
+ }
1206
+
1207
+ if (phase === 'intro') {
1208
+ return (
1209
+ <View style={{ flex: 1 }}>
1210
+ <StepShell
1211
+ title={t.liveness.introTitle}
1212
+ subtitle={t.liveness.introSubtitle}
1213
+ iconNode={<StepIcon name="face" />}
1214
+ >
1215
+ <ScrollView contentContainerStyle={styles.tipsList}>
1216
+ {t.liveness.introTips.map((tip, idx) => (
1217
+ <View
1218
+ key={idx}
1219
+ style={[
1220
+ styles.tipRow,
1221
+ {
1222
+ borderColor: theme.borderColor,
1223
+ backgroundColor: mixHex(
1224
+ theme.primaryColor,
1225
+ theme.backgroundColor,
1226
+ 6,
1227
+ ),
1228
+ borderRadius: theme.borderRadiusPx,
1229
+ },
1230
+ ]}
1231
+ >
1232
+ <View
1233
+ style={[
1234
+ styles.tipIcon,
1235
+ {
1236
+ backgroundColor: mixHex(
1237
+ theme.primaryColor,
1238
+ theme.backgroundColor,
1239
+ 18,
1240
+ ),
1241
+ },
1242
+ ]}
1243
+ >
1244
+ <Text
1245
+ style={[styles.tipIconText, { color: theme.primaryColor }]}
1246
+ >
1247
+ {idx + 1}
1248
+ </Text>
1249
+ </View>
1250
+ <Text style={[styles.tipText, { color: theme.textColor }]}>
1251
+ {tip}
1252
+ </Text>
1253
+ </View>
1254
+ ))}
1255
+ </ScrollView>
1256
+ {bannerError ? <Banner message={bannerError} /> : null}
1257
+ <View style={styles.introActions}>
1258
+ {showBackButton ? (
1259
+ <Button
1260
+ variant="ghost"
1261
+ label={t.liveness.introBack}
1262
+ onPress={() =>
1263
+ onCancel({
1264
+ code: SdkErrorCode.LIVENESS_FAILED,
1265
+ message: 'User exited the liveness intro.',
1266
+ })
1267
+ }
1268
+ fullWidth={false}
1269
+ style={styles.introBtn}
1270
+ />
1271
+ ) : null}
1272
+ <Button
1273
+ label={t.liveness.introStart}
1274
+ onPress={() => setPhase('capturing')}
1275
+ fullWidth={!showBackButton}
1276
+ style={showBackButton ? styles.introBtn : undefined}
1277
+ />
1278
+ </View>
1279
+ </StepShell>
1280
+ </View>
1281
+ );
1282
+ }
1283
+
1284
+ if (phase === 'finalizing') {
1285
+ return (
1286
+ <AnalyzingOverlay
1287
+ headline={t.liveness.analyzingHeadline}
1288
+ caption={t.liveness.analyzingCaption}
1289
+ />
1290
+ );
1291
+ }
1292
+
1293
+ return (
1294
+ <View style={{ flex: 1 }}>
1295
+ <LivenessCamera
1296
+ ref={cameraRef}
1297
+ statusText={statusText}
1298
+ challengeText={challengeText}
1299
+ ovalCue={ovalCue}
1300
+ toast={toast}
1301
+ progress={progress}
1302
+ permissionDeniedLabel={t.liveness.cameraPermissionDenied}
1303
+ retryLabel={t.liveness.cameraTryAgain}
1304
+ cancelLabel={t.common.cancel}
1305
+ // Intentionally no onCancel during capture. The capture screen is
1306
+ // meant to be fullscreen and uninterruptible — if the user wants
1307
+ // out, the 25 s progress watchdog catches stalled sessions and
1308
+ // routes them through the RetryDialog (with its own Cancel option).
1309
+ // The intro screen keeps the explicit "Atrás" button.
1310
+ />
1311
+ </View>
1312
+ );
1313
+ }
1314
+
1315
+ const styles = StyleSheet.create({
1316
+ tipsList: {
1317
+ paddingVertical: 4,
1318
+ gap: 10,
1319
+ },
1320
+ tipRow: {
1321
+ flexDirection: 'row',
1322
+ alignItems: 'center',
1323
+ gap: 12,
1324
+ padding: 12,
1325
+ borderWidth: 1,
1326
+ },
1327
+ tipIcon: {
1328
+ width: 32,
1329
+ height: 32,
1330
+ borderRadius: 16,
1331
+ alignItems: 'center',
1332
+ justifyContent: 'center',
1333
+ },
1334
+ tipIconText: {
1335
+ fontSize: 14,
1336
+ fontWeight: '700',
1337
+ },
1338
+ tipText: {
1339
+ flex: 1,
1340
+ fontSize: 14,
1341
+ lineHeight: 20,
1342
+ },
1343
+ introActions: {
1344
+ flexDirection: 'row',
1345
+ gap: 10,
1346
+ marginTop: 6,
1347
+ },
1348
+ introBtn: {
1349
+ flex: 1,
1350
+ },
1351
+ });