@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Runs the wallet monitor's pass loop under a watchdog.
3
+ *
4
+ * `Monitor.startTasks()` is `while (running) { await runOnce(); await wait }`.
5
+ * Two things end that loop with no signal to anyone:
6
+ *
7
+ * · a task whose `await` never resolves — runOnce runs tasks sequentially
8
+ * with no per-task timeout, so one hung network or SQLite call parks every
9
+ * other task behind it, TaskSendWaiting included;
10
+ * · `runOnce`'s own catch block calling `logEvent`, which is a SQLite write —
11
+ * if that throws, the error escapes `startTasks` and the loop is gone.
12
+ *
13
+ * Seen 2026-09-18: Clock ticks stopped at 13:29:01 while the app stayed in
14
+ * use; two ordinary BSV sends made minutes later sat at `sending` until the
15
+ * app was force-quit, because nothing but the monitor broadcasts an `unsent`
16
+ * request.
17
+ *
18
+ * So the loop is driven from here instead. Each completed pass stamps
19
+ * `lastPassAt`; the host polls `isStalled` and calls `restart`, which starts a
20
+ * new generation of the loop on the SAME monitor. The old generation, if its
21
+ * hung await ever resolves, sees the generation change and exits rather than
22
+ * running alongside the new one. A pass that throws is logged and does not end
23
+ * the loop.
24
+ *
25
+ * `_tasksRunning` and `_tasksRunningPromise` are kept in step with what
26
+ * `Monitor.startTasks` would have set, because `stopTasks()` clears the first
27
+ * and `stopMonitorAndDrain` awaits the second.
28
+ */
29
+ import type { Monitor } from '@bsv/wallet-toolbox-mobile'
30
+
31
+ /** No completed pass for this long, while the app is active, means the loop is gone. */
32
+ export const MONITOR_STALL_MS = 120_000
33
+
34
+ /** The private loop state the toolbox's own `startTasks` maintains. */
35
+ interface LoopState {
36
+ _tasksRunning: boolean
37
+ _tasksRunningPromise?: Promise<void>
38
+ resolveCompletion?: () => void
39
+ runOnce(): Promise<void>
40
+ options: { taskRunWaitMsecs: number }
41
+ }
42
+
43
+ export class MonitorSupervisor {
44
+ /** When the most recent pass completed (or the loop was started/touched). */
45
+ lastPassAt: number
46
+ /** How many times `restart` has run. Exposed for logging and tests. */
47
+ restarts = 0
48
+ private generation = 0
49
+ private monitor: Monitor | undefined
50
+
51
+ constructor(
52
+ private readonly now: () => number = () => Date.now(),
53
+ private readonly wait: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms)),
54
+ private readonly warn: (message: string, error?: unknown) => void = (m, e) => console.warn(m, e ?? '')
55
+ ) {
56
+ this.lastPassAt = this.now()
57
+ }
58
+
59
+ /** Begin driving `monitor`. Replaces `monitor.startTasks()`; never awaited. */
60
+ start(monitor: Monitor): void {
61
+ this.monitor = monitor
62
+ const state = monitor as unknown as LoopState
63
+ state._tasksRunning = true
64
+ state._tasksRunningPromise = new Promise<void>(resolve => {
65
+ state.resolveCompletion = resolve
66
+ })
67
+ this.lastPassAt = this.now()
68
+ void this.loop(state, ++this.generation)
69
+ }
70
+
71
+ /**
72
+ * Something else proves the loop is not stalled — the app just came back to
73
+ * the foreground and the loop's timers were frozen with it. Resets the clock
74
+ * so the first watchdog check after a resume cannot fire on a gap that was
75
+ * the OS's, not the monitor's.
76
+ */
77
+ touch(): void {
78
+ this.lastPassAt = this.now()
79
+ }
80
+
81
+ isStalled(stallMs: number = MONITOR_STALL_MS): boolean {
82
+ const state = this.monitor as unknown as LoopState | undefined
83
+ if (!state?._tasksRunning) return false
84
+ return this.now() - this.lastPassAt > stallMs
85
+ }
86
+
87
+ /**
88
+ * Start a new generation of the loop on the current monitor. The stalled
89
+ * generation is abandoned: when (if) its await resolves it exits on the
90
+ * generation check. Returns false when there is no running monitor to restart.
91
+ */
92
+ restart(): boolean {
93
+ const state = this.monitor as unknown as LoopState | undefined
94
+ if (!state?._tasksRunning) return false
95
+ this.restarts++
96
+ this.lastPassAt = this.now()
97
+ void this.loop(state, ++this.generation)
98
+ return true
99
+ }
100
+
101
+ private async loop(state: LoopState, generation: number): Promise<void> {
102
+ while (state._tasksRunning && generation === this.generation) {
103
+ try {
104
+ await state.runOnce()
105
+ } catch (e) {
106
+ // The toolbox loop dies here. A failed pass is a failed pass; the next
107
+ // one runs.
108
+ this.warn('[MonitorSupervisor] monitor pass failed', e)
109
+ }
110
+ if (generation !== this.generation) return
111
+ this.lastPassAt = this.now()
112
+ await this.wait(state.options.taskRunWaitMsecs)
113
+ }
114
+ // Only the live generation may report completion: an abandoned one waking
115
+ // up late must not resolve a drain that belongs to its successor.
116
+ if (generation === this.generation && state.resolveCompletion) {
117
+ state.resolveCompletion()
118
+ state.resolveCompletion = undefined
119
+ }
120
+ }
121
+ }
@@ -13,7 +13,7 @@
13
13
  * a pass takes at most one chunk and the interval floor keeps it off the JS thread the rest
14
14
  * of the time.
15
15
  */
16
- import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
16
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile'
17
17
  import type { Monitor } from '@bsv/wallet-toolbox-mobile'
18
18
  import { MIN_PUSH_INTERVAL_MS } from '../backup/constants'
19
19
  import type { PushResult } from '../backup/push'
@@ -50,6 +50,11 @@ export class TaskBackupPush extends WalletMonitorTask {
50
50
  static lastError: string | undefined
51
51
  /** Time of the last successful pass, for the backup-health display. */
52
52
  static lastSuccessAt: number | undefined
53
+ /** A push pass is in flight. Guards against MonitorSupervisor's watchdog
54
+ * restart overlapping an old generation's still-running runOnce() with a
55
+ * new generation's — without this, both could concurrently push the same
56
+ * backup log (XR-105; same pattern as TaskDrainOutbox.running). */
57
+ static running = false
53
58
 
54
59
  static noteConnectivity (online: boolean): void {
55
60
  TaskBackupPush.onlineNow = online
@@ -95,6 +100,7 @@ export class TaskBackupPush extends WalletMonitorTask {
95
100
  TaskBackupPush.backoffMs = TaskBackupPush.BASE_BACKOFF_MS
96
101
  TaskBackupPush.lastError = undefined
97
102
  TaskBackupPush.lastSuccessAt = undefined
103
+ TaskBackupPush.running = false
98
104
  }
99
105
 
100
106
  constructor (
@@ -115,6 +121,12 @@ export class TaskBackupPush extends WalletMonitorTask {
115
121
  }
116
122
 
117
123
  async runTask (): Promise<string> {
124
+ // A watchdog restart can spawn a new generation's runOnce() while an old
125
+ // generation's own runOnce() is still executing (it is not cancelled,
126
+ // only stopped from looping again). Without this guard both could
127
+ // concurrently push the same backup log (XR-105).
128
+ if (TaskBackupPush.running) return ''
129
+ TaskBackupPush.running = true
118
130
  TaskBackupPush.checkNow = false
119
131
  const startedAt = Date.now()
120
132
 
@@ -163,6 +175,8 @@ export class TaskBackupPush extends WalletMonitorTask {
163
175
  TaskBackupPush.lastError = message
164
176
  TaskBackupPush.noteFailure(startedAt)
165
177
  return `backup: push failed, retrying after ${TaskBackupPush.backoffMs}ms: ${message}`
178
+ } finally {
179
+ TaskBackupPush.running = false
166
180
  }
167
181
  }
168
182
  }
@@ -11,7 +11,7 @@
11
11
  * and rebuilt on network switches and wallet rebuilds, and a pending inbox
12
12
  * must survive that.
13
13
  */
14
- import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
14
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile'
15
15
  import type { Monitor } from '@bsv/wallet-toolbox-mobile'
16
16
 
17
17
  export interface CreditInboxTaskResult {
@@ -11,7 +11,7 @@
11
11
  * and rebuilt on network switches and wallet rebuilds, and a pending outbox
12
12
  * must survive that.
13
13
  */
14
- import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
14
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile'
15
15
  import type { Monitor } from '@bsv/wallet-toolbox-mobile'
16
16
  import type { OutboxEntry } from '../peerpay/outbox'
17
17
 
@@ -48,6 +48,11 @@ export class TaskDrainOutbox extends WalletMonitorTask {
48
48
  static hasPending = false
49
49
  static backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
50
50
  static nextDueAt = 0
51
+ /** A drain pass is in flight. Guards against MonitorSupervisor's watchdog
52
+ * restart overlapping an old generation's still-running runOnce() with a
53
+ * new generation's — without this, both could concurrently retry the same
54
+ * outbox entry (reviews/misc-p2.md misc-p2-08). */
55
+ static running = false
51
56
 
52
57
  static noteConnectivity(online: boolean): void {
53
58
  TaskDrainOutbox.onlineNow = online
@@ -77,6 +82,7 @@ export class TaskDrainOutbox extends WalletMonitorTask {
77
82
  TaskDrainOutbox.hasPending = false
78
83
  TaskDrainOutbox.backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
79
84
  TaskDrainOutbox.nextDueAt = 0
85
+ TaskDrainOutbox.running = false
80
86
  }
81
87
 
82
88
  constructor(
@@ -102,6 +108,12 @@ export class TaskDrainOutbox extends WalletMonitorTask {
102
108
  }
103
109
 
104
110
  async runTask(): Promise<string> {
111
+ // A watchdog restart can spawn a new generation's runOnce() while an old
112
+ // generation's own runOnce() is still executing (it is not cancelled,
113
+ // only stopped from looping again). Without this guard both could
114
+ // concurrently retry the same outbox entry.
115
+ if (TaskDrainOutbox.running) return ''
116
+ TaskDrainOutbox.running = true
105
117
  TaskDrainOutbox.checkNow = false
106
118
  try {
107
119
  const r = await this.drain()
@@ -117,6 +129,8 @@ export class TaskDrainOutbox extends WalletMonitorTask {
117
129
  } catch (e) {
118
130
  this.scheduleRetry()
119
131
  return `DrainOutbox failed: ${e instanceof Error ? e.message : String(e)}\n`
132
+ } finally {
133
+ TaskDrainOutbox.running = false
120
134
  }
121
135
  }
122
136
  }
@@ -19,7 +19,7 @@
19
19
  * reports online seconds before routes actually work — which is exactly the
20
20
  * "payments sit at nosend forever" bug this rewrite removes.
21
21
  */
22
- import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
22
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile'
23
23
  import type { Monitor } from '@bsv/wallet-toolbox-mobile'
24
24
  import type { ProcessOfflineActionsResult } from '../storage/methods/processOfflineActions'
25
25
 
@@ -42,6 +42,11 @@ export class TaskSendOffline extends WalletMonitorTask {
42
42
  * alone will not help, and nothing else in the system records it.
43
43
  */
44
44
  static lastStall: string | undefined
45
+ /** A release pass is in flight. Guards against MonitorSupervisor's watchdog
46
+ * restart overlapping an old generation's still-running runOnce() with a
47
+ * new generation's — without this, both could concurrently release the
48
+ * same offline queue (XR-105; same pattern as TaskDrainOutbox.running). */
49
+ static running = false
45
50
 
46
51
  static noteConnectivity(online: boolean): void {
47
52
  TaskSendOffline.onlineNow = online
@@ -73,6 +78,7 @@ export class TaskSendOffline extends WalletMonitorTask {
73
78
  TaskSendOffline.backoffMs = TaskSendOffline.BASE_BACKOFF_MS
74
79
  TaskSendOffline.nextDueAt = 0
75
80
  TaskSendOffline.lastStall = undefined
81
+ TaskSendOffline.running = false
76
82
  }
77
83
 
78
84
  constructor(
@@ -97,6 +103,12 @@ export class TaskSendOffline extends WalletMonitorTask {
97
103
  }
98
104
 
99
105
  async runTask(): Promise<string> {
106
+ // A watchdog restart can spawn a new generation's runOnce() while an old
107
+ // generation's own runOnce() is still executing (it is not cancelled,
108
+ // only stopped from looping again). Without this guard both could
109
+ // concurrently release the same offline queue (XR-105).
110
+ if (TaskSendOffline.running) return ''
111
+ TaskSendOffline.running = true
100
112
  TaskSendOffline.checkNow = false
101
113
  try {
102
114
  const r = await this.release()
@@ -118,6 +130,8 @@ export class TaskSendOffline extends WalletMonitorTask {
118
130
  // a failed drain, so it earns a retry rather than silence.
119
131
  this.scheduleRetry()
120
132
  return `SendOffline failed: ${e instanceof Error ? e.message : String(e)}\n`
133
+ } finally {
134
+ TaskSendOffline.running = false
121
135
  }
122
136
  }
123
137
  }
@@ -14,6 +14,8 @@
14
14
  * retry, a wrong "offline" hides the online rails from someone who has signal.
15
15
  */
16
16
  import NetInfo from '@react-native-community/netinfo'
17
+ import { DEFAULT_MESSAGEBOX_URL } from '../config'
18
+ import { DEFAULT_ARC_URLS } from '../constants'
17
19
 
18
20
  export interface OnlineState {
19
21
  isConnected: boolean | null
@@ -32,3 +34,50 @@ export async function getOnline(): Promise<boolean> {
32
34
  export function subscribeOnline(cb: (online: boolean) => void): () => void {
33
35
  return NetInfo.addEventListener(state => cb(isOnlineState(state)))
34
36
  }
37
+
38
+ /** Longest a live request may take before it counts as "nothing got out". */
39
+ export const PROBE_TIMEOUT_MS = 4000
40
+
41
+ /**
42
+ * Hosts the wallet already talks to, so asking them adds no third party and no
43
+ * new traffic pattern. HTTPS, so a captive portal cannot answer for them.
44
+ */
45
+ const PROBE_URLS = [DEFAULT_ARC_URLS.main, DEFAULT_MESSAGEBOX_URL]
46
+
47
+ /**
48
+ * A live request, for when NetInfo's verdict is offline and something needs to
49
+ * know whether to believe it.
50
+ *
51
+ * That verdict is not a measurement of the moment. On iOS it is a cached
52
+ * reachability snapshot — the OS delivers no callbacks while the app is
53
+ * suspended, and NetInfo's cache is never re-read — plus an HTTP probe of a
54
+ * Google host the wallet has no other use for. Either can say offline for a
55
+ * device whose connection works, and NetInfo will not correct itself until the
56
+ * next network change. This asks the wallet's own hosts instead: any HTTP
57
+ * response, a 404 included, proves DNS, a route and TLS all worked, so one
58
+ * answer from any host is enough. It only ever upgrades a verdict to online,
59
+ * never the reverse.
60
+ */
61
+ export function probeOnline(timeoutMs: number = PROBE_TIMEOUT_MS): Promise<boolean> {
62
+ return new Promise(resolve => {
63
+ const controller = new AbortController()
64
+ let failed = 0
65
+ const finish = (online: boolean) => {
66
+ clearTimeout(timer)
67
+ controller.abort()
68
+ resolve(online)
69
+ }
70
+ const timer = setTimeout(() => finish(false), timeoutMs)
71
+ for (const url of PROBE_URLS) {
72
+ Promise.resolve()
73
+ .then(() => fetch(url, { method: 'HEAD', cache: 'no-store', credentials: 'omit', signal: controller.signal }))
74
+ .then(
75
+ () => finish(true),
76
+ () => {
77
+ failed += 1
78
+ if (failed === PROBE_URLS.length) finish(false)
79
+ }
80
+ )
81
+ }
82
+ })
83
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Whether a URL is safe to hand to a native fetch/prefetch as a destination
3
+ * this app does not control.
4
+ *
5
+ * There is no synchronous DNS resolution available on this runtime, so this
6
+ * cannot catch a hostname that only *resolves* to a private address (DNS
7
+ * rebinding) — that needs a redirect/connect-time check on the platform's
8
+ * networking stack, which this codebase does not have. What it DOES catch,
9
+ * cheaply and up front, is the concrete class of report this closes: a
10
+ * foreign paymail registry, a user-typed trust-provider domain, or a search
11
+ * result that names a loopback/private/link-local address or IP literal
12
+ * directly (XR-073 / SEC2-057, SEC2-076). A hostname is otherwise accepted
13
+ * without being resolved — this is a floor, not a firewall.
14
+ */
15
+ const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
16
+
17
+ function isPrivateIPv4(host: string): boolean {
18
+ const m = IPV4.exec(host)
19
+ if (!m) return false
20
+ const parts = m.slice(1, 5).map(Number)
21
+ if (parts.some(n => n > 255)) return false
22
+ const [a, b] = parts
23
+ if (a === 127) return true // loopback
24
+ if (a === 10) return true // RFC1918
25
+ if (a === 172 && b >= 16 && b <= 31) return true // RFC1918
26
+ if (a === 192 && b === 168) return true // RFC1918
27
+ if (a === 169 && b === 254) return true // link-local
28
+ if (a === 100 && b >= 64 && b <= 127) return true // CGNAT (RFC6598)
29
+ if (a === 0) return true // "this network"
30
+ if (a >= 224) return true // multicast + reserved
31
+ return false
32
+ }
33
+
34
+ /** Also catches the bracketed literal a URL's `hostname` gives back, e.g. `[::1]`. */
35
+ function isPrivateIPv6(host: string): boolean {
36
+ const h = host.replace(/^\[|\]$/g, '').toLowerCase()
37
+ if (h === '::1' || h === '::') return true
38
+ if (h.startsWith('fe8') || h.startsWith('fe9') || h.startsWith('fea') || h.startsWith('feb')) return true // link-local fe80::/10
39
+ if (h.startsWith('fc') || h.startsWith('fd')) return true // unique local fc00::/7
40
+ // IPv4-mapped/compatible — judge the embedded address. A URL's `.hostname`
41
+ // canonicalises the literal to hex groups (`::ffff:a.b.c.d` becomes
42
+ // `::ffff:7f00:1`), so the last two 16-bit groups are read back as bytes
43
+ // rather than matched against the dotted form.
44
+ if (h.includes('ffff')) {
45
+ const groups = h.split(':')
46
+ const last = groups.slice(-2)
47
+ if (last.length === 2 && last.every(g => /^[0-9a-f]{1,4}$/.test(g))) {
48
+ const hi = parseInt(last[0], 16)
49
+ const lo = parseInt(last[1], 16)
50
+ const ipv4 = `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`
51
+ if (isPrivateIPv4(ipv4)) return true
52
+ }
53
+ }
54
+ return false
55
+ }
56
+
57
+ /**
58
+ * The address-class half of `isPublicHttpsUrl`, exposed on its own for
59
+ * validators that enforce a different scheme themselves (e.g. `wss://`
60
+ * relay URLs, or the `https://` pairing origin's own reserved-`.invalid`
61
+ * check) and only need "is this hostname loopback/private/link-local/
62
+ * reserved/a bare local-network literal" (XR-024 / SEC2-055). Takes a URL's
63
+ * already-punycoded `.hostname` — bracketed IPv6 included.
64
+ */
65
+ export function isPrivateNetworkHost(rawHost: string): boolean {
66
+ const host = rawHost.toLowerCase().replace(/\.$/, '')
67
+ if (!host) return true
68
+ if (host === 'localhost' || host.endsWith('.localhost')) return true
69
+ if (host === 'local' || host.endsWith('.local')) return true
70
+ if (host === 'internal' || host.endsWith('.internal')) return true
71
+ if (host.startsWith('[') || host.includes(':')) return isPrivateIPv6(host)
72
+ return isPrivateIPv4(host)
73
+ }
74
+
75
+ /**
76
+ * A parseable, credential-free `https://` URL whose host is not a loopback,
77
+ * private-use, link-local, CGNAT, multicast/reserved, or `.local`/`localhost`/
78
+ * `.internal` address. The path/query is not otherwise restricted — this is a
79
+ * host-class check, not a full origin policy.
80
+ */
81
+ export function isPublicHttpsUrl(raw: string): boolean {
82
+ let url: URL
83
+ try {
84
+ url = new URL(raw)
85
+ } catch {
86
+ return false
87
+ }
88
+ if (url.protocol !== 'https:') return false
89
+ if (url.username || url.password) return false
90
+ return !isPrivateNetworkHost(url.hostname)
91
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * XR-064: a custom ARC broadcast endpoint carries the signed transaction (and
3
+ * any configured API token) over the wire. Restrict it to https, with a
4
+ * narrow explicit exception for local development against a loopback
5
+ * broadcaster (http://localhost / http://127.0.0.1) — so an on-path
6
+ * attacker on a person-chosen plaintext host cannot observe the transaction
7
+ * and callback token, or return a bare success that suppresses the real
8
+ * HTTPS fallback chain, while the legitimate local-dev workflow keeps
9
+ * working.
10
+ */
11
+ export function validateArcUrl(url: string): boolean {
12
+ const trimmed = url.trim()
13
+ if (!trimmed) return true // empty clears the override back to the default
14
+ let parsed: URL
15
+ try {
16
+ parsed = new URL(trimmed)
17
+ } catch {
18
+ return false
19
+ }
20
+ if (parsed.protocol === 'https:') return true
21
+ return parsed.protocol === 'http:' && (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1')
22
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Which separators money is printed with: always the device's own locale.
3
+ */
4
+
5
+ /** The device's own locale, resolved once. */
6
+ function detectDeviceLocale(): string {
7
+ try {
8
+ return Intl.NumberFormat().resolvedOptions().locale?.split('-u-')[0] || 'en-US'
9
+ } catch {
10
+ return 'en-US'
11
+ }
12
+ }
13
+
14
+ const deviceLocale = detectDeviceLocale()
15
+
16
+ /** The locale every formatter in `amountFormatHelpers` prints through. */
17
+ export function getNumberLocale(): string {
18
+ return deviceLocale
19
+ }