@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
@@ -18,9 +18,8 @@
18
18
  * database reads, writes and logging, which is validated on device.
19
19
  */
20
20
  import { Beef } from '@bsv/sdk'
21
- import { attemptToPostReqsToNetwork } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/attemptToPostReqsToNetwork'
22
- import { EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/entities'
23
- import type { TableProvenTxReq, TableTransaction } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
21
+ import { attemptToPostReqsToNetwork, EntityProvenTx, EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile'
22
+ import type { TableProvenTxReq, TableTransaction } from '@bsv/wallet-toolbox-mobile'
24
23
  import type { StorageExpoSQLite } from '../StorageExpoSQLite'
25
24
  import { findOfflineActions, updateOfflineAction, type OfflineActionRow, type OfflineDb } from './offlineActions'
26
25
  import {
@@ -34,13 +33,7 @@ import {
34
33
  } from '../../offline/plan'
35
34
  import { descendantsOf, type OrderableTx } from '../../offline/order'
36
35
  import { postTokenStep, reconcileSettlements, type TokenFrameSource } from '../../mandala/drain'
37
- import type {
38
- AdmissionVerifier,
39
- CoverFn,
40
- SettlementStore,
41
- SubmitFn,
42
- TokenSettlementRow
43
- } from '../../mandala/types'
36
+ import type { AdmissionVerifier, CoverFn, SettlementStore, SubmitFn, TokenSettlementRow } from '../../mandala/types'
44
37
  import { devLog } from '../../logging'
45
38
  import { getOnline } from '../../net/online'
46
39
 
@@ -52,7 +45,13 @@ export const STALL_FOREIGN_ANCESTOR = 'offline_stall_foreign_ancestor'
52
45
  export interface ProcessOfflineActionsResult {
53
46
  /** Queue rows moved to 'sent'. A foreign ancestor's broadcast is logged, not counted. */
54
47
  sent: number
55
- /** Transactions whose local records were changed to record a rejection. */
48
+ /**
49
+ * Transactions whose local records were changed to record a rejection.
50
+ * Includes both a rejection this pass's own cascade decided and a stale
51
+ * 'sent' row this pass reconciled against a since-invalidated request
52
+ * (XQ-009 remainder) — both are "a local record changed to record a
53
+ * rejection", and neither needs its own counter.
54
+ */
56
55
  rejected: number
57
56
  /**
58
57
  * True if at least one subtree of the plan could not finish and was left
@@ -153,12 +152,28 @@ export async function processOfflineActions(args: {
153
152
  }
154
153
  }
155
154
 
155
+ // XQ-009 remainder: a row this device once honestly marked 'sent' (real
156
+ // proof, or a real broadcast) can still have its backing request later
157
+ // reclaimed by the toolbox's own proof-timeout machinery
158
+ // (`EntityProvenTxReq`'s `applyProofTimeout`, reached from `TaskSendWaiting`
159
+ // once `attempts` runs out) if the transaction never actually confirms — a
160
+ // reorg, or a rarer race. When that happens the toolbox's OWN request row
161
+ // already reflects it (`status: 'invalid'`) and has already reclaimed the
162
+ // spendable inputs; this queue's own 'sent' row just never learns about it,
163
+ // leaving the activity list and any resend logic reading a stale success
164
+ // forever. Purely local and read-only against the toolbox's own tables —
165
+ // it never re-broadcasts, aborts, or writes a transaction/request row
166
+ // itself, only brings this queue's bookkeeping in line with a decision the
167
+ // toolbox already made — so it runs unconditionally, before the
168
+ // connectivity probe and even when there is nothing else to do this pass.
169
+ const staleReconciled = await reconcileStaleSentActions(storage, db)
170
+
156
171
  // 'posting' is included so a run interrupted mid-flight resumes rather than
157
172
  // stranding its rows. Re-posting is safe: a transaction the network already has
158
173
  // comes back as accepted (ARC's `SEEN_ON_NETWORK`), and a request storage has
159
174
  // already recorded as delivered is not posted again at all — see `postOwned`.
160
175
  const queued = await findOfflineActions(db, { status: ['queued', 'posting'] })
161
- if (queued.length === 0) return { sent: 0, rejected: 0, stopped: false }
176
+ if (queued.length === 0) return { sent: 0, rejected: staleReconciled, stopped: false }
162
177
 
163
178
  // BEFORE the connectivity probe, because it needs none: a row whose request
164
179
  // storage already records as delivered ('unmined', 'completed', …) has
@@ -182,11 +197,11 @@ export async function processOfflineActions(args: {
182
197
  rows.push(row)
183
198
  }
184
199
  }
185
- if (rows.length === 0) return { sent, rejected: 0, stopped: false }
200
+ if (rows.length === 0) return { sent, rejected: staleReconciled, stopped: false }
186
201
 
187
202
  if (!(await probeOnline())) {
188
203
  devLog(`[processOfflineActions] offline, leaving ${rows.length} action(s) queued`)
189
- return { sent, rejected: 0, stopped: true }
204
+ return { sent, rejected: staleReconciled, stopped: true }
190
205
  }
191
206
 
192
207
  // Merge every held request's BEEF into one graph. Anything that cannot be read
@@ -252,7 +267,7 @@ export async function processOfflineActions(args: {
252
267
  const txs: OrderableTx[] = merged.txs
253
268
  const plan = planRelease({ rows, txs })
254
269
 
255
- let rejected = 0
270
+ let rejected = staleReconciled
256
271
  const resolved = new Set<string>()
257
272
  const skip = new Set<string>()
258
273
  const stallNotes: string[] = blocked.length > 0 ? [...blocked] : []
@@ -470,6 +485,53 @@ async function findReq(storage: StorageExpoSQLite, txid: string): Promise<TableP
470
485
  }
471
486
  }
472
487
 
488
+ /**
489
+ * XQ-009 remainder: bring a 'sent' queue row back in line once its backing
490
+ * request has since been invalidated.
491
+ *
492
+ * A row only ever reaches 'sent' from either a real, verified proof
493
+ * (`postOwned`/`postForeign`'s Merkle-path-checked `networkAlreadyHas`) or
494
+ * this device's own successful broadcast — never from a bare, unauthenticated
495
+ * status claim (that is exactly what XQ-009's own fix closed). What this
496
+ * reconciles is the narrower case left after that: a transaction that really
497
+ * did look delivered at the time can still fail to confirm — a reorg, or a
498
+ * rarer race — and the toolbox's OWN monitor eventually notices on its own
499
+ * timeline (`EntityProvenTxReq`'s proof-timeout marks the request `invalid`
500
+ * once its retry budget is exhausted, `TaskSendWaiting` reclaiming the
501
+ * spendable inputs as part of that). Nothing here decides any of that, or
502
+ * touches a proven_tx_req/transaction row at all — it only reads what the
503
+ * toolbox already decided and updates this queue's OWN bookkeeping table to
504
+ * match, so the activity list and any resend logic stop reading a stale
505
+ * 'sent' as reality. Never re-broadcasts, never releases or aborts anything.
506
+ *
507
+ * Read-only against `findOfflineActions`/`findReq`, both already
508
+ * fault-tolerant (a read failure there returns nothing, not a throw), so a
509
+ * failure here costs only a skipped row for one pass, not the rest of the
510
+ * run — errors are still caught around the one write, for the same reason.
511
+ */
512
+ async function reconcileStaleSentActions(storage: StorageExpoSQLite, db: OfflineDb): Promise<number> {
513
+ let sentRows: OfflineActionRow[]
514
+ try {
515
+ sentRows = await findOfflineActions(db, { status: ['sent'] })
516
+ } catch (e) {
517
+ devLog('[processOfflineActions] could not read sent rows to reconcile:', e)
518
+ return 0
519
+ }
520
+ let reconciled = 0
521
+ for (const row of sentRows) {
522
+ const api = await findReq(storage, row.txid)
523
+ if (api?.status !== 'invalid') continue
524
+ try {
525
+ await updateOfflineAction(db, row.txid, { status: 'rejected', rejectedReason: 'proof_timeout' })
526
+ devLog(`[processOfflineActions] reconciled stale 'sent' row ${row.txid}: its request is now 'invalid'`)
527
+ reconciled++
528
+ } catch (e) {
529
+ devLog(`[processOfflineActions] could not reconcile stale 'sent' row ${row.txid}:`, e)
530
+ }
531
+ }
532
+ return reconciled
533
+ }
534
+
473
535
  /** Return every unresolved row we may have moved to 'posting' to 'queued'. */
474
536
  async function requeue(db: OfflineDb, plan: { txid: string; owned: boolean }[], resolved: Set<string>): Promise<void> {
475
537
  for (const step of plan) {
@@ -527,7 +589,7 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
527
589
  // can only read as serviceError: re-held, re-queued, and stuck on every tick
528
590
  // while the activity list says settled (2026-09-16). Asking first costs one
529
591
  // status lookup and lets storage record what already happened.
530
- if (await networkAlreadyHas(storage, api.txid)) {
592
+ if (await networkAlreadyHas(storage, api.txid, api.rawTx)) {
531
593
  devLog(`[processOfflineActions] the network already has ${api.txid}; recording delivery without a post`)
532
594
  await recordDeliveredElsewhere(storage, api)
533
595
  return 'success'
@@ -606,21 +668,47 @@ export async function postOwnedByTxid(storage: StorageExpoSQLite, txid: string):
606
668
  return await postOwned(storage, api)
607
669
  }
608
670
 
671
+ /** Whatever `EntityProvenTx.fromTxid` actually needs — extracted rather than
672
+ * importing the (unexported) `WalletServices` type by name. */
673
+ type ProvenTxServices = Parameters<typeof EntityProvenTx.fromTxid>[1]
674
+
609
675
  /**
610
- * Whether the network already has `txid`, by the services' own status lookup
611
- * ('mined' or 'known'). Every failure — no such service, a transport fault, an
612
- * unexpected shape — is `false`: the answer then falls back to the ordinary
613
- * post, whose own result decides. Never a reason to stall.
676
+ * Whether the network already has `txid`, PROVEN.
677
+ *
678
+ * XQ-009: a bare `getStatusForTxids` 'mined'/'known' string costs nothing for
679
+ * an attacker who controls, or MITMs, the status endpoint — and both callers
680
+ * below treat a `true` answer as licence to skip this device's own broadcast
681
+ * and record the transaction as durably delivered, with no reconciliation
682
+ * path if that later turns out to be wrong. So the status string is only the
683
+ * cheap first check; a positive answer must still be confirmed by the same
684
+ * chain-tracker-validated proof the toolbox's own `TaskCheckForProofs`
685
+ * already trusts (`EntityProvenTx.fromTxid`) — this device's OWN `rawTx`
686
+ * (never fetched from the network) plus a Merkle path whose root validates
687
+ * against this wallet's independently-maintained chain tracker. Forging a
688
+ * status string is free; forging a Merkle path that validates against a real
689
+ * chain tracker would require actually getting the transaction mined.
690
+ *
691
+ * `rawTx` is optional only so a caller with no local copy of the candidate
692
+ * transaction (a foreign ancestor whose beef entry is txid-only) degrades to
693
+ * the pre-existing "no proof, no shortcut" answer rather than skipping proof
694
+ * entirely — it never widens what counts as proof.
695
+ *
696
+ * Every failure — no such service, a transport fault, an unexpected shape, no
697
+ * valid proof — is `false`: the answer then falls back to the ordinary post,
698
+ * whose own result decides. Never a reason to stall.
614
699
  */
615
- async function networkAlreadyHas(storage: StorageExpoSQLite, txid: string): Promise<boolean> {
700
+ async function networkAlreadyHas(storage: StorageExpoSQLite, txid: string, rawTx?: number[]): Promise<boolean> {
616
701
  try {
617
- const services = storage.getServices() as {
702
+ const services = storage.getServices() as ProvenTxServices & {
618
703
  getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
619
704
  }
620
705
  if (typeof services.getStatusForTxids !== 'function') return false
621
706
  const r = await services.getStatusForTxids([txid])
622
707
  const status = r.results?.find(x => x.txid === txid)?.status
623
- return status === 'mined' || status === 'known'
708
+ if (status !== 'mined' && status !== 'known') return false
709
+ if (!rawTx) return false
710
+ const { proven } = await EntityProvenTx.fromTxid(txid, services, rawTx)
711
+ return proven !== undefined
624
712
  } catch (e) {
625
713
  devLog(`[processOfflineActions] could not ask the network whether it has ${txid}:`, e)
626
714
  return false
@@ -676,8 +764,12 @@ async function closeSettlementAsBroadcast(store: SettlementStore, txid: string):
676
764
  async function postForeign(storage: StorageExpoSQLite, merged: Beef, txid: string): Promise<PostOutcome> {
677
765
  // Same witness as `postOwned`: an ancestor that arrived inside a counterparty's
678
766
  // BEEF was usually broadcast by that counterparty already, and a failed
679
- // re-post of it would block every owned transaction behind it.
680
- if (await networkAlreadyHas(storage, txid)) {
767
+ // re-post of it would block every owned transaction behind it. The
768
+ // candidate rawTx for the proof check comes from the merged graph itself
769
+ // (a counterparty's own bytes) rather than the network — absent only when
770
+ // that entry is txid-only, in which case `networkAlreadyHas` degrades to
771
+ // its pre-existing "no proof, no shortcut" answer.
772
+ if (await networkAlreadyHas(storage, txid, merged.findTxid(txid)?.tx?.toBinary())) {
681
773
  devLog(`[processOfflineActions] the network already has foreign ancestor ${txid}; not posting`)
682
774
  return 'success'
683
775
  }
@@ -14,9 +14,14 @@ import { devLog } from '../../logging'
14
14
  const SAFE_REQ_STATUSES = new Set(['invalid', 'doubleSpend'])
15
15
 
16
16
  export type ReviewStatusDb = {
17
+ // Method shorthand (not arrow-style properties) is intentional: it keeps this
18
+ // structurally assignable from node:sqlite's DatabaseSync, whose statement
19
+ // methods take the narrower SQLInputValue type rather than unknown. Arrow-style
20
+ // properties are checked contravariantly under strictFunctionTypes and reject
21
+ // that narrower parameter type; method shorthand is checked bivariantly.
17
22
  prepare(sql: string): {
18
- all: (...params: unknown[]) => unknown[]
19
- run: (...params: unknown[]) => unknown
23
+ all(...params: unknown[]): unknown[]
24
+ run(...params: unknown[]): unknown
20
25
  }
21
26
  }
22
27
 
@@ -1,5 +1,6 @@
1
1
  import type { SQLiteDatabase } from 'expo-sqlite'
2
2
  import type { BindValue } from '../methods/offlineActions'
3
+ import { devLog } from '../../logging'
3
4
 
4
5
  /**
5
6
  * SQL statements to create all wallet storage tables
@@ -156,6 +157,15 @@ export async function createTables(db: SQLiteDatabase): Promise<void> {
156
157
  CREATE INDEX IF NOT EXISTS idx_transactions_txid ON transactions(txid);
157
158
  `)
158
159
 
160
+ // NEW-01: a device that created this table before this migration existed
161
+ // keeps it; CREATE TABLE IF NOT EXISTS cannot add the column, so the guarded
162
+ // ALTER does (ensureTransactionsColumns, defined below — hoisted). Called
163
+ // here, inside createTables, rather than only from StorageExpoSQLite.migrate,
164
+ // so every direct createTables() caller (this schema file's own tests
165
+ // included) gets these columns too, exactly like ensureTokenSettlementColumns
166
+ // below.
167
+ await ensureTransactionsColumns(db)
168
+
159
169
  // Commissions table
160
170
  await db.execAsync(`
161
171
  CREATE TABLE IF NOT EXISTS commissions (
@@ -361,6 +371,30 @@ export async function createTables(db: SQLiteDatabase): Promise<void> {
361
371
  CREATE INDEX IF NOT EXISTS idx_offline_actions_txid ON offline_actions(txid);
362
372
  `)
363
373
 
374
+ // Contacts — local, userId-scoped naming of counterparty identity keys.
375
+ // `name` is the user's own label and is never overwritten by a background
376
+ // refresh; `cachedHandle`/`cachedAvatarUrl`/`cachedCertifier` mirror what
377
+ // resolveIdentity last saw and are read-only in the UI. @bsv/sdk's
378
+ // ContactsManager and @bsv/mandala's contactsStore were rejected for v1:
379
+ // each write there is a signed on-chain action.
380
+ await db.execAsync(`
381
+ CREATE TABLE IF NOT EXISTS contacts (
382
+ contactId INTEGER PRIMARY KEY AUTOINCREMENT,
383
+ created_at TEXT NOT NULL,
384
+ updated_at TEXT NOT NULL,
385
+ userId INTEGER NOT NULL,
386
+ identityKey TEXT NOT NULL,
387
+ name TEXT NOT NULL,
388
+ cachedHandle TEXT,
389
+ cachedAvatarUrl TEXT,
390
+ cachedCertifier TEXT,
391
+ source TEXT NOT NULL DEFAULT 'manual',
392
+ FOREIGN KEY (userId) REFERENCES users(userId)
393
+ );
394
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_contacts_unique ON contacts(userId, identityKey);
395
+ CREATE INDEX IF NOT EXISTS idx_contacts_userId ON contacts(userId);
396
+ `)
397
+
364
398
  await createMandalaSettlementTables(db)
365
399
  }
366
400
 
@@ -399,6 +433,7 @@ export async function createMandalaSettlementTables(
399
433
  overlayIdentityKey TEXT NOT NULL,
400
434
  admissionOutputsJson TEXT,
401
435
  admissionSignatureHex TEXT,
436
+ relevantVout INTEGER,
402
437
  refusedCode TEXT,
403
438
  refusedPayloadHash TEXT,
404
439
  poisonedByTxid TEXT,
@@ -415,6 +450,11 @@ export async function createMandalaSettlementTables(
415
450
  // CREATE TABLE IF NOT EXISTS cannot add the column, so the guarded ALTER does.
416
451
  await ensureTokenSettlementColumns(db)
417
452
  await db.execAsync(`CREATE INDEX IF NOT EXISTS idx_token_settlements_reference ON token_settlements(reference);`)
453
+ // Drives a contact's activity pane (core/contacts/contactActivity.ts):
454
+ // every token transfer with this counterparty, in one indexed lookup.
455
+ await db.execAsync(
456
+ `CREATE INDEX IF NOT EXISTS idx_token_settlements_counterpartyKey ON token_settlements(counterpartyKey);`
457
+ )
418
458
 
419
459
  // Cached mirror of the AdmissionEntry values this device has SEEN. Purely a
420
460
  // derivable cache (FIX G) — never a precondition for anything.
@@ -482,6 +522,65 @@ export async function ensureOfflineActionsColumns(db: {
482
522
  }
483
523
  }
484
524
 
525
+ /**
526
+ * NEW-01: `@bsv/wallet-toolbox-mobile`'s BRC-177 `noSendExpiry` lifecycle
527
+ * (early-reclaim actions, `armNoSendExpiry`, `abortAction`,
528
+ * `updateTransactionStatus`) reads and writes these `transactions` columns
529
+ * unconditionally — not only when a BRC-177 action is actually used.
530
+ * `protectNoSendExpiryReclaimInputOnFailure`, the guard every 'failed'
531
+ * transition runs through, filters on `noSendExpiryReclaimTxid`: without this
532
+ * column that WHERE clause throws "no such column", not "no match", so NO
533
+ * failed-transition of a transaction with a txid can complete — `abortAction`
534
+ * of any signed action, a failed broadcast, a proof-check timeout, and
535
+ * `reviewStatus`'s own `failInvalidReqTxs` sweep all reach it. This app never
536
+ * creates a BRC-177 protected action itself (`supportsNoSendExpiryPersistence`
537
+ * is not overridden and defaults to `false`, so `armNoSendExpiry` always
538
+ * throws `WERR_NOT_IMPLEMENTED`), but the vendor's generic failure path does
539
+ * not gate on that — every row still needs these columns to exist, forever
540
+ * NULL in practice here.
541
+ *
542
+ * Types and names taken from `TableTransaction` in
543
+ * `@bsv/wallet-toolbox-mobile`'s `out/index.mobile.d.cts`. All nullable, no
544
+ * defaults: an existing row reads back every one of these as `undefined`,
545
+ * which is exactly what "this transaction never touched BRC-177" already
546
+ * means to every caller.
547
+ */
548
+ const TRANSACTIONS_COLUMNS: { name: string; ddl: string }[] = [
549
+ { name: 'noSendExpiryMode', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryMode TEXT' },
550
+ { name: 'noSendExpiryValue', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryValue INTEGER' },
551
+ { name: 'noSendExpiryDeadline', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryDeadline INTEGER' },
552
+ { name: 'noSendExpiryState', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryState TEXT' },
553
+ { name: 'noSendExpiryAnchorTxid', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryAnchorTxid TEXT' },
554
+ { name: 'noSendExpiryAnchorVout', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryAnchorVout INTEGER' },
555
+ { name: 'noSendExpiryReleasedAt', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReleasedAt INTEGER' },
556
+ { name: 'noSendExpiryObservedAt', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryObservedAt INTEGER' },
557
+ { name: 'noSendExpiryReclaimTxid', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimTxid TEXT' },
558
+ { name: 'noSendExpiryReclaimRawTx', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimRawTx BLOB' },
559
+ {
560
+ name: 'noSendExpiryReclaimDerivationPrefix',
561
+ ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimDerivationPrefix TEXT'
562
+ },
563
+ {
564
+ name: 'noSendExpiryReclaimDerivationSuffix',
565
+ ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimDerivationSuffix TEXT'
566
+ },
567
+ {
568
+ name: 'noSendExpiryReclaimSatoshis',
569
+ ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimSatoshis INTEGER'
570
+ }
571
+ ]
572
+
573
+ export async function ensureTransactionsColumns(db: {
574
+ getAllAsync(sql: string, params: BindValue[]): Promise<unknown[]>
575
+ execAsync(sql: string): Promise<unknown>
576
+ }): Promise<void> {
577
+ const info = (await db.getAllAsync('PRAGMA table_info(transactions)', [])) as { name: string }[]
578
+ const have = new Set(info.map(c => c.name))
579
+ for (const col of TRANSACTIONS_COLUMNS) {
580
+ if (!have.has(col.name)) await db.execAsync(col.ddl)
581
+ }
582
+ }
583
+
485
584
  /**
486
585
  * The same doctrine for `token_settlements`, which shipped before it had a
487
586
  * `reference` column and cannot be re-created over live rows.
@@ -493,7 +592,13 @@ export async function ensureOfflineActionsColumns(db: {
493
592
  * wallet action reference — so the backfill is simply the next hand-over.
494
593
  */
495
594
  const TOKEN_SETTLEMENT_COLUMNS: { name: string; ddl: string }[] = [
496
- { name: 'reference', ddl: 'ALTER TABLE token_settlements ADD COLUMN reference TEXT' }
595
+ { name: 'reference', ddl: 'ALTER TABLE token_settlements ADD COLUMN reference TEXT' },
596
+ // XR-038: the wallet-relevant output index, so a cached admission for some
597
+ // OTHER output of the same txid can never stand in for this one. Nullable,
598
+ // no default — an existing row reads back `relevantVout === undefined`,
599
+ // which `postTokenStep` reads as 0 (the payee's-output convention), exactly
600
+ // as it always has for every row written before this column existed.
601
+ { name: 'relevantVout', ddl: 'ALTER TABLE token_settlements ADD COLUMN relevantVout INTEGER' }
497
602
  ]
498
603
 
499
604
  export async function ensureTokenSettlementColumns(db: {
@@ -503,6 +608,54 @@ export async function ensureTokenSettlementColumns(db: {
503
608
  const info = (await db.getAllAsync('PRAGMA table_info(token_settlements)', [])) as { name: string }[]
504
609
  const have = new Set(info.map(c => c.name))
505
610
  for (const col of TOKEN_SETTLEMENT_COLUMNS) {
506
- if (!have.has(col.name)) await db.execAsync(col.ddl)
611
+ if (have.has(col.name)) continue
612
+ await db.execAsync(col.ddl)
613
+ // XR-033: this ALTER just gave every existing row a NULL `reference`, and
614
+ // the abort guard's primary check (`getSettlementByReference`) can never
615
+ // match a NULL one against any reference — so backfill it now, in the
616
+ // same migration step, rather than leaving it to "the next hand-over"
617
+ // (which never comes for a row already stuck in a blocked state).
618
+ if (col.name === 'reference') await backfillLegacyTokenSettlementReferences(db)
619
+ }
620
+ }
621
+
622
+ /**
623
+ * XR-033: resolves each pre-migration row's `reference` from `transactions`,
624
+ * the SAME table `abortAction({reference})` itself matches a reference
625
+ * against (`findTransactions({partial:{reference}})`) — so this backfills
626
+ * from the one mapping that is already authoritative, rather than guessing.
627
+ *
628
+ * Scoped to rows that both need it and can be resolved: still blocked (the
629
+ * same states `abortGuard.ts`'s `ABORT_BLOCKED_SETTLEMENT_STATES` lists —
630
+ * duplicated here, not imported, for the reason `settlementStore.ts` gives:
631
+ * this schema file is statements, not cross-module logic) and whose
632
+ * transaction row still exists to resolve from. A row that cannot be
633
+ * resolved (its transaction is gone) is left NULL; the abort guard's own
634
+ * second, coarser check (`hasUnresolvedLegacyBlockedRows`) covers that case
635
+ * without this migration needing to.
636
+ *
637
+ * Never throws: this runs inside the ADD COLUMN step of the wallet's whole
638
+ * migration ladder, and `transactions` — always present in the real app,
639
+ * created earlier in this same `createTables` — is not guaranteed by this
640
+ * function's own narrow signature. A device where the backfill itself cannot
641
+ * run is exactly what `hasUnresolvedLegacyBlockedRows` exists to catch at
642
+ * `abortAction` time instead, so a failure here costs that coarser refusal,
643
+ * never a broken migration.
644
+ */
645
+ async function backfillLegacyTokenSettlementReferences(db: {
646
+ execAsync(sql: string): Promise<unknown>
647
+ }): Promise<void> {
648
+ try {
649
+ await db.execAsync(`
650
+ UPDATE token_settlements
651
+ SET reference = (
652
+ SELECT reference FROM transactions WHERE transactions.txid = token_settlements.txid
653
+ )
654
+ WHERE reference IS NULL
655
+ AND state IN ('held','handed_over','submitting','admitted','broadcast')
656
+ AND EXISTS (SELECT 1 FROM transactions WHERE transactions.txid = token_settlements.txid)
657
+ `)
658
+ } catch (e) {
659
+ devLog('[createTables] could not backfill legacy token_settlements references:', e)
507
660
  }
508
661
  }
@@ -10,19 +10,53 @@ export interface Connection {
10
10
  protocolID: string // JSON-stringified WalletProtocol
11
11
  connectedAt: number
12
12
  status: 'active' | 'disconnected'
13
+ /** XR-027: HMAC over (origin, sessionId, protocolID, backendIdentityKey),
14
+ * computed by an ADMIN-scoped wallet under the `connection authority`
15
+ * namespace reserved in core/services/vault/guard.ts -- see
16
+ * core/services/connectionAuthority.ts. Absent on a record saved before
17
+ * this fix, or one that never got tagged; callers must treat that exactly
18
+ * like a tag that fails verification (needs re-approval), never as
19
+ * implicitly trusted. */
20
+ authorityTag?: string
13
21
  }
14
22
 
15
23
  const STORAGE_KEY = 'connections'
16
24
 
17
25
  class ConnectionStore {
18
26
  connections: Connection[] = []
27
+ /** XR-027: a tag the pairing/reconnect screens compute with their own
28
+ * admin-scoped wallet BEFORE calling connect() -- add() below (called from
29
+ * deep inside connect()'s websocket-open callback, which never sees an
30
+ * admin wallet) consumes it in the same synchronous step that creates the
31
+ * record, so a freshly approved connection is never observably tagless in
32
+ * between. Never persisted and never part of the observed connection
33
+ * list; mobx wraps it as an ObservableMap, but nothing here relies on
34
+ * that reactivity. */
35
+ private pendingAuthorityTags = new Map<string, string>()
19
36
 
20
37
  constructor() {
21
38
  makeAutoObservable(this)
22
39
  void this.load()
23
40
  }
24
41
 
42
+ stageAuthorityTag(sessionId: string, tag: string) {
43
+ this.pendingAuthorityTags.set(sessionId, tag)
44
+ }
45
+
46
+ /** A staged tag that never gets consumed (approval abandoned, connect()
47
+ * failed before its record was ever added) would otherwise sit in memory
48
+ * forever. Screens call this from their own catch block; harmless to call
49
+ * for a sessionId with nothing staged. */
50
+ discardStagedAuthorityTag(sessionId: string) {
51
+ this.pendingAuthorityTags.delete(sessionId)
52
+ }
53
+
25
54
  add(connection: Connection) {
55
+ const tag = this.pendingAuthorityTags.get(connection.sessionId)
56
+ if (tag !== undefined) {
57
+ this.pendingAuthorityTags.delete(connection.sessionId)
58
+ connection = { ...connection, authorityTag: tag }
59
+ }
26
60
  const idx = this.connections.findIndex(c => c.sessionId === connection.sessionId)
27
61
  if (idx >= 0) {
28
62
  this.connections[idx] = connection
@@ -35,6 +35,14 @@ export interface MandalaEndpointConfig {
35
35
  messageBoxUrl: string
36
36
  }
37
37
 
38
+ /** The paymail handle registry this build talks to, for one chain. */
39
+ export interface HandleRegistryConfig {
40
+ /** The domain handles live under here, e.g. `deggen.com`. Bare and lowercase. */
41
+ domain: string
42
+ /** Origin of the registry that serves that domain — no path, query or fragment. */
43
+ url: string
44
+ }
45
+
38
46
  /**
39
47
  * Runtime configuration supplied by the host app.
40
48
  *
@@ -81,6 +89,17 @@ export interface ToolboxConfig {
81
89
  * testnet deployment.
82
90
  */
83
91
  mandala?: Partial<Record<AppChain, MandalaEndpointConfig>>
92
+ /**
93
+ * The paymail handle registry, per chain: the domain this build's handles
94
+ * live under, and the host that serves it. Both together or neither — a
95
+ * domain with no URL is a registry nothing can reach, and a URL with no
96
+ * domain is a host whose certificates nothing can be checked against.
97
+ *
98
+ * There is deliberately no default. A chain with no complete entry shows
99
+ * the existing "not available yet" copy in Profile and adds no registry tier
100
+ * to Pay's recipient search.
101
+ */
102
+ handleRegistry?: Partial<Record<AppChain, HandleRegistryConfig>>
84
103
  /**
85
104
  * Release gate for the YubiKey vault (spec §0, D15). Default false: the home
86
105
  * button and Settings row are hidden, the vault route shows "Not available
@@ -95,6 +114,7 @@ interface ResolvedConfig {
95
114
  backupUrl: string
96
115
  services: Partial<Record<AppChain, ToolboxServiceConfig>>
97
116
  mandala: Partial<Record<AppChain, MandalaEndpointConfig>>
117
+ handleRegistry: Partial<Record<AppChain, HandleRegistryConfig>>
98
118
  vaultEnabled: boolean
99
119
  }
100
120
 
@@ -105,6 +125,33 @@ const NOT_CONFIGURED =
105
125
  'from the host app entry point, before rendering WalletContextProvider. ' +
106
126
  'Pass backupUrl: null to disable backup deliberately.'
107
127
 
128
+ /**
129
+ * Hosts a development build may reach over plain http: the simulator's own
130
+ * machine, the Android emulator's alias for it, and RFC 1918 space. Everything
131
+ * else must be https — which key owns a handle (or holds a backup, or admits
132
+ * a Mandala settlement) is precisely what a reader on the path would want to
133
+ * change.
134
+ */
135
+ const PRIVATE_HOST =
136
+ /^(localhost|127\.0\.0\.1|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/
137
+
138
+ /**
139
+ * XR-065 (SEC2-074): the https-except-private-network policy
140
+ * `getHandleRegistryConfig` already applied to the paymail registry origin,
141
+ * shared here so `normalizeBackupUrl` and `getMandalaEndpoints` stop
142
+ * accepting a plain http: or credential-bearing origin with no policy at
143
+ * all. A host's own backup service, Mandala overlay, and Mandala MessageBox
144
+ * are each configuration-time, host-trusted values, not remote/runtime
145
+ * input — but a misconfigured or copy-pasted http: URL, or one carrying a
146
+ * bearer credential, still exposes every request this package makes over
147
+ * that origin to an on-path attacker.
148
+ */
149
+ export function isAllowedServiceOrigin(parsed: URL): boolean {
150
+ if (parsed.username || parsed.password) return false
151
+ if (parsed.protocol === 'https:') return true
152
+ return parsed.protocol === 'http:' && PRIVATE_HOST.test(parsed.hostname)
153
+ }
154
+
108
155
  function normalizeBackupUrl(raw: string): string {
109
156
  const trimmed = raw.trim().replace(/\/+$/, '')
110
157
  if (trimmed === '') return ''
@@ -123,6 +170,11 @@ function normalizeBackupUrl(raw: string): string {
123
170
  if (parsed.search !== '' || parsed.hash !== '') {
124
171
  throw new Error(`configureToolbox: backupUrl must be a bare origin, with no query or fragment: ${raw}`)
125
172
  }
173
+ if (!isAllowedServiceOrigin(parsed)) {
174
+ throw new Error(
175
+ `configureToolbox: backupUrl must be https (plain http is allowed only for a local-dev host): ${raw}`
176
+ )
177
+ }
126
178
  return trimmed
127
179
  }
128
180
 
@@ -140,6 +192,7 @@ export function configureToolbox(config: ToolboxConfig): void {
140
192
  backupUrl: config.backupUrl == null ? '' : normalizeBackupUrl(config.backupUrl),
141
193
  services: config.services ?? {},
142
194
  mandala: config.mandala ?? {},
195
+ handleRegistry: config.handleRegistry ?? {},
143
196
  vaultEnabled: config.vaultEnabled === true
144
197
  }
145
198
  }
@@ -187,9 +240,60 @@ export function getMandalaEndpoints(chain: AppChain): MandalaEndpointConfig | un
187
240
  const messageBoxUrl = entry.messageBoxUrl?.trim().replace(/\/+$/, '') ?? ''
188
241
  if (overlayUrl === '' || messageBoxUrl === '') return undefined
189
242
  if (!COMPRESSED_KEY.test(overlayIdentityKey)) return undefined
243
+ // XR-065 (SEC2-074): neither URL had a scheme policy at all before this --
244
+ // a plain http: overlay or MessageBox origin (or one carrying embedded
245
+ // credentials) resolved to a fully populated, "working" config.
246
+ for (const url of [overlayUrl, messageBoxUrl]) {
247
+ let parsed: URL
248
+ try {
249
+ parsed = new URL(url)
250
+ } catch {
251
+ return undefined
252
+ }
253
+ if (!isAllowedServiceOrigin(parsed)) return undefined
254
+ }
190
255
  return { overlayUrl, overlayIdentityKey, messageBoxUrl }
191
256
  }
192
257
 
258
+ /**
259
+ * The same rule as `DOMAIN_FORMAT` in `identity/handleRegistry/rules.ts`, which
260
+ * backs the `looksLikeDomain` the resolver and `parsePaymail` apply to the same
261
+ * strings. Restated rather than imported so this module stays a leaf and does
262
+ * not depend on a feature directory — change both together, because a domain
263
+ * this accepts and that one rejects is a configured registry nothing resolves.
264
+ */
265
+ const REGISTRY_DOMAIN = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/
266
+
267
+ /**
268
+ * The handle registry for a chain, or undefined when this build has none.
269
+ *
270
+ * Same fail-closed posture as `getMandalaEndpoints`: never throws, and a
271
+ * partial or malformed entry answers undefined rather than a half-usable
272
+ * object. `10.0.2.2` — the Android emulator's route to its host — falls out of
273
+ * the RFC 1918 branch and needs no case of its own.
274
+ *
275
+ * `url` must be a bare origin, for the reason `normalizeBackupUrl` says it
276
+ * above: every route is built by appending to it (`${url}/api/handle/dee`), so
277
+ * a configured `https://host/?x=1` addresses neither the host's registry nor
278
+ * anything else — exactly the half-usable entry this getter exists to refuse.
279
+ */
280
+ export function getHandleRegistryConfig(chain: AppChain): HandleRegistryConfig | undefined {
281
+ const entry = current?.handleRegistry[chain]
282
+ if (!entry) return undefined
283
+ const domain = entry.domain?.trim().toLowerCase() ?? ''
284
+ const url = entry.url?.trim().replace(/\/+$/, '') ?? ''
285
+ if (!REGISTRY_DOMAIN.test(domain) || url === '') return undefined
286
+ let parsed: URL
287
+ try {
288
+ parsed = new URL(url)
289
+ } catch {
290
+ return undefined
291
+ }
292
+ if (parsed.search !== '' || parsed.hash !== '') return undefined
293
+ if (parsed.pathname !== '' && parsed.pathname !== '/') return undefined
294
+ return isAllowedServiceOrigin(parsed) ? { domain, url } : undefined
295
+ }
296
+
193
297
  /**
194
298
  * Whether Mandala stablecoins are available on this network.
195
299
  *