@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
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { IdentityClient, StorageDownloader } from '@bsv/sdk'
16
16
  import type { DisplayableIdentity, WalletInterface } from '@bsv/sdk'
17
+ import { isPublicHttpsUrl } from '../core/net/publicDestination'
17
18
 
18
19
  /** Drops repeats by identityKey, keeping the first occurrence. */
19
20
  export const uniqueIdentities = (results: DisplayableIdentity[]) => {
@@ -23,22 +24,28 @@ export const uniqueIdentities = (results: DisplayableIdentity[]) => {
23
24
  }
24
25
 
25
26
  /**
26
- * Picks a usable avatar URL. An http(s) URL wins outright; anything else is
27
- * treated as a UHRP hash and resolved through storage, falling back to the raw
28
- * value so a downloader outage degrades to a broken image rather than a throw.
27
+ * Picks a usable avatar URL. An http(s) URL wins outright, but only when it is
28
+ * a public https destination: `avatarURL` comes from an untrusted BRC-100
29
+ * identity certificate, and HandleReceive/ContactSigil/RecipientField hand it
30
+ * straight to React Native's native Image loader with no other gate (XR-073 /
31
+ * SEC2-057, SEC2-076). Anything else is treated as a UHRP hash and resolved
32
+ * through storage; the SDK only requires a UHRP advertisement's hosted
33
+ * location to be a credential-free https URL, not a public one, so that
34
+ * resolved location is gated the same way before use.
29
35
  */
30
36
  export async function resolveAvatarURL(urls: (string | undefined)[]): Promise<string | undefined> {
31
37
  const defined = urls.filter((u): u is string => !!u)
32
- const httpUrl = defined.find(u => u.startsWith('http'))
38
+ const httpUrl = defined.find(u => u.startsWith('http') && isPublicHttpsUrl(u))
33
39
  if (httpUrl) return httpUrl
34
- const nonHttp = defined.find(u => !!u)
40
+ const nonHttp = defined.find(u => !u.startsWith('http'))
35
41
  if (!nonHttp) return undefined
36
42
  try {
37
43
  const downloader = new StorageDownloader()
38
44
  const resolved = await downloader.resolve(nonHttp)
39
- return resolved[0] ?? nonHttp
45
+ const candidate = resolved[0] ?? nonHttp
46
+ return isPublicHttpsUrl(candidate) ? candidate : undefined
40
47
  } catch {
41
- return nonHttp
48
+ return undefined
42
49
  }
43
50
  }
44
51
 
@@ -80,7 +87,16 @@ export async function resolveIdentity(
80
87
  }
81
88
  }
82
89
 
83
- /** Attribute search. Unlike resolveIdentity this one DOES throw; callers catch. */
90
+ /**
91
+ * Attribute search. Unlike resolveIdentity this one DOES throw; callers catch.
92
+ *
93
+ * Each hit's `avatarURL` is exactly as untrusted as any other BRC-100
94
+ * identity certificate field, but unlike `resolveIdentity`/`mergeIdentityRecords`
95
+ * it reaches ContactsScreen's network-search list and the Pay recipient
96
+ * search dropdown (both hand it straight to ContactSigil's native `<Image>`)
97
+ * without going through `resolveAvatarURL` first — gate it the same way here
98
+ * (XR-073 / SEC2-057, SEC2-076).
99
+ */
84
100
  export async function searchIdentities(
85
101
  idClient: IdentityClient,
86
102
  text: string
@@ -90,7 +106,13 @@ export async function searchIdentities(
90
106
  limit: 5,
91
107
  seekPermission: false
92
108
  })
93
- return uniqueIdentities(results)
109
+ const unique = uniqueIdentities(results)
110
+ return Promise.all(
111
+ unique.map(async identity => ({
112
+ ...identity,
113
+ avatarURL: (await resolveAvatarURL([identity.avatarURL])) || ''
114
+ }))
115
+ )
94
116
  }
95
117
 
96
118
  /**
@@ -1,4 +1,4 @@
1
- import React, { useEffect, useState } from 'react'
1
+ import React, { useState } from 'react'
2
2
  import { View, Text, TouchableOpacity, StyleSheet, Modal, ScrollView } from 'react-native'
3
3
  import { observer } from 'mobx-react-lite'
4
4
  import { WalletClient } from '@bsv/sdk'
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next'
8
8
  import { GroupedSection } from '../components/ui/GroupedList'
9
9
  import { ListRow } from '../components/ui/ListRow'
10
10
  import { showToast } from '../components/ui/Toast'
11
+ import { showAlert } from '../components/ui/AlertCard'
11
12
  import QRScanner from '../components/QRScanner'
12
13
  import {
13
14
  useTheme,
@@ -28,9 +29,11 @@ import {
28
29
  buildRelayWebSocketUrl,
29
30
  validateMobileIdentityKey,
30
31
  validateRelayUrl,
32
+ validateStoredConnectionAuthorityTag,
31
33
  validateStoredConnectionFields,
32
34
  validateStoredConnectionSequence
33
35
  } from '../../core/services/walletConnectionValidation'
36
+ import { computeConnectionAuthorityTag, verifyConnectionAuthorityTag } from '../../core/services/connectionAuthority'
34
37
 
35
38
  /**
36
39
  * expo-clipboard ships an untransformed ESM build (its Clipboard.js imports
@@ -154,27 +157,19 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
154
157
  const { colors } = useTheme()
155
158
  const { t } = useTranslation()
156
159
  const { managers } = useWallet()
157
- const { connect, reconnect } = useWalletConnection()
160
+ const { connect, reconnect, disconnect, sessionMeta } = useWalletConnection()
158
161
  const insets = useSafeAreaInsets()
159
162
  const [scanning, setScanning] = useState(false)
160
- const { router, useLocalSearchParams } = loadExpoRouter()
163
+ const { router } = loadExpoRouter()
161
164
  const Ionicons = loadIonicons()
162
- const deepLinkParams = useLocalSearchParams<PairingParams>()
163
165
 
164
- // Auto-connect when navigated here with deep link pairing params
165
- useEffect(() => {
166
- if (!deepLinkParams.topic || !managers.permissionsManager) return
167
- const query = new URLSearchParams({
168
- topic: deepLinkParams.topic,
169
- backendIdentityKey: deepLinkParams.backendIdentityKey ?? '',
170
- protocolID: deepLinkParams.protocolID ?? '',
171
- origin: deepLinkParams.origin ?? '',
172
- expiry: deepLinkParams.expiry ?? '',
173
- sig: deepLinkParams.sig ?? ''
174
- })
175
- const uri = `bsv-wallet://pair?${query}`
176
- handleScan(uri)
177
- }, [deepLinkParams.topic, managers.permissionsManager]) // eslint-disable-line react-hooks/exhaustive-deps
166
+ // NOTE: this screen used to auto-connect from `useLocalSearchParams`
167
+ // deep-link params the instant it saw a `topic`, with no user gesture in
168
+ // between (MITM-P1-deeplink-autoconnect). `nativeIntent.ts`'s
169
+ // `resolveNativeIntent` no longer routes an external pairing link here at
170
+ // all — it lands on `/pair` (PairScreen), which shows the same
171
+ // origin/permissions Approve/Reject card a scanned or pasted URI gets.
172
+ // This screen now only ever connects from an explicit scan or paste below.
178
173
 
179
174
  async function handleScan(data: string) {
180
175
  setScanning(false)
@@ -193,6 +188,25 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
193
188
  capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)),
194
189
  external.originator
195
190
  )
191
+ // XR-027: stage a saved-pairing authority tag for the EXACT tuple being
192
+ // approved, computed with an ADMIN-scoped wallet (never `wallet` above
193
+ // — see connectionAuthority.ts for why), before connect() runs. A
194
+ // failure here must not block a pairing the user just approved; it
195
+ // only leaves this record untagged, which reconnect later treats as
196
+ // "needs re-approval", same as a tampered record.
197
+ try {
198
+ const adminWallet = capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR))
199
+ const tag = await computeConnectionAuthorityTag(adminWallet, ADMIN_ORIGINATOR, {
200
+ origin: external.origin,
201
+ topic: result.params.topic,
202
+ protocolID: result.params.protocolID,
203
+ backendIdentityKey: result.params.backendIdentityKey,
204
+ })
205
+ connectionStore.stageAuthorityTag(result.params.topic, tag)
206
+ } catch (err) {
207
+ console.warn('[connections] failed to compute connection authority tag', err)
208
+ connectionStore.discardStagedAuthorityTag(result.params.topic)
209
+ }
196
210
  await connect({ ...result.params, origin: external.origin }, wallet)
197
211
  } catch (err) {
198
212
  showToast(`${t('connection_failed')}: ${err instanceof Error ? err.message : t('unknown_error')}`, { type: 'error' })
@@ -200,6 +214,12 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
200
214
  }
201
215
 
202
216
  async function handleDisconnect(conn: Connection) {
217
+ // XR-018: local revocation must not depend on the peer's cooperation, or
218
+ // on the best-effort session_revoke send below succeeding. If this is
219
+ // the provider's own live socket for this session, tear it down FIRST —
220
+ // that's the only thing that actually stops wireSocket's onmessage from
221
+ // continuing to dispatch privileged RPC methods to it.
222
+ if (sessionMeta?.topic === conn.sessionId) disconnect()
203
223
  connectionStore.setStatus(conn.sessionId, 'disconnected')
204
224
 
205
225
  if (!managers.permissionsManager) return
@@ -253,8 +273,55 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
253
273
 
254
274
  async function handleReconnect(conn: Connection) {
255
275
  if (!managers.permissionsManager) return
276
+ let external: ReturnType<typeof parseExternalOrigin>
277
+ try {
278
+ external = parseExternalOrigin(conn.origin)
279
+ } catch (err) {
280
+ showToast(`${t('reconnect_failed')}: ${err instanceof Error ? err.message : t('unknown_error')}`, { type: 'error' })
281
+ return
282
+ }
283
+ // XR-027: reconnect() itself authenticates only that the wallet's own
284
+ // PUBLIC identity key still matches — it never authenticates that the
285
+ // stored (origin, topic, protocolID, backendIdentityKey) tuple is the one
286
+ // the user actually approved, so a well-formed but SUBSTITUTED record
287
+ // (planted by anything that can write to AsyncStorage) would otherwise
288
+ // authenticate exactly like the real one. Verify the admin-computed
289
+ // authority tag over the CURRENT tuple first, with an ADMIN-scoped
290
+ // wallet (never the site-scoped `wallet` constructed below) — a missing
291
+ // tag (never tagged, or a pre-fix legacy record) or one that fails
292
+ // verification (any field substituted) is "needs re-approval", and this
293
+ // must never fall through to reconnect() either way.
294
+ const adminWallet = capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR))
295
+ let storedTag: string | undefined
296
+ try {
297
+ storedTag = validateStoredConnectionAuthorityTag((conn as { authorityTag?: unknown }).authorityTag)
298
+ } catch {
299
+ storedTag = undefined // malformed tag on disk — treat exactly like a missing one
300
+ }
301
+ const authentic = await verifyConnectionAuthorityTag(adminWallet, ADMIN_ORIGINATOR, {
302
+ origin: external.origin,
303
+ topic: conn.sessionId,
304
+ protocolID: conn.protocolID,
305
+ backendIdentityKey: conn.backendIdentityKey
306
+ }, storedTag)
307
+ if (!authentic) {
308
+ showToast(t('reconnect_needs_reapproval'), { type: 'error' })
309
+ return
310
+ }
311
+ // Showing the canonicalized origin and requiring an explicit
312
+ // re-confirmation here is a separate, additional consent step: it means
313
+ // the user is never re-granted a paired RPC counterparty without seeing
314
+ // which (now-authenticated) origin it is for.
315
+ const choice = await showAlert({
316
+ title: t('reconnect_confirm_title'),
317
+ message: t('reconnect_confirm_message', { origin: external.originator }),
318
+ buttons: [
319
+ { text: t('reconnect'), key: 'reconnect' },
320
+ { text: t('cancel'), key: 'cancel', style: 'cancel' }
321
+ ]
322
+ })
323
+ if (choice !== 'reconnect') return
256
324
  try {
257
- const external = parseExternalOrigin(conn.origin)
258
325
  const wallet = new WalletClient(
259
326
  capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)),
260
327
  external.originator
@@ -0,0 +1,289 @@
1
+ /**
2
+ * A contact: their face, name and read-only registered handle up top; your
3
+ * own name for them (editable, pencil → confirm); their Identifier with a
4
+ * copy button; delete; and every interaction with them across every asset
5
+ * (2026-09-17 ruling), drawn with the same rows Home uses.
6
+ */
7
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
8
+ import { I18nManager, ScrollView, StyleSheet, Text, View } from 'react-native'
9
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
10
+ import { useTranslation } from 'react-i18next'
11
+ import { useTheme, spacing, typography, useWallet } from '@bsv/expo-wallet-toolbox'
12
+ import { showAlert } from '../components/ui/AlertCard'
13
+ import { GroupedSection } from '../components/ui/GroupedList'
14
+ import { ListRow } from '../components/ui/ListRow'
15
+ import { PencilEditField } from '../components/ui/PencilEditField'
16
+ import PressableScale from '../components/ui/PressableScale'
17
+ import ContactSigil from '../components/wallet/ContactSigil'
18
+ import ContactActivityList from '../components/wallet/ContactActivityList'
19
+ import IdentifierRow from '../components/wallet/IdentifierRow'
20
+ import { useContactsStore } from '../hooks/useContactsStore'
21
+ import { getContactActivity, type ContactActivityItem } from '../../core/contacts/contactActivity'
22
+ import { mergeContactCache } from '../../core/contacts/contactCache'
23
+ import { makeIdentityClient, resolveIdentity } from '../resolveIdentity'
24
+ import { getHandleRegistryConfig } from '../../core/toolboxConfig'
25
+ import { parsePaymail } from '../../core/identity/handleRegistry/rules'
26
+ import { createHandleRegistryClient } from '../../core/identity/handleRegistry/client'
27
+ import type { ContactRow } from '../../core/contacts/contactsStore'
28
+
29
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
30
+ let ioniconsComponent: IoniconsComponent | undefined
31
+ function loadIonicons(): IoniconsComponent {
32
+ if (!ioniconsComponent) {
33
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
34
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
35
+ }
36
+ return ioniconsComponent
37
+ }
38
+
39
+ type ExpoRouterModule = typeof import('expo-router')
40
+ let expoRouterMod: ExpoRouterModule | undefined
41
+ function loadExpoRouter(): ExpoRouterModule {
42
+ if (!expoRouterMod) {
43
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
44
+ expoRouterMod = require('expo-router') as ExpoRouterModule
45
+ }
46
+ return expoRouterMod
47
+ }
48
+
49
+ function firstParam(v: string | string[] | undefined): string | undefined {
50
+ return Array.isArray(v) ? v[0] : v
51
+ }
52
+
53
+ export function ContactScreen() {
54
+ const { t } = useTranslation()
55
+ const { colors } = useTheme()
56
+ const insets = useSafeAreaInsets()
57
+ const Ionicons = loadIonicons()
58
+ const { router, useLocalSearchParams } = loadExpoRouter()
59
+ const { managers, adminOriginator, storage, walletUserId, selectedNetwork } = useWallet()
60
+ const store = useContactsStore()
61
+ const params = useLocalSearchParams<{ identityKey?: string | string[] }>()
62
+ const identityKey = firstParam(params.identityKey) ?? ''
63
+
64
+ const [contact, setContact] = useState<ContactRow | undefined>(undefined)
65
+ const [activity, setActivity] = useState<ContactActivityItem[]>([])
66
+
67
+ const reload = useCallback(async () => {
68
+ if (!store || walletUserId === null || !identityKey) return
69
+ setContact(await store.getContact(walletUserId, identityKey))
70
+ }, [store, walletUserId, identityKey])
71
+
72
+ useEffect(() => {
73
+ void reload()
74
+ }, [reload])
75
+
76
+ useEffect(() => {
77
+ if (!identityKey) return
78
+ const wallet = managers?.permissionsManager
79
+ void getContactActivity({
80
+ wallet: wallet as never,
81
+ adminOriginator,
82
+ settlementsDb: storage?.sqliteDb as never,
83
+ identityKey
84
+ }).then(setActivity)
85
+ }, [identityKey, managers, adminOriginator, storage])
86
+
87
+ /**
88
+ * Best-effort background cache refresh: the overlay's avatar and the
89
+ * registry's handle, in ONE write. `refreshContactCache` replaces all three
90
+ * cache columns, so two separate calls would each blank what the other just
91
+ * stored. Once per visit — the write feeds `reload`, and re-running on the
92
+ * contact it produced would be a loop.
93
+ *
94
+ * One guard per source, though, not one for the pass. The two clients arrive
95
+ * at different moments: a screen drawn before the wallet finished building
96
+ * has no identity client, while a chain WITH a registry configured has its
97
+ * registry client from the first render — so a single guard would be claimed
98
+ * by the pass that could only do the registry half, and the avatar would
99
+ * never be refreshed for the whole visit even though `managers` is a
100
+ * dependency precisely so that it could be.
101
+ *
102
+ * `name` is never touched: it is the user's own label for this person.
103
+ */
104
+ const refreshedAvatarKeyRef = useRef('')
105
+ const refreshedHandleKeyRef = useRef('')
106
+ useEffect(() => {
107
+ if (!identityKey || !store || walletUserId === null || !contact) return
108
+ const idClient = makeIdentityClient(managers?.permissionsManager as never, adminOriginator)
109
+ const registry = getHandleRegistryConfig(selectedNetwork)
110
+ const client = registry ? createHandleRegistryClient({ pinned: registry }) : null
111
+ const wantAvatar = !!idClient && refreshedAvatarKeyRef.current !== identityKey
112
+ const wantHandle = !!client && refreshedHandleKeyRef.current !== identityKey
113
+ if (!wantAvatar && !wantHandle) return
114
+ if (wantAvatar) refreshedAvatarKeyRef.current = identityKey
115
+ if (wantHandle) refreshedHandleKeyRef.current = identityKey
116
+ let cancelled = false
117
+ // A pass that never reaches its decision hands the guard back, so a
118
+ // `contact` that changes mid-lookup (a rename, whose `reload` is a new
119
+ // row) is re-checked instead of losing this visit's refresh. It cannot
120
+ // reopen the loop the guard is for: that path is exactly the one this is
121
+ // true on. Set BEFORE the write, not after: a cancellation landing while
122
+ // the UPDATE is in flight would otherwise repeat both lookups to send the
123
+ // same three columns again.
124
+ let decided = false
125
+ void (async () => {
126
+ const [identity, lookup] = await Promise.all([
127
+ wantAvatar && idClient ? resolveIdentity(idClient, identityKey).then(([, found]) => found) : null,
128
+ // A contact whose cached handle names another domain is looked up
129
+ // there; everyone else on the registry this build is configured for.
130
+ wantHandle && client
131
+ ? client.lookupProfile(identityKey, parsePaymail(contact.cachedHandle ?? '')?.domain)
132
+ : null
133
+ ])
134
+ if (cancelled) return
135
+ // `lookupProfile`, not `lookupIdentityKey`: a `failed` lookup is the
136
+ // registry not having answered, and writing `''` for it would blank a
137
+ // contact's handle every time this screen is opened offline. Only an
138
+ // answer — `found` or `none` — may change the column.
139
+ const learnedHandle = lookup?.kind === 'found' ? lookup.profile.paymail : lookup?.kind === 'none' ? '' : undefined
140
+ const next = mergeContactCache(contact, {
141
+ ...(identity?.avatarURL ? { cachedAvatarUrl: identity.avatarURL } : {}),
142
+ ...(learnedHandle === undefined ? {} : { cachedHandle: learnedHandle })
143
+ })
144
+ decided = true
145
+ if (!next) return
146
+ await store.refreshContactCache(walletUserId, identityKey, next)
147
+ if (!cancelled) void reload().catch(() => {})
148
+ })().catch(() => {})
149
+ return () => {
150
+ cancelled = true
151
+ if (decided) return
152
+ if (wantAvatar) refreshedAvatarKeyRef.current = ''
153
+ if (wantHandle) refreshedHandleKeyRef.current = ''
154
+ }
155
+ }, [identityKey, store, walletUserId, managers, adminOriginator, selectedNetwork, contact, reload])
156
+
157
+ const onDelete = useCallback(async () => {
158
+ if (!store || walletUserId === null || !contact) return
159
+ const choice = await showAlert({
160
+ title: t('contact_delete'),
161
+ message: t('contact_delete_body', { name: contact.name }),
162
+ buttons: [
163
+ { text: t('cancel'), style: 'cancel', key: 'cancel' },
164
+ { text: t('contact_delete'), style: 'destructive', key: 'delete' }
165
+ ]
166
+ })
167
+ if (choice !== 'delete') return
168
+ await store.deleteContact(walletUserId, identityKey)
169
+ router.back()
170
+ }, [store, walletUserId, contact, identityKey, t, router])
171
+
172
+ if (!contact) return <View style={[styles.container, { backgroundColor: colors.background }]} />
173
+
174
+ return (
175
+ <View style={[styles.container, { backgroundColor: colors.background, paddingTop: insets.top }]}>
176
+ <View style={[styles.header, { borderBottomColor: colors.separator }]}>
177
+ <PressableScale
178
+ onPress={() => router.back()}
179
+ haptic="tap"
180
+ style={styles.headerBtn}
181
+ accessibilityRole="button"
182
+ accessibilityLabel={t('go_back')}
183
+ >
184
+ <Ionicons
185
+ name={I18nManager.isRTL ? 'chevron-forward' : 'chevron-back'}
186
+ size={24}
187
+ color={colors.textSecondary}
188
+ />
189
+ </PressableScale>
190
+ <Text style={[styles.headerTitle, { color: colors.textPrimary }]} numberOfLines={1}>
191
+ {contact.name}
192
+ </Text>
193
+ <View style={styles.headerBtn} />
194
+ </View>
195
+
196
+ <ScrollView
197
+ contentContainerStyle={[styles.content, { paddingBottom: Math.max(insets.bottom, spacing.lg) }]}
198
+ keyboardShouldPersistTaps="handled"
199
+ >
200
+ <View style={styles.hero}>
201
+ <ContactSigil identityKey={identityKey} avatarUrl={contact.cachedAvatarUrl} size={72} radius={24} />
202
+ <Text style={[styles.heroName, { color: colors.textPrimary }]} numberOfLines={1}>
203
+ {contact.name}
204
+ </Text>
205
+ {!!contact.cachedHandle && (
206
+ <>
207
+ <Text style={[styles.handle, { color: colors.textSecondary }]}>{contact.cachedHandle}</Text>
208
+ <View style={styles.captionRow}>
209
+ <Ionicons name="shield-checkmark-outline" size={12} color={colors.textTertiary} />
210
+ <Text style={[styles.handleCaption, { color: colors.textTertiary }]}>
211
+ {t('contact_handle_caption')}
212
+ </Text>
213
+ </View>
214
+ </>
215
+ )}
216
+ </View>
217
+
218
+ <GroupedSection header={t('contact_name_section')} footer={t('contact_name_hint')}>
219
+ <PencilEditField
220
+ value={contact.name}
221
+ placeholder={t('contact_new_title')}
222
+ onSave={async next => {
223
+ if (walletUserId === null) return
224
+ await store?.renameContact(walletUserId, identityKey, next)
225
+ void reload()
226
+ }}
227
+ editAccessibilityLabel={t('contact_edit_name')}
228
+ saveAccessibilityLabel={t('contact_save_name')}
229
+ />
230
+ </GroupedSection>
231
+
232
+ <GroupedSection header={t('contact_identifier')}>
233
+ <IdentifierRow identityKey={identityKey} />
234
+ </GroupedSection>
235
+
236
+ <GroupedSection>
237
+ <ListRow
238
+ label={t('contact_delete')}
239
+ icon="trash-outline"
240
+ iconColor={colors.error}
241
+ destructive
242
+ showChevron={false}
243
+ onPress={onDelete}
244
+ isLast
245
+ />
246
+ </GroupedSection>
247
+
248
+ <Text style={[styles.sectionTitle, { color: colors.textTertiary }]}>{t('contact_activity').toUpperCase()}</Text>
249
+ <ContactActivityList items={activity} identityKey={identityKey} />
250
+ </ScrollView>
251
+ </View>
252
+ )
253
+ }
254
+
255
+ export default ContactScreen
256
+
257
+ const styles = StyleSheet.create({
258
+ container: { flex: 1 },
259
+ header: {
260
+ flexDirection: 'row',
261
+ alignItems: 'center',
262
+ justifyContent: 'space-between',
263
+ paddingHorizontal: spacing.sm,
264
+ paddingVertical: spacing.md,
265
+ borderBottomWidth: StyleSheet.hairlineWidth
266
+ },
267
+ headerBtn: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
268
+ headerTitle: { ...typography.headline, fontWeight: '600', flex: 1, textAlign: 'center' },
269
+ content: { paddingTop: spacing.lg },
270
+ hero: {
271
+ alignItems: 'center',
272
+ gap: spacing.sm,
273
+ paddingHorizontal: spacing.xl,
274
+ paddingTop: spacing.sm,
275
+ paddingBottom: spacing.xl
276
+ },
277
+ heroName: { ...typography.title2, fontWeight: '700', marginTop: spacing.xs },
278
+ handle: { ...typography.body, fontWeight: '500' },
279
+ captionRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
280
+ handleCaption: { ...typography.caption1 },
281
+ // Tracked small caps, matching GroupedSection's own header.
282
+ sectionTitle: {
283
+ fontSize: 10.5,
284
+ fontWeight: '700',
285
+ letterSpacing: 1.3,
286
+ paddingHorizontal: spacing.xl,
287
+ paddingBottom: spacing.sm
288
+ }
289
+ })