@bsv/expo-wallet-toolbox 0.7.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 (151) hide show
  1. package/CHANGELOG.md +1745 -0
  2. package/README.md +47 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  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/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +631 -162
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/syncHeaders.ts +12 -1
  24. package/core/i18n/translations.tsx +953 -25
  25. package/core/identity/handleRegistry/client.ts +31 -2
  26. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  27. package/core/identity/handleRegistry/resolver.ts +71 -3
  28. package/core/index.ts +33 -3
  29. package/core/localpay/build.ts +225 -24
  30. package/core/localpay/pending.ts +110 -7
  31. package/core/localpay/pendingAbortAuthority.ts +95 -0
  32. package/core/localpay/pendingAborts.ts +264 -28
  33. package/core/localpay/session.ts +42 -17
  34. package/core/localpay/settlementAck.ts +10 -1
  35. package/core/localpay/transport/socket.ts +52 -3
  36. package/core/localpay/verify.ts +100 -10
  37. package/core/mandala/abortGuard.ts +96 -20
  38. package/core/mandala/createRuntime.ts +206 -33
  39. package/core/mandala/drain.ts +89 -11
  40. package/core/mandala/inboxPrehold.ts +186 -0
  41. package/core/mandala/permissionModule.ts +202 -20
  42. package/core/mandala/settlementStore.ts +24 -2
  43. package/core/mandala/types.ts +40 -5
  44. package/core/monitor/TaskBackupPush.ts +14 -0
  45. package/core/monitor/TaskDrainOutbox.ts +14 -0
  46. package/core/monitor/TaskSendOffline.ts +14 -0
  47. package/core/net/publicDestination.ts +91 -0
  48. package/core/net/validateArcUrl.ts +22 -0
  49. package/core/offline/cancelParked.ts +134 -13
  50. package/core/offline/payerHold.ts +100 -24
  51. package/core/offline/plan.ts +36 -7
  52. package/core/pay/beefRepair.ts +6 -2
  53. package/core/pay/damagedInbox.ts +24 -0
  54. package/core/pay/rails/address.ts +107 -12
  55. package/core/pay/rails/handle.ts +117 -22
  56. package/core/pay/rails/index.ts +45 -7
  57. package/core/pay/rails/nativeIntent.ts +61 -0
  58. package/core/pay/receiveHistory.ts +93 -0
  59. package/core/pay/recordProof.ts +19 -1
  60. package/core/pay/refreshProofGuard.ts +42 -1
  61. package/core/pay/watchlist.ts +5 -2
  62. package/core/peerpay/control.ts +17 -18
  63. package/core/peerpay/handleResendRequests.ts +58 -4
  64. package/core/peerpay/outbox.ts +3 -1
  65. package/core/recovery/backupMaterial.ts +61 -0
  66. package/core/recovery/createWallet.ts +95 -0
  67. package/core/recovery/recoverWallet.ts +120 -0
  68. package/core/recovery/restoreWallet.ts +170 -0
  69. package/core/recovery/secret.ts +92 -0
  70. package/core/recovery/shareCollector.ts +71 -0
  71. package/core/recovery/shareParsing.ts +87 -0
  72. package/core/recovery/shares.ts +116 -0
  73. package/core/recovery/useRecoveryDeps.ts +70 -0
  74. package/core/services/arcTokenStorage.ts +52 -0
  75. package/core/services/arcadeBroadcastProvider.ts +232 -48
  76. package/core/services/autoApprovePolicy.ts +105 -0
  77. package/core/services/callbackToken.ts +19 -0
  78. package/core/services/capWalletArgs.ts +14 -2
  79. package/core/services/connectionAuthority.ts +98 -0
  80. package/core/services/exchangeRate.ts +35 -12
  81. package/core/services/externalOrigin.ts +11 -0
  82. package/core/services/secrets/kek.ts +126 -29
  83. package/core/services/secrets/migration.ts +16 -4
  84. package/core/services/secrets/store.ts +42 -14
  85. package/core/services/vault/VaultKeyService.ts +228 -45
  86. package/core/services/vault/chainRecovery.ts +483 -0
  87. package/core/services/vault/driver.ts +9 -1
  88. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  89. package/core/services/vault/guard.ts +218 -32
  90. package/core/services/vault/hardwareLease.ts +19 -0
  91. package/core/services/vault/metaAuthority.ts +210 -0
  92. package/core/services/vault/pivReset.ts +64 -23
  93. package/core/services/vault/r1comb.ts +139 -3
  94. package/core/services/vault/session.ts +25 -4
  95. package/core/services/vault/transfers.ts +866 -170
  96. package/core/services/vault/types.ts +19 -4
  97. package/core/services/vault/vaultStore.ts +256 -29
  98. package/core/services/walletArgLimits.ts +45 -2
  99. package/core/services/walletConnectionValidation.ts +76 -6
  100. package/core/services/walletServiceConfig.ts +10 -8
  101. package/core/storage/StorageExpoSQLite.ts +47 -13
  102. package/core/storage/methods/findSql.ts +21 -2
  103. package/core/storage/methods/offlineActions.ts +10 -1
  104. package/core/storage/methods/processOfflineActions.ts +116 -23
  105. package/core/storage/schema/createTables.ts +126 -2
  106. package/core/stores/ConnectionStore.ts +34 -0
  107. package/core/toolboxConfig.ts +45 -11
  108. package/core/walletDbRegistry.ts +63 -0
  109. package/core/walletMonitor.ts +17 -1
  110. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  111. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  112. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  113. package/package.json +2 -2
  114. package/ui/backupShares.ts +26 -169
  115. package/ui/components/pay/AddressReceive.tsx +13 -6
  116. package/ui/components/pay/AssetPicker.tsx +30 -9
  117. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  118. package/ui/components/pay/NearbyFlow.tsx +480 -243
  119. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  120. package/ui/components/pay/UniversalSend.tsx +167 -73
  121. package/ui/components/ui/AlertCard.tsx +38 -5
  122. package/ui/components/ui/PermissionSheet.tsx +197 -66
  123. package/ui/components/vault/EnrollWizard.tsx +61 -13
  124. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  125. package/ui/components/wallet/ActivityRow.tsx +5 -3
  126. package/ui/components/wallet/AmountInput.tsx +8 -2
  127. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  128. package/ui/components/wallet/Balance.tsx +42 -23
  129. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  130. package/ui/exportTransactions.ts +36 -4
  131. package/ui/hooks/useExportWalletData.ts +25 -2
  132. package/ui/importDatabases.ts +339 -24
  133. package/ui/index.ts +9 -3
  134. package/ui/isImageUrl.ts +6 -0
  135. package/ui/printRecoveryShares.ts +9 -10
  136. package/ui/recoveryPrompts.ts +91 -0
  137. package/ui/resolveIdentity.ts +31 -9
  138. package/ui/screens/ConnectionsScreen.tsx +86 -19
  139. package/ui/screens/IdentifierScreen.tsx +30 -8
  140. package/ui/screens/PairScreen.tsx +74 -2
  141. package/ui/screens/SettingsScreen.tsx +10 -4
  142. package/ui/screens/TrustScreen.tsx +99 -4
  143. package/ui/screens/VaultScreen.tsx +410 -61
  144. package/ui/screens/VaultTransferScreen.tsx +59 -7
  145. package/ui/screens/WalletCheckScreen.tsx +17 -6
  146. package/ui/screens/WalletConfigScreen.tsx +82 -28
  147. package/ui/screens/WalletHomeScreen.tsx +179 -88
  148. package/ui/screens/detailActionKeys.ts +55 -0
  149. package/ui/tokenFormat.ts +44 -4
  150. package/ui/txStatus.ts +5 -0
  151. 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
@@ -74,19 +74,41 @@ export function IdentifierScreen() {
74
74
  name?: string | string[]
75
75
  handle?: string | string[]
76
76
  }>()
77
- const [identityKey, setIdentityKey] = useState(firstParam(params.identityKey) ?? '')
78
- const name = firstParam(params.name) ?? ''
79
- const handle = firstParam(params.handle) ?? ''
77
+ const routeIdentityKey = firstParam(params.identityKey) ?? ''
78
+ const routeName = firstParam(params.name) ?? ''
79
+ const routeHandle = firstParam(params.handle) ?? ''
80
80
 
81
- // Profile passes the key along; a cold deep link into this screen fetches it.
81
+ /**
82
+ * The route's `identityKey` is untrusted input, not a value this screen can
83
+ * act on directly: this is "Your Identifier", reached from a deep link
84
+ * (`app/identifier.tsx`, via `resolveNativeIntent`) that carries no
85
+ * blocklist for it, and Profile's own push of its already-known key is only
86
+ * an optimization, not the source of truth. So the wallet's own key is
87
+ * always fetched, and it is the ONLY value ever used to build the QR/copy/
88
+ * share link — the route value is never rendered there, only compared
89
+ * against it (XR-070 / SEC2-061).
90
+ */
91
+ const [walletKey, setWalletKey] = useState<string | null>(null)
82
92
  useEffect(() => {
83
- if (identityKey) return
84
93
  const wallet = managers?.permissionsManager
85
- if (!wallet) return
94
+ if (!wallet || typeof wallet.getPublicKey !== 'function') return
95
+ let cancelled = false
86
96
  void wallet.getPublicKey({ identityKey: true }, adminOriginator).then(r => {
87
- if (r?.publicKey) setIdentityKey(r.publicKey)
97
+ if (!cancelled && r?.publicKey) setWalletKey(r.publicKey)
88
98
  })
89
- }, [identityKey, managers, adminOriginator])
99
+ return () => {
100
+ cancelled = true
101
+ }
102
+ }, [managers, adminOriginator])
103
+
104
+ const identityKey = walletKey ?? ''
105
+ // The route's name/handle are cosmetic labels, but they are shown only when
106
+ // the route's identityKey hint actually matches the wallet's own resolved
107
+ // key — otherwise they are exactly as untrustworthy as the key would have
108
+ // been, and abbreviateKey(identityKey) below already covers "no label yet".
109
+ const routeMatchesWallet = walletKey !== null && routeIdentityKey.toLowerCase() === walletKey.toLowerCase()
110
+ const name = routeMatchesWallet ? routeName : ''
111
+ const handle = routeMatchesWallet ? routeHandle : ''
90
112
 
91
113
  const link = identityKey ? contactAddLinkFor(identityKey) : ''
92
114
 
@@ -7,6 +7,7 @@ import {
7
7
  SafeAreaView,
8
8
  ActivityIndicator,
9
9
  } from 'react-native'
10
+ import AsyncStorage from '@react-native-async-storage/async-storage'
10
11
  import { WalletClient } from '@bsv/sdk'
11
12
  import {
12
13
  useWallet,
@@ -18,8 +19,13 @@ import {
18
19
  guardVaultAccess,
19
20
  capWalletArgs,
20
21
  ADMIN_ORIGINATOR,
21
- parseExternalOrigin
22
+ parseExternalOrigin,
23
+ connectionStore,
24
+ DEFAULT_AUTO_APPROVE_THRESHOLD,
25
+ AUTO_APPROVE_STORAGE_KEY,
26
+ AUTO_APPROVE_DAILY_CAP_SATS
22
27
  } from '@bsv/expo-wallet-toolbox'
28
+ import { computeConnectionAuthorityTag } from '../../core/services/connectionAuthority'
23
29
 
24
30
  /**
25
31
  * expo-router is required lazily rather than imported at module scope: this
@@ -62,6 +68,21 @@ export function PairScreen() {
62
68
  // Pre-connection validation error (before connect() is called)
63
69
  const [preConnectError, setPreConnectError] = useState<string | null>(null)
64
70
 
71
+ // XR-023: the ONLY value ever shown to the user pre-approval must be the
72
+ // same validated/canonicalized origin handleApprove authorizes — never the
73
+ // raw, attacker-controlled route param. Set once validation below passes.
74
+ const [canonicalOrigin, setCanonicalOrigin] = useState<string | null>(null)
75
+
76
+ // XR-028: the standing auto-spend authority a paired origin gets was never
77
+ // disclosed at approval time. Read the SAME persisted threshold WalletContext
78
+ // reads for spendingAuthorizationCallback — 0/unset means auto-approve is off.
79
+ const [autoApproveThreshold, setAutoApproveThreshold] = useState(DEFAULT_AUTO_APPROVE_THRESHOLD)
80
+ useEffect(() => {
81
+ AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY)
82
+ .then(v => { if (v !== null) setAutoApproveThreshold(Number(v) || 0) })
83
+ .catch(() => {})
84
+ }, [])
85
+
65
86
  // Whether this mount is a reconnect (explicitly passed from connections screen)
66
87
  const isReconnect = params.reconnect === 'true'
67
88
 
@@ -91,6 +112,15 @@ export function PairScreen() {
91
112
  setPreConnectError('QR code has expired')
92
113
  return
93
114
  }
115
+ // Canonicalize BEFORE it is ever rendered — the same validator
116
+ // handleApprove uses, run up front instead of only at Approve time, so
117
+ // the displayed value and the authorized value are never different
118
+ // objects. An unparseable origin must never reach the Approve card.
119
+ try {
120
+ setCanonicalOrigin(parseExternalOrigin(origin).originator)
121
+ } catch (err) {
122
+ setPreConnectError(err instanceof Error ? err.message : 'Origin URL is not valid')
123
+ }
94
124
  }, []) // eslint-disable-line react-hooks/exhaustive-deps
95
125
 
96
126
  // Nav timer — start when leaving this screen, cancel when returning
@@ -114,6 +144,31 @@ export function PairScreen() {
114
144
  capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)),
115
145
  external.originator
116
146
  )
147
+ // XR-027: stage a saved-pairing authority tag for the EXACT tuple the
148
+ // user is approving on this screen, BEFORE connect() ever runs — with
149
+ // an ADMIN-scoped wallet, never `wallet` above (that one is scoped to
150
+ // the peer's own originator and would let the peer mint this tag
151
+ // itself; see connectionAuthority.ts). connectionStore.add() (deep
152
+ // inside connect()'s websocket-open callback, which never sees an
153
+ // admin wallet) consumes the staged tag the moment it creates the
154
+ // record. A failure here must never block a pairing the user just
155
+ // explicitly approved — it only means this record starts out
156
+ // untagged, which reconnect treats as "needs re-approval" later,
157
+ // exactly like a tampered record; it is never a silent downgrade of
158
+ // trust for the live session being approved right now.
159
+ try {
160
+ const adminWallet = capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR))
161
+ const tag = await computeConnectionAuthorityTag(adminWallet, ADMIN_ORIGINATOR, {
162
+ origin: external.origin,
163
+ topic: params.topic,
164
+ protocolID: params.protocolID,
165
+ backendIdentityKey: params.backendIdentityKey,
166
+ })
167
+ connectionStore.stageAuthorityTag(params.topic, tag)
168
+ } catch (err) {
169
+ console.warn('[PairScreen] failed to compute connection authority tag', err)
170
+ connectionStore.discardStagedAuthorityTag(params.topic)
171
+ }
117
172
  await connect({
118
173
  topic: params.topic,
119
174
  backendIdentityKey: params.backendIdentityKey,
@@ -172,13 +227,30 @@ export function PairScreen() {
172
227
  <View style={styles.infoBox}>
173
228
  <View style={styles.infoRow}>
174
229
  <Text style={styles.infoLabel}>Origin</Text>
175
- <Text style={styles.infoValue} numberOfLines={1}>{params.origin}</Text>
230
+ {/* ellipsizeMode="middle" (not RN's tail-truncating default)
231
+ keeps the registrable-domain suffix visible even for a long
232
+ attacker-chosen hostname designed to hide it behind a
233
+ trustworthy-looking prefix. */}
234
+ <Text style={styles.infoValue} numberOfLines={1} ellipsizeMode="middle">
235
+ {canonicalOrigin ?? ''}
236
+ </Text>
176
237
  </View>
177
238
  <View style={styles.divider} />
178
239
  <View style={styles.infoRow}>
179
240
  <Text style={styles.infoLabel}>Permissions</Text>
180
241
  <Text style={styles.infoValue}>getPublicKey, listOutputs + more</Text>
181
242
  </View>
243
+ {autoApproveThreshold > 0 && (
244
+ <>
245
+ <View style={styles.divider} />
246
+ <View style={styles.infoRow}>
247
+ <Text style={styles.infoLabel}>Auto-approve</Text>
248
+ <Text style={styles.infoValue}>
249
+ Up to {autoApproveThreshold.toLocaleString()} sats per request, {AUTO_APPROVE_DAILY_CAP_SATS.toLocaleString()} sats/24h total, without asking
250
+ </Text>
251
+ </View>
252
+ </>
253
+ )}
182
254
  </View>
183
255
 
184
256
  <View style={styles.buttonRow}>
@@ -1,7 +1,7 @@
1
1
  import React, { useState, useEffect, useCallback } from 'react'
2
2
  import { View, Text, ScrollView, StyleSheet } from 'react-native'
3
3
  import { useTranslation } from 'react-i18next'
4
- import { useTheme, spacing, typography, useWallet, isVaultAvailable } from '@bsv/expo-wallet-toolbox'
4
+ import { useTheme, spacing, typography, useWallet, isVaultAvailable, useVault } from '@bsv/expo-wallet-toolbox'
5
5
  import { GroupedSection } from '../components/ui/GroupedList'
6
6
  import { ListRow } from '../components/ui/ListRow'
7
7
  import AmountDisplay from '../components/wallet/AmountDisplay'
@@ -37,6 +37,11 @@ export function SettingsScreen() {
37
37
  // Read during render, from the reactive network, so the row disappears on a
38
38
  // switch to testnet without a remount.
39
39
  const vaultAvailable = isVaultAvailable(selectedNetwork)
40
+ // F-07: an existing, already-funded vault stays reachable even when the
41
+ // flag is off or the network switched — see showVaultRow below. VaultScreen
42
+ // itself is never gated on that flag for withdraw.
43
+ const { hasVaultMeta } = useVault()
44
+ const showVaultRow = vaultAvailable || hasVaultMeta
40
45
 
41
46
  const balanceCacheKey = `cached_wallet_balance_${selectedNetwork}`
42
47
  const balanceCacheTimestampKey = `cached_wallet_balance_ts_${selectedNetwork}`
@@ -136,11 +141,12 @@ export function SettingsScreen() {
136
141
  icon="swap-horizontal-outline"
137
142
  iconColor={colors.success}
138
143
  onPress={() => router.push('/pay')}
139
- isLast={!vaultAvailable}
144
+ isLast={!showVaultRow}
140
145
  />
141
146
  {/* Same release and network gate as the home screen's Vault
142
- destination (spec §5.5, task 11). */}
143
- {vaultAvailable && (
147
+ destination (spec §5.5, task 11), plus the F-07 OR for an
148
+ existing enrollment. */}
149
+ {showVaultRow && (
144
150
  <ListRow
145
151
  label={t('vault_row_title')}
146
152
  icon="safe"
@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next'
17
17
  // settings types.
18
18
  import type { Certifier as WalletCertifier } from '@bsv/wallet-toolbox-mobile'
19
19
  import validateTrust from '../validateTrust'
20
+ import { isPublicHttpsUrl } from '../../core/net/publicDestination'
20
21
  import { GroupedSection } from '../components/ui/GroupedList'
21
22
  import { showAlert } from '../components/ui/AlertCard'
22
23
  import { haptics, useTheme, spacing, radii, typography, useWallet } from '@bsv/expo-wallet-toolbox'
@@ -156,13 +157,93 @@ const orderChanged = (a: Certifier[], b: Certifier[]): boolean => {
156
157
 
157
158
  const fetchWithTimeout = async (url: string, ms: number) => {
158
159
  const controller = new AbortController()
160
+ const startedAt = Date.now()
159
161
  const id = setTimeout(() => controller.abort(), ms)
162
+ let res: Response
160
163
  try {
161
- const res = await fetch(url, { signal: controller.signal })
162
- return res
164
+ // `redirect: 'error'` so an on-path attacker cannot substitute the origin
165
+ // a trust-provider manifest is fetched from by redirecting the entered
166
+ // HTTPS origin somewhere else (XR-076 / SEC2-011) — a legitimate provider
167
+ // has no reason to redirect its own manifest.json.
168
+ res = await fetch(url, { signal: controller.signal, redirect: 'error' })
163
169
  } finally {
164
170
  clearTimeout(id)
165
171
  }
172
+ // XR-075 (SEC2-090): `id` above bounds only the connection/headers --
173
+ // clearing it as soon as fetch() resolves left body consumption (the
174
+ // caller's later res.json()) completely unbounded: a provider that answers
175
+ // instantly and then stalls or drips its body could hang this screen's
176
+ // loading state forever. Mirrors core/identity/handleRegistry/resolver.ts's
177
+ // fetchWithTimeout: a second timer, scoped to the remaining time budget,
178
+ // keeps the same AbortController live through body consumption too, and
179
+ // the byte cap from readBoundedManifestJson (XR-074) applies here as well.
180
+ const originalJson = res.json.bind(res)
181
+ res.json = () =>
182
+ new Promise((resolve, reject) => {
183
+ const bodyTimer = setTimeout(
184
+ () => {
185
+ controller.abort()
186
+ reject(new Error(`The domain did not respond within ${Math.round(ms / 1000)} seconds`))
187
+ },
188
+ Math.max(0, ms - (Date.now() - startedAt))
189
+ )
190
+ void readBoundedManifestJson(res, originalJson)
191
+ .then(resolve, reject)
192
+ .finally(() => clearTimeout(bodyTimer))
193
+ })
194
+ return res
195
+ }
196
+
197
+ /**
198
+ * XR-074 (SEC2-012): every other JSON-consuming call site in the handle
199
+ * registry (resolver.ts's readBoundedJson, XR-077) bounds body bytes before
200
+ * parsing — this screen's own manifest fetch never got that treatment. A
201
+ * malicious or compromised trust-provider domain could otherwise answer with
202
+ * an arbitrarily large body and force a full JSON parse/allocation before
203
+ * validateTrust ever runs. A BRC-68 manifest is a few hundred bytes of JSON;
204
+ * this ceiling is comfortably over anything real while still bounding an
205
+ * attacker-controlled response.
206
+ */
207
+ const MAX_TRUST_MANIFEST_BYTES = 64 * 1024
208
+
209
+ /**
210
+ * Mirrors core/identity/handleRegistry/resolver.ts's readBoundedJson: a
211
+ * declared Content-Length over the cap is refused before anything is read;
212
+ * otherwise, when the runtime exposes the body as a stream, chunks are
213
+ * counted as they arrive and the read is aborted the instant the running
214
+ * total crosses the cap. `fallback` (the runtime's own `response.json`) is
215
+ * used only when no stream is available to count from.
216
+ */
217
+ async function readBoundedManifestJson(res: Response, fallback: () => Promise<unknown>): Promise<unknown> {
218
+ const declared = res.headers?.get?.('content-length')
219
+ if (declared) {
220
+ const n = Number(declared)
221
+ if (Number.isFinite(n) && n > MAX_TRUST_MANIFEST_BYTES) {
222
+ throw new Error(`Trust manifest declared ${n} bytes, over the ${MAX_TRUST_MANIFEST_BYTES} byte limit`)
223
+ }
224
+ }
225
+ const reader = (res as { body?: ReadableStream<Uint8Array> | null }).body?.getReader?.()
226
+ if (!reader) return await fallback()
227
+ const chunks: Uint8Array[] = []
228
+ let total = 0
229
+ for (;;) {
230
+ const { done, value } = await reader.read()
231
+ if (done) break
232
+ if (!value) continue
233
+ total += value.byteLength
234
+ if (total > MAX_TRUST_MANIFEST_BYTES) {
235
+ await reader.cancel().catch(() => {})
236
+ throw new Error(`Trust manifest exceeded the ${MAX_TRUST_MANIFEST_BYTES} byte limit while streaming`)
237
+ }
238
+ chunks.push(value)
239
+ }
240
+ const merged = new Uint8Array(total)
241
+ let offset = 0
242
+ for (const chunk of chunks) {
243
+ merged.set(chunk, offset)
244
+ offset += chunk.byteLength
245
+ }
246
+ return JSON.parse(new TextDecoder().decode(merged))
166
247
  }
167
248
 
168
249
  // -------------------- Main Screen --------------------
@@ -465,7 +546,21 @@ function AddProviderModal({
465
546
  if (!domain) return
466
547
  setLoading(true)
467
548
  setDomainError(null)
468
- const url = domain.startsWith('http') ? `${domain}/manifest.json` : `https://${domain}/manifest.json`
549
+ // An explicit http:// origin is a downgrade a passive network attacker
550
+ // can force just by intercepting the connection — refuse it outright
551
+ // rather than fetching it (XR-076 / SEC2-011). A bare domain always
552
+ // resolves to https://; an explicit https:// origin is passed through.
553
+ if (/^http:\/\//i.test(domain)) {
554
+ throw new Error('Trust providers must be imported over https://')
555
+ }
556
+ const url = domain.startsWith('https://') ? `${domain}/manifest.json` : `https://${domain}/manifest.json`
557
+ // A user-typed domain needs no DNS trickery to reach a loopback or
558
+ // private-network service directly (XR-073 / SEC2-057, SEC2-076) —
559
+ // refuse it before making the request, same host-class check the
560
+ // handle registry applies to a foreign domain's own capabilities.
561
+ if (!isPublicHttpsUrl(url)) {
562
+ throw new Error('That domain does not name a public trust provider')
563
+ }
469
564
  let res: Response
470
565
  try {
471
566
  res = await fetchWithTimeout(url, 15000)
@@ -474,7 +569,7 @@ function AddProviderModal({
474
569
  throw new Error('Could not fetch the trust data from that domain (it needs to follow the BRC-68 protocol)')
475
570
  }
476
571
  if (!res.ok) throw new Error('Failed to fetch trust manifest from that domain')
477
- const json = await res.json()
572
+ const json = (await res.json()) as any
478
573
  const trust = json?.babbage?.trust
479
574
  if (!json?.babbage || !trust || typeof trust !== 'object') {
480
575
  throw new Error('This domain does not support importing a trust relationship (it needs to follow the BRC-68 protocol)')