@myazahq/kyc-sdk-react-native 2.5.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +277 -7
  2. package/android/build.gradle +30 -16
  3. package/android/consumer-rules.pro +22 -0
  4. package/android/src/main/AndroidManifest.xml +17 -6
  5. package/android/src/main/java/com/margelo/nitro/myazakyc/HybridMyazaFaceDetector.kt +27 -70
  6. package/android/src/main/java/com/margelo/nitro/myazakyc/HybridMyazaTextRecognizer.kt +14 -0
  7. package/android/src/main/java/com/margelo/nitro/myazakyc/MlKitModelReadiness.kt +154 -0
  8. package/app.plugin.js +146 -10
  9. package/ios/HybridMyazaFaceDetector.swift +8 -3
  10. package/ios/HybridMyazaTextRecognizer.swift +8 -0
  11. package/nitrogen/generated/android/c++/JHybridMyazaTextRecognizerSpec.cpp +21 -0
  12. package/nitrogen/generated/android/c++/JHybridMyazaTextRecognizerSpec.hpp +2 -0
  13. package/nitrogen/generated/android/kotlin/com/margelo/nitro/myazakyc/HybridMyazaTextRecognizerSpec.kt +8 -0
  14. package/nitrogen/generated/ios/c++/HybridMyazaTextRecognizerSpecSwift.hpp +16 -0
  15. package/nitrogen/generated/ios/swift/HybridMyazaTextRecognizerSpec.swift +2 -0
  16. package/nitrogen/generated/ios/swift/HybridMyazaTextRecognizerSpec_cxx.swift +31 -0
  17. package/nitrogen/generated/shared/c++/HybridMyazaTextRecognizerSpec.cpp +2 -0
  18. package/nitrogen/generated/shared/c++/HybridMyazaTextRecognizerSpec.hpp +2 -0
  19. package/package.json +30 -9
  20. package/src/MyazaKYC.tsx +4 -11
  21. package/src/assets/fonts/Karla_400Regular.ttf +0 -0
  22. package/src/assets/fonts/Karla_500Medium.ttf +0 -0
  23. package/src/assets/fonts/Karla_600SemiBold.ttf +0 -0
  24. package/src/assets/fonts/Karla_700Bold.ttf +0 -0
  25. package/src/assets/fonts/OFL-Karla.txt +93 -0
  26. package/src/assets/fonts/OFL-SpaceGrotesk.txt +93 -0
  27. package/src/assets/fonts/README.md +12 -0
  28. package/src/assets/fonts/SpaceGrotesk_500Medium.ttf +0 -0
  29. package/src/assets/fonts/SpaceGrotesk_600SemiBold.ttf +0 -0
  30. package/src/assets/fonts/SpaceGrotesk_700Bold.ttf +0 -0
  31. package/src/capture/useAutoCapture.ts +8 -1
  32. package/src/components/CountryField.tsx +8 -0
  33. package/src/components/CountryRegionPicker.tsx +184 -0
  34. package/src/components/DialCodePicker.tsx +47 -68
  35. package/src/components/DialCodeRow.tsx +102 -0
  36. package/src/components/DocumentCropper.tsx +30 -24
  37. package/src/components/DocumentReview.tsx +11 -1
  38. package/src/components/DocumentReviewSide.tsx +6 -2
  39. package/src/components/DocumentReviewZoom.tsx +5 -1
  40. package/src/components/FramedMapPicker.tsx +122 -0
  41. package/src/components/GeoBadge.tsx +34 -0
  42. package/src/components/Icon.tsx +10 -192
  43. package/src/components/KycFlow.tsx +69 -34
  44. package/src/components/LineSkeleton.tsx +100 -0
  45. package/src/components/MapChrome.tsx +67 -0
  46. package/src/components/MapPinMarker.tsx +54 -0
  47. package/src/components/MapPinPicker.tsx +179 -0
  48. package/src/components/MilestoneTrack.tsx +155 -0
  49. package/src/components/MyazaButton.tsx +9 -0
  50. package/src/components/MyazaInput.tsx +17 -1
  51. package/src/components/OptionRow.tsx +22 -3
  52. package/src/components/PhoneNumberInput.tsx +8 -0
  53. package/src/components/PoweredBy.tsx +5 -5
  54. package/src/components/PresenceBlocks.tsx +153 -0
  55. package/src/components/RequiredDocumentPill.tsx +114 -0
  56. package/src/components/StepHeader.tsx +23 -3
  57. package/src/components/StepView.tsx +17 -0
  58. package/src/components/StickyActions.tsx +56 -0
  59. package/src/components/dialCodeRows.ts +64 -0
  60. package/src/components/documentReviewCopy.ts +39 -0
  61. package/src/components/fonts.ts +14 -17
  62. package/src/components/icon-map.ts +176 -0
  63. package/src/components/stepHeaderMeta.tsx +48 -5
  64. package/src/config/addressCollection.ts +125 -0
  65. package/src/config/biometricOptions.ts +100 -0
  66. package/src/config/business.ts +20 -1
  67. package/src/config/businessSteps.ts +8 -2
  68. package/src/config/consentStep.ts +19 -0
  69. package/src/config/documentCaptureMethods.ts +31 -0
  70. package/src/config/proofOfAddress.ts +54 -11
  71. package/src/config/regions.ts +24 -0
  72. package/src/config/stepOrder.ts +79 -5
  73. package/src/config/uploadLimits.ts +35 -0
  74. package/src/config/workflowMerge.ts +13 -5
  75. package/src/index.ts +49 -1
  76. package/src/lib/address-current-location.ts +171 -0
  77. package/src/lib/address-field-modes.ts +119 -0
  78. package/src/lib/address-flow.ts +172 -0
  79. package/src/lib/address-helpers.ts +48 -0
  80. package/src/lib/address-line.ts +76 -0
  81. package/src/lib/address-pin-move.ts +97 -0
  82. package/src/lib/address-step-recovery.ts +63 -0
  83. package/src/lib/authed-image.ts +78 -0
  84. package/src/lib/biometric-copy.ts +51 -0
  85. package/src/lib/captureRing.ts +83 -0
  86. package/src/lib/country-adoption.ts +89 -0
  87. package/src/lib/documentCaptureCheck.ts +136 -0
  88. package/src/lib/inferred-country.ts +65 -0
  89. package/src/lib/livenessLayout.ts +49 -0
  90. package/src/lib/map-frame.ts +159 -0
  91. package/src/lib/map-tiles.ts +143 -0
  92. package/src/lib/model-ready.ts +82 -0
  93. package/src/lib/poa-country-gate.ts +27 -0
  94. package/src/lib/prime-models.ts +50 -0
  95. package/src/lib/resubmit.ts +36 -7
  96. package/src/lib/result-copy.ts +116 -0
  97. package/src/lib/result-wait.ts +53 -0
  98. package/src/lib/review-map-surface.ts +26 -0
  99. package/src/lib/scope.ts +31 -0
  100. package/src/lib/selfie-sharpness.ts +211 -0
  101. package/src/lib/selfie-upload-wait.ts +79 -0
  102. package/src/lib/street-view-fov.ts +42 -0
  103. package/src/lib/webview-available.ts +47 -0
  104. package/src/liveness/avatarSource.ts +59 -0
  105. package/src/liveness/useLiveness.ts +6 -1
  106. package/src/liveness/useModelReady.ts +9 -55
  107. package/src/mrz/extract.ts +71 -4
  108. package/src/mrz/textRecognizer.ts +36 -0
  109. package/src/mrz/useTextModelReady.ts +21 -0
  110. package/src/presence/background-math.ts +100 -0
  111. package/src/presence/background-store.ts +82 -0
  112. package/src/presence/background.ts +165 -0
  113. package/src/presence/foreground-service.ts +193 -0
  114. package/src/presence/fs.ts +51 -0
  115. package/src/presence/geofence.ts +41 -0
  116. package/src/presence/math.ts +44 -0
  117. package/src/presence/post.ts +40 -0
  118. package/src/presence/report.ts +87 -0
  119. package/src/presence/sampler.ts +110 -0
  120. package/src/presence/status.ts +92 -0
  121. package/src/presence/store.ts +94 -0
  122. package/src/presence/tier.ts +36 -0
  123. package/src/presence/watch-wait.ts +81 -0
  124. package/src/screens/AddressCountryControl.tsx +115 -0
  125. package/src/screens/BusinessDetailsFields.tsx +3 -0
  126. package/src/screens/BusinessDetailsStep.tsx +2 -0
  127. package/src/screens/BusinessDocumentSlot.tsx +3 -2
  128. package/src/screens/BusinessDocumentsStep.tsx +4 -55
  129. package/src/screens/CompanyInfoFields.tsx +6 -1
  130. package/src/screens/ConsentStep.tsx +6 -17
  131. package/src/screens/ContactActions.tsx +54 -0
  132. package/src/screens/ContactDestinationField.tsx +4 -0
  133. package/src/screens/ContactEntryPanel.tsx +75 -0
  134. package/src/screens/ContactVerificationStep.tsx +26 -56
  135. package/src/screens/CountrySelectStep.tsx +13 -147
  136. package/src/screens/DocumentCaptureStep.tsx +177 -93
  137. package/src/screens/LivenessAvatar.tsx +33 -16
  138. package/src/screens/LivenessStep.tsx +188 -49
  139. package/src/screens/MrzScanView.tsx +33 -0
  140. package/src/screens/PoaDocumentTypeList.tsx +66 -0
  141. package/src/screens/ProofOfAddressParts.tsx +151 -0
  142. package/src/screens/ProofOfAddressStep.tsx +58 -99
  143. package/src/screens/SubmittedBadge.tsx +25 -0
  144. package/src/screens/SubmittedError.tsx +64 -0
  145. package/src/screens/SubmittedResult.tsx +117 -0
  146. package/src/screens/SubmittedStep.tsx +71 -164
  147. package/src/screens/SubmittedSuccess.tsx +127 -0
  148. package/src/screens/SubmittedWaiting.tsx +45 -0
  149. package/src/screens/address/AddressEntranceStep.tsx +161 -0
  150. package/src/screens/address/AddressIntroGate.tsx +148 -0
  151. package/src/screens/address/AddressMapStub.tsx +50 -0
  152. package/src/screens/address/AddressPinStep.tsx +178 -0
  153. package/src/screens/address/AddressReviewStep.tsx +162 -0
  154. package/src/screens/address/AddressSandboxTabs.tsx +158 -0
  155. package/src/screens/address/AddressSearchField.tsx +115 -0
  156. package/src/screens/address/AddressSearchStep.tsx +94 -0
  157. package/src/screens/address/CurrentLocationRow.tsx +135 -0
  158. package/src/screens/address/DetailsSheet.tsx +175 -0
  159. package/src/screens/address/DetailsSheetFields.tsx +184 -0
  160. package/src/screens/address/EntranceDropzone.tsx +178 -0
  161. package/src/screens/address/EntranceFraming.tsx +66 -0
  162. package/src/screens/address/EntrancePills.tsx +60 -0
  163. package/src/screens/address/FramedStreetView.tsx +155 -0
  164. package/src/screens/address/IntroDisclosures.tsx +210 -0
  165. package/src/screens/address/LabelDecisionRow.tsx +113 -0
  166. package/src/screens/address/PinSummaryRow.tsx +105 -0
  167. package/src/screens/address/ReviewAddressBand.tsx +111 -0
  168. package/src/screens/address/ReviewEntranceThumbs.tsx +64 -0
  169. package/src/screens/address/ReviewMapPicture.tsx +106 -0
  170. package/src/screens/address/SearchResults.tsx +105 -0
  171. package/src/screens/address/SearchScreen.tsx +176 -0
  172. package/src/screens/address/SkipForNow.tsx +43 -0
  173. package/src/screens/address/StreetViewChrome.tsx +81 -0
  174. package/src/screens/address/detail-values.ts +22 -0
  175. package/src/screens/address/fix-source.ts +27 -0
  176. package/src/screens/address/index.ts +8 -0
  177. package/src/screens/address/meta.ts +44 -0
  178. package/src/screens/address/use-address-flow.ts +200 -0
  179. package/src/screens/address/use-label-pin.ts +80 -0
  180. package/src/screens/address/use-pin-actions.ts +192 -0
  181. package/src/screens/consent/model.ts +79 -10
  182. package/src/screens/document/CaptureCheckNotice.tsx +77 -0
  183. package/src/screens/document/UploadPhase.tsx +177 -0
  184. package/src/screens/document/useDocumentCamera.ts +109 -0
  185. package/src/screens/liveness/CaptureRing.tsx +91 -0
  186. package/src/screens/liveness/LivenessCamera.tsx +63 -0
  187. package/src/screens/liveness/LivenessHandover.tsx +43 -0
  188. package/src/screens/liveness/LivenessOutcome.tsx +8 -4
  189. package/src/screens/liveness/SelfiePreview.tsx +31 -7
  190. package/src/screens/liveness/ShutterFlash.tsx +25 -0
  191. package/src/screens/liveness/index.ts +4 -0
  192. package/src/screens/liveness/useSelfieUpload.ts +23 -3
  193. package/src/screens/nfc/NfcScanIllustration.tsx +7 -18
  194. package/src/screens/useAddressPhotoAttach.ts +77 -0
  195. package/src/screens/useBusinessDocumentAttach.ts +93 -0
  196. package/src/screens/usePoaAttach.ts +12 -15
  197. package/src/services/api-types.ts +119 -1
  198. package/src/services/api-verify-types.ts +37 -0
  199. package/src/services/api.ts +149 -3
  200. package/src/services/deviceMetadata.ts +1 -1
  201. package/src/services/location.ts +234 -0
  202. package/src/services/mediaCompress.ts +23 -5
  203. package/src/services/uploadErrors.ts +30 -0
  204. package/src/services/workflowGate.ts +7 -0
  205. package/src/specs/MyazaTextRecognizer.nitro.ts +29 -0
  206. package/src/store/address.ts +97 -0
  207. package/src/store/derive.ts +29 -4
  208. package/src/store/kycStore.ts +120 -5
  209. package/src/store/serverConfig.ts +18 -0
  210. package/src/store/session.ts +23 -4
  211. package/src/store/state.ts +134 -0
  212. package/src/store/submit.ts +18 -1
  213. package/src/types/config.ts +63 -1
  214. package/src/types/verification.ts +12 -0
  215. package/src/types/workflow.ts +97 -1
  216. package/src/assets/liveness/Blink.gif +0 -0
  217. package/src/assets/liveness/Nod.gif +0 -0
  218. package/src/assets/liveness/Smile.gif +0 -0
  219. package/src/assets/liveness/Turn.gif +0 -0
@@ -0,0 +1,44 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Presence math — the pure half of the foreground reporter. On-device
3
+ // evaluation is the contract: the phone decides "inside the fence?" and "what
4
+ // local day/night is it?", and only the derived record (day + flag) ever
5
+ // leaves the device. Raw coordinates never travel after capture.
6
+ //
7
+ // Mirrors the Flutter SDK's presence_math.dart — keep the two in lockstep.
8
+ // ---------------------------------------------------------------------------
9
+
10
+ const EARTH_RADIUS_M = 6_371_000;
11
+
12
+ export function haversineMeters(
13
+ lat1: number,
14
+ lng1: number,
15
+ lat2: number,
16
+ lng2: number,
17
+ ): number {
18
+ const rad = (d: number) => (d * Math.PI) / 180;
19
+ const dLat = rad(lat2 - lat1);
20
+ const dLng = rad(lng2 - lng1);
21
+ const a =
22
+ Math.sin(dLat / 2) ** 2 +
23
+ Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLng / 2) ** 2;
24
+ return 2 * EARTH_RADIUS_M * Math.asin(Math.min(1, Math.sqrt(a)));
25
+ }
26
+
27
+ /** The server's at-address rule, applied on-device: 250 m, widened to the
28
+ * fix's reported accuracy, capped at 1 km. */
29
+ export function insideFence(
30
+ pin: { lat: number; lng: number },
31
+ fix: { lat: number; lng: number; accuracy: number | null },
32
+ ): boolean {
33
+ const radius = Math.min(1000, Math.max(250, fix.accuracy ?? 0));
34
+ return haversineMeters(pin.lat, pin.lng, fix.lat, fix.lng) <= radius;
35
+ }
36
+
37
+ /** The observation's day + night flag, from the DEVICE's local clock — that is
38
+ * the whole point of on-device evaluation. Night = 20:00–05:59 local. */
39
+ export function localDayAndNight(now = new Date()): { day: string; nightPresent: boolean } {
40
+ const pad = (n: number) => String(n).padStart(2, '0');
41
+ const day = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
42
+ const hour = now.getHours();
43
+ return { day, nightPresent: hour >= 20 || hour < 6 };
44
+ }
@@ -0,0 +1,40 @@
1
+ // ---------------------------------------------------------------------------
2
+ // The one wire path for presence observations — shared by the foreground
3
+ // reporter and the background geofence flush, so the two tiers can never
4
+ // drift on the request shape. Best-effort by contract: a failure returns
5
+ // false and the caller keeps its queue.
6
+ // ---------------------------------------------------------------------------
7
+
8
+ import { resolveBaseUrl } from '../services/resolveUrl';
9
+
10
+ export interface WireObservation {
11
+ day: string;
12
+ source: 'geofence' | 'foreground';
13
+ dwellMinutes: number;
14
+ nightPresent: boolean;
15
+ samples: number;
16
+ integrity?: { mockLocation?: boolean; emulator?: boolean };
17
+ }
18
+
19
+ export async function postObservations(
20
+ apiKey: string,
21
+ devUrl: string | undefined,
22
+ externalUserId: string,
23
+ observations: WireObservation[],
24
+ ): Promise<boolean> {
25
+ if (observations.length === 0) return true;
26
+ try {
27
+ const base = resolveBaseUrl(apiKey, devUrl);
28
+ const response = await fetch(`${base}/api/kyc/address/observations`, {
29
+ method: 'POST',
30
+ headers: {
31
+ 'Content-Type': 'application/json',
32
+ Authorization: `Bearer ${apiKey}`,
33
+ },
34
+ body: JSON.stringify({ externalUserId, observations }),
35
+ });
36
+ return response.ok;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
@@ -0,0 +1,87 @@
1
+ // ---------------------------------------------------------------------------
2
+ // The FOREGROUND presence reporter — the default tier, no background
3
+ // permission. The host app calls reportAddressPresence() on app open, or the
4
+ // moment the flow submits (watch-wait.ts makes that safe: the watch is minted
5
+ // seconds after the submission is accepted, and a fresh pin waits for it);
6
+ // the SDK takes one while-in-use fix, evaluates the fence ON-DEVICE against
7
+ // the pin stored at capture, and posts a single per-day aggregate. Everything is best-effort: a denied permission, a missing pin, or
8
+ // a network fault returns a reason, never a throw — a presence report must
9
+ // never break the host app's startup path.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import * as Location from 'expo-location';
13
+ import { currentPosition } from '../services/location';
14
+ import { insideFence, localDayAndNight } from './math';
15
+ import { postObservations } from './post';
16
+ import { loadPresencePin } from './store';
17
+ import { awaitWatch, fetchWatchStatus, pinIsFresh } from './watch-wait';
18
+
19
+ export interface ReportPresenceOptions {
20
+ /** The org's PUBLISHABLE key (the same one the KYC flow mounts with). */
21
+ apiKey: string;
22
+ /** The org's user reference — must match the KYC flow's `userId`. */
23
+ externalUserId: string;
24
+ /** Dev-server override, exactly like the SDK config's `devUrl`. */
25
+ devUrl?: string;
26
+ }
27
+
28
+ export interface ReportPresenceResult {
29
+ reported: boolean;
30
+ /** Whether the fix landed inside the fence (null when nothing was reported). */
31
+ inside: boolean | null;
32
+ reason:
33
+ | 'reported'
34
+ | 'no_pin'
35
+ | 'services_off'
36
+ | 'no_fix'
37
+ | 'outside_fence'
38
+ /** Nothing is monitoring this user right now, so a report would be dropped. */
39
+ | 'no_watch'
40
+ | 'network_error';
41
+ }
42
+
43
+ export async function reportAddressPresence(
44
+ options: ReportPresenceOptions,
45
+ ): Promise<ReportPresenceResult> {
46
+ const pin = loadPresencePin(options.externalUserId);
47
+ if (!pin) return { reported: false, inside: null, reason: 'no_pin' };
48
+
49
+ // The phone's location toggle, checked before the permission dance: off,
50
+ // every fix fails, and `no_fix` told the host nothing about why.
51
+ const services = await Location.hasServicesEnabledAsync().catch(() => true);
52
+ if (!services) return { reported: false, inside: null, reason: 'services_off' };
53
+
54
+ const fix = await currentPosition();
55
+ if (!fix) return { reported: false, inside: null, reason: 'no_fix' };
56
+
57
+ const inside = insideFence(pin, fix);
58
+ // An outside fix is NOT evidence of absence (people go to work) — the server
59
+ // scores presence, never absence — so there is nothing worth sending.
60
+ if (!inside && fix.mocked !== true) {
61
+ return { reported: false, inside: false, reason: 'outside_fence' };
62
+ }
63
+
64
+ // The watch is minted seconds after a submission is accepted, and the
65
+ // ingest drops a report that arrives before it (watch-wait.ts).
66
+ const watch = await awaitWatch(pinIsFresh(pin), {
67
+ fetchStatus: () => fetchWatchStatus(options.apiKey, options.devUrl, options.externalUserId),
68
+ });
69
+ if (watch === 'absent') return { reported: false, inside, reason: 'no_watch' };
70
+
71
+ const { day, nightPresent } = localDayAndNight();
72
+ // One wire path for both tiers (post.ts) — the request shape cannot fork.
73
+ const ok = await postObservations(options.apiKey, options.devUrl, options.externalUserId, [
74
+ {
75
+ day,
76
+ source: 'foreground',
77
+ dwellMinutes: 0,
78
+ nightPresent,
79
+ samples: 1,
80
+ // A mocked fix is REPORTED, flagged — evidence OF fraud is worth
81
+ // more to the watch than silence.
82
+ ...(fix.mocked === true ? { integrity: { mockLocation: true } } : {}),
83
+ },
84
+ ]);
85
+ if (!ok) return { reported: false, inside, reason: 'network_error' };
86
+ return { reported: true, inside, reason: 'reported' };
87
+ }
@@ -0,0 +1,110 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Pure state machine for the foreground-service tier. A geofence hands us
3
+ // ENTER/EXIT moments; a periodic location sample hands us POSITIONS, and the
4
+ // job here is to turn positions back into the same enter/exit spans the
5
+ // geofence tier folds, on the SAME stored `enterAt`, so the two tiers
6
+ // cooperate on one state rather than double-counting a stay:
7
+ //
8
+ // inside, no open stay → open one (stamp enterAt)
9
+ // inside, open stay → nothing (the fence or an earlier sample did it)
10
+ // outside, open stay → close it: fold the span into per-day aggregates
11
+ // outside, no open stay → nothing (absence is never evidence)
12
+ // mocked → report the day FLAGGED, never open a stay
13
+ //
14
+ // Why this exists at all: on phones whose manufacturers kill background work
15
+ // (the Tecno/Infinix/Xiaomi population that dominates our markets), geofence
16
+ // transitions are dropped, silently. A foreground service keeps the process
17
+ // alive and hands it fixes every few minutes; folding those through the same
18
+ // span logic is what makes verification finish on those devices.
19
+ //
20
+ // Mirrors the Flutter plugin's PresenceSampler.kt — keep the two in lockstep.
21
+ // ---------------------------------------------------------------------------
22
+
23
+ import { foldSpanIntoDays } from './background-math';
24
+ import { insideFence, localDayAndNight } from './math';
25
+ import type { WireObservation } from './post';
26
+
27
+ export interface SampleFix {
28
+ lat: number;
29
+ lng: number;
30
+ accuracy: number | null;
31
+ timestamp: number;
32
+ mocked: boolean | null;
33
+ }
34
+
35
+ export interface SamplerResult {
36
+ /** The open stay after these samples (null = none open). */
37
+ enterAt: number | null;
38
+ /** Per-day aggregates to queue (same-day entries already merged). */
39
+ observations: WireObservation[];
40
+ }
41
+
42
+ /** Merge day aggregates that landed on the same day (several spans a day):
43
+ * sum dwell, OR night, sum samples. The geofence flush uses the same rule. */
44
+ export function mergeObservations(
45
+ existing: WireObservation[],
46
+ fresh: WireObservation[],
47
+ ): WireObservation[] {
48
+ const byDay = new Map(existing.map((o) => [o.day, { ...o }]));
49
+ for (const o of fresh) {
50
+ const prior = byDay.get(o.day);
51
+ if (!prior) {
52
+ byDay.set(o.day, { ...o });
53
+ continue;
54
+ }
55
+ prior.dwellMinutes += o.dwellMinutes;
56
+ prior.nightPresent = prior.nightPresent || o.nightPresent;
57
+ prior.samples += o.samples;
58
+ if (o.integrity) prior.integrity = { ...prior.integrity, ...o.integrity };
59
+ }
60
+ return [...byDay.values()];
61
+ }
62
+
63
+ /**
64
+ * Apply a batch of fixes (any order; sorted here) to the open-stay state.
65
+ * `offsetMinutes` is the device's UTC offset for the fold; it defaults to the
66
+ * device's own, and is a parameter only so the maths is testable in any TZ.
67
+ */
68
+ export function applyLocationSamples(
69
+ pin: { lat: number; lng: number },
70
+ samples: ReadonlyArray<SampleFix>,
71
+ enterAt: number | null,
72
+ offsetMinutes?: number,
73
+ ): SamplerResult {
74
+ let open = enterAt;
75
+ let observations: WireObservation[] = [];
76
+ const ordered = [...samples]
77
+ .filter((s) => Number.isFinite(s.timestamp))
78
+ .sort((a, b) => a.timestamp - b.timestamp);
79
+
80
+ for (const fix of ordered) {
81
+ if (fix.mocked === true) {
82
+ const { day, nightPresent } = localDayAndNight(new Date(fix.timestamp));
83
+ observations = mergeObservations(observations, [
84
+ {
85
+ day,
86
+ source: 'geofence',
87
+ dwellMinutes: 0,
88
+ nightPresent,
89
+ samples: 1,
90
+ integrity: { mockLocation: true },
91
+ },
92
+ ]);
93
+ continue;
94
+ }
95
+ const inside = insideFence(pin, fix);
96
+ if (inside) {
97
+ if (open == null) open = fix.timestamp;
98
+ continue;
99
+ }
100
+ if (open == null) continue;
101
+ const days = foldSpanIntoDays(open, fix.timestamp, offsetMinutes);
102
+ open = null;
103
+ if (days.length === 0) continue;
104
+ observations = mergeObservations(
105
+ observations,
106
+ days.map((d) => ({ ...d, source: 'geofence' as const, samples: 1 })),
107
+ );
108
+ }
109
+ return { enterAt: open, observations };
110
+ }
@@ -0,0 +1,92 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Tier visibility + recovery. A revoked permission silently downgrades the
3
+ // presence tier, and "silently" is the defect: the host app cannot ask the
4
+ // person to restore what it does not know is gone. presenceStatus() answers
5
+ // "which tier is actually running for this user?", and openLocationSettings()
6
+ // is the only honest recovery path — neither OS allows re-prompting in-app
7
+ // after a denial, so the road back runs through Settings.
8
+ //
9
+ // The phone's LOCATION SERVICES toggle is checked as well as the permissions.
10
+ // Permission granted with the toggle off produced `no_fix` on every report
11
+ // and nothing said why; OkHi's integration guidance calls this out for the
12
+ // same reason. It is a first-class input to the tier (tier.ts).
13
+ // ---------------------------------------------------------------------------
14
+
15
+ import { Linking, Platform } from 'react-native';
16
+ import * as Location from 'expo-location';
17
+ import { foregroundServiceRunning } from './foreground-service';
18
+ import { geofenceArmed } from './geofence';
19
+ import { loadPresencePin } from './store';
20
+ import { resolvePresenceTier, type PermissionState, type PresenceTier } from './tier';
21
+
22
+ export type { PresenceTier } from './tier';
23
+
24
+ export interface PresenceStatus {
25
+ /** The tier that is ACTUALLY running, not the one that was asked for. */
26
+ tier: PresenceTier;
27
+ /** Whether a pin is stored for this user (without one, no tier can run). */
28
+ pinStored: boolean;
29
+ /** Whether the stored pin is the always-on arrangement. */
30
+ alwaysOn: boolean;
31
+ /** The phone's location services switch. Off, nothing can run whatever
32
+ * the permissions say; `openLocationSettings('services')` is the road back. */
33
+ locationServicesEnabled: boolean;
34
+ foregroundPermission: PermissionState;
35
+ backgroundPermission: PermissionState;
36
+ /** The geofence is registered with the OS right now. */
37
+ geofenceArmed: boolean;
38
+ /** The Android foreground service is running right now (always false on iOS). */
39
+ foregroundServiceRunning: boolean;
40
+ }
41
+
42
+ function normalise(status: string | undefined): PermissionState {
43
+ if (status === 'granted') return 'granted';
44
+ if (status === 'denied') return 'denied';
45
+ return 'undetermined';
46
+ }
47
+
48
+ export async function presenceStatus(externalUserId: string): Promise<PresenceStatus> {
49
+ const pin = loadPresencePin(externalUserId);
50
+ const [fg, bg, armed, services, service] = await Promise.all([
51
+ Location.getForegroundPermissionsAsync().catch(() => null),
52
+ Location.getBackgroundPermissionsAsync().catch(() => null),
53
+ geofenceArmed(),
54
+ // An unanswerable check reads as ON: the permissions below still gate,
55
+ // and a false "off" would send people to Settings for nothing.
56
+ Location.hasServicesEnabledAsync().catch(() => true),
57
+ foregroundServiceRunning(),
58
+ ]);
59
+ const inputs = {
60
+ pinStored: pin != null,
61
+ locationServicesEnabled: services,
62
+ foregroundPermission: normalise(fg?.status),
63
+ backgroundPermission: normalise(bg?.status),
64
+ geofenceArmed: armed,
65
+ foregroundServiceRunning: service,
66
+ };
67
+ return {
68
+ tier: resolvePresenceTier(inputs),
69
+ alwaysOn: pin?.alwaysOn === true,
70
+ ...inputs,
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Deep-link to Settings — the only road back after a denial or a switched-off
76
+ * toggle. `'app'` (default) opens the app's own settings page (permissions);
77
+ * `'services'` opens the phone's location-services screen on Android, which
78
+ * is where the toggle lives (iOS has no such deep link, so it falls back to
79
+ * the app page). Never throws; a host may call it straight from a button.
80
+ */
81
+ export async function openLocationSettings(target: 'app' | 'services' = 'app'): Promise<void> {
82
+ try {
83
+ if (target === 'services' && Platform.OS === 'android') {
84
+ await Linking.sendIntent('android.settings.LOCATION_SOURCE_SETTINGS');
85
+ return;
86
+ }
87
+ await Linking.openSettings();
88
+ } catch {
89
+ // Nothing to do: the OS refused, and the host's copy already told the
90
+ // person where to go by hand.
91
+ }
92
+ }
@@ -0,0 +1,94 @@
1
+ // ---------------------------------------------------------------------------
2
+ // The on-device pin store. When a workflow enables presence verification, the
3
+ // captured pin is saved LOCALLY (keyed by the org's user reference) so later
4
+ // app opens can evaluate "am I at the address?" without the coordinates ever
5
+ // leaving the phone. A small JSON file in the app's document directory via
6
+ // expo-file-system — loaded through the SDK's optional-module pattern, so a
7
+ // host app without the module simply has no presence tier (never a crash).
8
+ // ---------------------------------------------------------------------------
9
+
10
+ import { readJsonFile, writeJsonFile } from './fs';
11
+
12
+ export interface StoredPin {
13
+ lat: number;
14
+ lng: number;
15
+ savedAt: string;
16
+ /** Always-on monitoring: the pin lives as long as the arrangement does
17
+ * (cleared only by clearPresencePin — revoke or sign-out), because the
18
+ * server keeps renewing the watch and reports must keep flowing. */
19
+ alwaysOn?: boolean;
20
+ }
21
+
22
+ const FILE_NAME = 'myaza-kyc-presence.json';
23
+
24
+ /**
25
+ * How long a stored pin may drive reports. The watch it feeds resolves within
26
+ * its policy window (30 days at the longest) and the server discards reports
27
+ * for a resolved watch anyway — but the DEVICE kept sampling location on
28
+ * every app open forever, for a check that had finished. The server cannot
29
+ * say "stop" without breaking the ingest endpoint's enumeration safety (an
30
+ * unknown user and a resolved watch must answer identically), so the bound
31
+ * lives here: longest window plus resolution slack, then the pin self-expires
32
+ * and the reporter goes quiet before ever touching the GPS.
33
+ */
34
+ export const PIN_TTL_DAYS = 45;
35
+
36
+ export function pinExpired(pin: StoredPin, nowMs: number = Date.now()): boolean {
37
+ // An always-on pin has no end date by design (the OkHi model): monitoring
38
+ // continues until revoked, and the TTL below exists only for BOUNDED
39
+ // watches whose purpose has a deadline.
40
+ if (pin.alwaysOn === true) return false;
41
+ const saved = Date.parse(pin.savedAt);
42
+ // An unparseable stamp is treated as expired: both platforms have always
43
+ // written savedAt, so a missing one is corruption, and corrupt entries must
44
+ // age out rather than report forever.
45
+ if (Number.isNaN(saved)) return true;
46
+ // Strictly past the TTL — the Flutter mirror compares the same way.
47
+ return nowMs - saved > PIN_TTL_DAYS * 24 * 60 * 60 * 1000;
48
+ }
49
+
50
+ function readAll(): Record<string, StoredPin> {
51
+ return readJsonFile(FILE_NAME) as Record<string, StoredPin>;
52
+ }
53
+
54
+ function writeAll(pins: Record<string, StoredPin>): void {
55
+ writeJsonFile(FILE_NAME, pins as Record<string, unknown>);
56
+ }
57
+
58
+ /** Saves the captured pin for later foreground reports. Never throws. */
59
+ export function savePresencePin(
60
+ externalUserId: string,
61
+ pin: { lat: number; lng: number },
62
+ opts?: { alwaysOn?: boolean },
63
+ ): void {
64
+ if (!externalUserId) return;
65
+ const pins = readAll();
66
+ pins[externalUserId] = {
67
+ lat: pin.lat,
68
+ lng: pin.lng,
69
+ savedAt: new Date().toISOString(),
70
+ ...(opts?.alwaysOn === true ? { alwaysOn: true } : {}),
71
+ };
72
+ writeAll(pins);
73
+ }
74
+
75
+ /** The stored pin for a user, or null (no store / never captured here /
76
+ * aged out — an expired pin is cleared on the way through). */
77
+ export function loadPresencePin(externalUserId: string): StoredPin | null {
78
+ const pin = readAll()[externalUserId];
79
+ if (!pin || typeof pin.lat !== 'number' || typeof pin.lng !== 'number') return null;
80
+ if (pinExpired(pin)) {
81
+ clearPresencePin(externalUserId);
82
+ return null;
83
+ }
84
+ return pin;
85
+ }
86
+
87
+ /** Drops a stored pin (e.g. after a watch resolves or the user signs out). */
88
+ export function clearPresencePin(externalUserId: string): void {
89
+ const pins = readAll();
90
+ if (externalUserId in pins) {
91
+ delete pins[externalUserId];
92
+ writeAll(pins);
93
+ }
94
+ }
@@ -0,0 +1,36 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Which presence tier is ACTUALLY running, as one pure decision — so the
3
+ // answer presenceStatus() gives can be pinned without a device, and so the
4
+ // Flutter mirror (presence_tier.dart) can be held to the same table.
5
+ //
6
+ // The location-services toggle sits ABOVE every permission: with services
7
+ // off, a granted permission and an armed fence produce no fix and no
8
+ // transition, so nothing is running whatever the grants say. That was the
9
+ // silent case — permission granted, toggle off, `no_fix` forever — and it is
10
+ // why the switch is a first-class input here rather than folded into one of
11
+ // the permission states.
12
+ // ---------------------------------------------------------------------------
13
+
14
+ export type PresenceTier = 'background' | 'foreground' | 'none';
15
+
16
+ export type PermissionState = 'granted' | 'denied' | 'undetermined';
17
+
18
+ export interface TierInputs {
19
+ pinStored: boolean;
20
+ locationServicesEnabled: boolean;
21
+ foregroundPermission: PermissionState;
22
+ backgroundPermission: PermissionState;
23
+ /** The OS geofence is registered right now. */
24
+ geofenceArmed: boolean;
25
+ /** The Android foreground service is running right now. */
26
+ foregroundServiceRunning: boolean;
27
+ }
28
+
29
+ export function resolvePresenceTier(i: TierInputs): PresenceTier {
30
+ if (!i.pinStored || !i.locationServicesEnabled) return 'none';
31
+ if (i.backgroundPermission === 'granted' && (i.geofenceArmed || i.foregroundServiceRunning)) {
32
+ return 'background';
33
+ }
34
+ if (i.foregroundPermission === 'granted') return 'foreground';
35
+ return 'none';
36
+ }
@@ -0,0 +1,81 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Waiting for the watch. The server mints an AddressWatch in the post-terminal
3
+ // hook chain, seconds AFTER a submission is accepted, and its ingest is
4
+ // enumeration-safe by contract: an observation for a user with no live watch
5
+ // answers `accepted: 0` exactly as an unknown user would, and is dropped. So
6
+ // a report made the moment onSubmit fires — the natural place for a host to
7
+ // make one — landed on nothing (iPhone + S24, 2026-09-07: three watches in a
8
+ // row lapsed INCONCLUSIVE with zero observations while both phones sat at the
9
+ // pin). The reporter therefore asks where the watch stands before it posts,
10
+ // and when the pin was captured minutes ago it WAITS for the watch to appear,
11
+ // bounded, rather than posting into the gap. Mirrors the Flutter SDK's
12
+ // presence_watch_wait.dart — keep the two in lockstep.
13
+ // ---------------------------------------------------------------------------
14
+
15
+ import { resolveBaseUrl } from '../services/resolveUrl';
16
+
17
+ /** A pin saved this recently was captured by a flow whose watch may still be minting. */
18
+ export const FRESH_PIN_MS = 15 * 60 * 1000;
19
+ /** How long a submit-time report waits for its watch before giving up. */
20
+ export const WATCH_WAIT_MS = 90 * 1000;
21
+ export const WATCH_POLL_MS = 3 * 1000;
22
+
23
+ export type WatchPresence = 'live' | 'absent' | 'unknown';
24
+
25
+ export function pinIsFresh(pin: { savedAt: string }, nowMs: number = Date.now()): boolean {
26
+ const saved = Date.parse(pin.savedAt);
27
+ return !Number.isNaN(saved) && nowMs - saved <= FRESH_PIN_MS;
28
+ }
29
+
30
+ /** The server's public status for the user's watch, or null when it could not be read. */
31
+ export async function fetchWatchStatus(
32
+ apiKey: string,
33
+ devUrl: string | undefined,
34
+ externalUserId: string,
35
+ ): Promise<string | null> {
36
+ try {
37
+ const base = resolveBaseUrl(apiKey, devUrl);
38
+ const response = await fetch(
39
+ `${base}/api/kyc/address/presence/${encodeURIComponent(externalUserId)}`,
40
+ { headers: { Authorization: `Bearer ${apiKey}` } },
41
+ );
42
+ if (!response.ok) return null;
43
+ const body = (await response.json()) as { status?: unknown };
44
+ return typeof body.status === 'string' ? body.status : null;
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ export interface AwaitWatchDeps {
51
+ fetchStatus: () => Promise<string | null>;
52
+ sleep?: (ms: number) => Promise<void>;
53
+ now?: () => number;
54
+ waitMs?: number;
55
+ pollMs?: number;
56
+ }
57
+
58
+ const realSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
59
+
60
+ /**
61
+ * Whether a live watch exists to receive a report. Only `in_progress` is
62
+ * live: a resolved cycle, or none at all, drops what is posted. An
63
+ * unreadable status is `unknown`, and the post goes ahead — a network doubt
64
+ * must not silence a report the server might accept. A FRESH pin changes the
65
+ * rule: its watch is probably still being minted (or the previous cycle has
66
+ * just lapsed and the new one is about to replace it), so the status is
67
+ * re-read until it turns live or the wait runs out.
68
+ */
69
+ export async function awaitWatch(fresh: boolean, deps: AwaitWatchDeps): Promise<WatchPresence> {
70
+ const sleep = deps.sleep ?? realSleep;
71
+ const now = deps.now ?? Date.now;
72
+ const deadline = now() + (deps.waitMs ?? WATCH_WAIT_MS);
73
+ const pollMs = deps.pollMs ?? WATCH_POLL_MS;
74
+ for (;;) {
75
+ const status = await deps.fetchStatus();
76
+ if (status === 'in_progress') return 'live';
77
+ if (!fresh) return status === null ? 'unknown' : 'absent';
78
+ if (now() >= deadline) return status === null ? 'unknown' : 'absent';
79
+ await sleep(pollMs);
80
+ }
81
+ }