@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -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 +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -6,30 +6,41 @@ import AppLogo from '../ui/AppLogo'
6
6
  import { sdk } from '@bsv/wallet-toolbox-mobile'
7
7
  import AsyncStorage from '@react-native-async-storage/async-storage'
8
8
 
9
- const BALANCE_CACHE_KEY = 'cached_wallet_balance'
10
- const BALANCE_CACHE_TIMESTAMP_KEY = 'cached_wallet_balance_timestamp'
9
+ // XR-058: scoped by network (matching useSpendableBalance's pattern) rather
10
+ // than a single global key, so one wallet/network context can never read
11
+ // back a figure cached by another. See WalletContext.tsx's logout sweep for
12
+ // the migration cleanup of the legacy unscoped key this replaces.
13
+ const BALANCE_CACHE_PREFIX = 'cached_wallet_balance_'
11
14
  const CACHE_DURATION = 30000 // 30 seconds
12
15
 
13
16
  export default function Balance() {
14
17
  const { colors } = useTheme()
15
- const { managers, adminOriginator, txStatusVersion } = useWallet()
16
- const [accountBalance, setAccountBalance] = React.useState<number | null>(null)
18
+ const { managers, adminOriginator, txStatusVersion, selectedNetwork } = useWallet()
19
+ const cacheKey = `${BALANCE_CACHE_PREFIX}${selectedNetwork}`
20
+ const timestampKey = `${cacheKey}_timestamp`
21
+ // { key, value } rather than a bare number: `key` is compared against the
22
+ // live `cacheKey` everywhere below, so a figure read for a since-departed
23
+ // wallet or network context can never be painted, even if this component
24
+ // stays mounted across a logout or network switch (XR-058).
25
+ const [accountBalance, setAccountBalance] = React.useState<{ key: string; value: number } | null>(null)
17
26
  const [balanceLoading, setBalanceLoading] = React.useState(false)
18
27
  // Read through a ref, not the state value: `accountBalance` in this callback's
19
28
  // deps would give it a new identity on every fetch, re-running both effects
20
29
  // below and firing a second, pointless fetch each time the figure changes.
21
- const accountBalanceRef = React.useRef<number | null>(null)
30
+ const accountBalanceRef = React.useRef<{ key: string; value: number } | null>(null)
22
31
  accountBalanceRef.current = accountBalance
23
32
 
24
33
  const refreshBalance = useCallback(async () => {
25
34
  try {
26
-
27
35
  if (!managers.permissionsManager) {
36
+ // No active wallet context for this network: never leave a previous
37
+ // context's figure on screen (XR-058).
38
+ setAccountBalance(null)
28
39
  return
29
40
  }
30
41
 
31
- // Only show loading if we don't have cached data
32
- if (accountBalanceRef.current === null) {
42
+ // Only show loading if we don't have cached data for this context
43
+ if (accountBalanceRef.current?.key !== cacheKey) {
33
44
  setBalanceLoading(true)
34
45
  }
35
46
 
@@ -40,44 +51,50 @@ export default function Balance() {
40
51
  )
41
52
 
42
53
  const total = totalOutputs ?? 0
43
- setAccountBalance(total)
54
+ setAccountBalance({ key: cacheKey, value: total })
44
55
 
45
56
  // Cache the new balance
46
- await Promise.all([
47
- AsyncStorage.setItem(BALANCE_CACHE_KEY, String(total)),
48
- AsyncStorage.setItem(BALANCE_CACHE_TIMESTAMP_KEY, String(Date.now()))
49
- ])
57
+ await Promise.all([AsyncStorage.setItem(cacheKey, String(total)), AsyncStorage.setItem(timestampKey, String(Date.now()))])
50
58
 
51
59
  setBalanceLoading(false)
52
60
  } catch (e) {
53
61
  console.error('Error refreshing balance:', e)
54
62
  setBalanceLoading(false)
55
63
  }
56
- }, [managers, adminOriginator])
64
+ }, [managers, adminOriginator, cacheKey, timestampKey])
57
65
 
58
- // Load cached balance immediately on mount
66
+ // Load cached balance immediately on mount — but only once a wallet
67
+ // context for this exact network is active. Reading (and painting) the
68
+ // cache before that is exactly how a departed wallet's figure used to leak
69
+ // into a fresh or different-context mount (XR-058).
59
70
  useEffect(() => {
60
71
  let mounted = true
61
72
 
62
73
  const loadCachedBalance = async () => {
74
+ if (!managers.permissionsManager) {
75
+ if (mounted) setAccountBalance(null)
76
+ return
77
+ }
63
78
  try {
64
79
  const [cachedBalance, cachedTimestamp] = await Promise.all([
65
- AsyncStorage.getItem(BALANCE_CACHE_KEY),
66
- AsyncStorage.getItem(BALANCE_CACHE_TIMESTAMP_KEY)
80
+ AsyncStorage.getItem(cacheKey),
81
+ AsyncStorage.getItem(timestampKey)
67
82
  ])
68
83
 
69
- if (mounted && cachedBalance !== null) {
84
+ if (!mounted || !managers.permissionsManager) return
85
+
86
+ if (cachedBalance !== null) {
70
87
  const balance = Number(cachedBalance)
71
88
  const timestamp = Number(cachedTimestamp)
72
89
  const isRecent = timestamp && Date.now() - timestamp < CACHE_DURATION
73
90
 
74
- setAccountBalance(balance)
91
+ setAccountBalance({ key: cacheKey, value: balance })
75
92
 
76
93
  // If cache is old, fetch fresh data
77
94
  if (!isRecent) {
78
95
  refreshBalance()
79
96
  }
80
- } else if (mounted) {
97
+ } else {
81
98
  // No cache, fetch fresh data
82
99
  refreshBalance()
83
100
  }
@@ -91,7 +108,7 @@ export default function Balance() {
91
108
  return () => {
92
109
  mounted = false
93
110
  }
94
- }, [refreshBalance])
111
+ }, [refreshBalance, cacheKey, managers.permissionsManager])
95
112
 
96
113
  // Refresh balance when SSE reports a transaction status change
97
114
  useEffect(() => {
@@ -100,16 +117,18 @@ export default function Balance() {
100
117
  }
101
118
  }, [txStatusVersion, refreshBalance])
102
119
 
120
+ const balance = accountBalance?.key === cacheKey ? accountBalance.value : null
121
+
103
122
  return (
104
123
  <View style={[componentStyles.container, { backgroundColor: colors.paperBackground }]}>
105
124
  <Text style={[componentStyles.sectionTitle, { color: colors.textPrimary }]}>you have</Text>
106
- {accountBalance === null && balanceLoading ? (
125
+ {balance === null && balanceLoading ? (
107
126
  <View style={componentStyles.loadingContainer}>
108
127
  <AppLogo size={50} rotate />
109
128
  </View>
110
129
  ) : (
111
130
  <Text onPress={refreshBalance} style={[componentStyles.balance, { color: colors.textPrimary }]}>
112
- <AmountDisplay abbreviate>{accountBalance ?? 0}</AmountDisplay>
131
+ <AmountDisplay abbreviate>{balance ?? 0}</AmountDisplay>
113
132
  <Text style={[componentStyles.cacheIndicator, { color: colors.textSecondary }]}></Text>
114
133
  </Text>
115
134
  )}
@@ -43,9 +43,15 @@ export const BiometricAdvisoryModal: React.FC<{
43
43
  * looking frozen for that whole stretch, with nothing on screen explaining
44
44
  * why. Keeping the modal up with a spinner in place of the label instead. */
45
45
  loading?: boolean
46
+ /** XR-114: true when this device/build will NOT actually get biometric
47
+ * protection (resolveProvisioningPolicy().disclose) — no strong biometrics
48
+ * enrolled, or a dev build without them. The unconditional "protected by
49
+ * Face ID/fingerprint" promise is false in that case; swap in an honest
50
+ * disclosure instead of silently degrading with no visible change. */
51
+ degraded?: boolean
46
52
  onCancel: () => void
47
53
  onContinue: () => void
48
- }> = ({ visible, loading = false, onCancel, onContinue }) => {
54
+ }> = ({ visible, loading = false, degraded = false, onCancel, onContinue }) => {
49
55
  const { colors } = useTheme()
50
56
  const Ionicons = loadIonicons()
51
57
 
@@ -74,7 +80,9 @@ export const BiometricAdvisoryModal: React.FC<{
74
80
  <Ionicons name="finger-print" size={28} color={colors.accent} />
75
81
  </View>
76
82
  <Text style={[styles.title, { color: colors.textPrimary }]}>{t('biometric_advisory_title')}</Text>
77
- <Text style={[styles.body, { color: colors.textSecondary }]}>{t('biometric_advisory_body')}</Text>
83
+ <Text style={[styles.body, { color: colors.textSecondary }]}>
84
+ {t(degraded ? 'biometric_advisory_body_degraded' : 'biometric_advisory_body')}
85
+ </Text>
78
86
 
79
87
  <PressableScale
80
88
  haptic="confirm"
@@ -89,7 +97,12 @@ export const BiometricAdvisoryModal: React.FC<{
89
97
  )}
90
98
  </PressableScale>
91
99
 
92
- <PressableScale haptic="tap" onPress={loading ? undefined : onCancel} disabled={loading} style={styles.secondary}>
100
+ <PressableScale
101
+ haptic="tap"
102
+ onPress={loading ? undefined : onCancel}
103
+ disabled={loading}
104
+ style={styles.secondary}
105
+ >
93
106
  <Text style={[styles.secondaryLabel, { color: loading ? colors.textTertiary : colors.textSecondary }]}>
94
107
  {t('cancel')}
95
108
  </Text>
@@ -19,6 +19,23 @@ function loadExpoSharing(): typeof import('expo-sharing') {
19
19
 
20
20
  const PAGE = 200
21
21
 
22
+ /**
23
+ * A remote PeerPay/nearby-payment sender's note reaches this file's
24
+ * `description` column verbatim (trimmed, length-capped — see
25
+ * core/pay/rails/handle.ts and core/localpay/pending.ts), and this export is
26
+ * shared as text/csv straight to whatever the OS share sheet opens it in.
27
+ * Any cell whose text begins with `=`, `+`, `-`, `@`, a tab or a carriage
28
+ * return is a live formula/command to spreadsheet software that still
29
+ * evaluates leading-character formulas on open (OWASP CSV Injection). Prefix
30
+ * such a value with a single leading apostrophe first — spreadsheet
31
+ * applications that honor that convention render it as literal text, and the
32
+ * original content is still fully visible rather than dropped — before the
33
+ * existing delimiter/quote escaping below runs.
34
+ */
35
+ function neutralizeFormula(s: string): string {
36
+ return /^[=+\-@\t\r]/.test(s) ? `'${s}` : s
37
+ }
38
+
22
39
  function csvEscape(v: unknown): string {
23
40
  if (v == null) return ''
24
41
  const s = String(v)
@@ -26,6 +43,21 @@ function csvEscape(v: unknown): string {
26
43
  return s
27
44
  }
28
45
 
46
+ /**
47
+ * Same as csvEscape, but for the columns that can carry attacker-controlled
48
+ * free text (description, tags, labels, outputDescriptions) — these alone
49
+ * are run through neutralizeFormula first. Columns that are always
50
+ * app-derived (txid, satoshis, status, blockHeight) use plain csvEscape:
51
+ * `satoshis` in particular is a signed number whose string form starts with
52
+ * '-' for every outgoing transaction, which would otherwise trip
53
+ * neutralizeFormula's leading-character check and corrupt a plain numeric
54
+ * cell (e.g. `-50000`) into text (`'-50000`) for no security benefit.
55
+ */
56
+ function csvEscapeUntrusted(v: unknown): string {
57
+ if (v == null) return ''
58
+ return csvEscape(neutralizeFormula(String(v)))
59
+ }
60
+
29
61
  /**
30
62
  * Exports all wallet transactions as a CSV file via the OS share dialog.
31
63
  * Columns: txid, satoshis (signed), description, status, blockHeight,
@@ -91,12 +123,12 @@ export async function exportTransactionsAsCsv(
91
123
  return [
92
124
  csvEscape(a.txid),
93
125
  csvEscape(sats),
94
- csvEscape(a.description),
126
+ csvEscapeUntrusted(a.description),
95
127
  csvEscape(a.status),
96
128
  csvEscape(height),
97
- csvEscape(tags),
98
- csvEscape(labels),
99
- csvEscape(outDescs)
129
+ csvEscapeUntrusted(tags),
130
+ csvEscapeUntrusted(labels),
131
+ csvEscapeUntrusted(outDescs)
100
132
  ].join(',')
101
133
  })
102
134
 
@@ -9,10 +9,23 @@
9
9
  * Lifted from WalletConfigScreen.handleExportData so both screens share one
10
10
  * implementation: one export at a time, `exporting` for the spinner, failures
11
11
  * logged rather than surfaced (a dismissed share sheet is not an error).
12
+ *
13
+ * XR-086: exportAllWalletDatabases() writes the raw, unencrypted SQLite image
14
+ * straight to the OS share sheet — identity keys, certificate fields,
15
+ * transaction/derivation metadata and contacts, with no passphrase or
16
+ * authenticated-encryption step. Wrapping it in one would need a product
17
+ * decision this hook cannot make alone (how the *importing* device gets the
18
+ * key/passphrase back — see importDatabases.ts, which has no decrypt step
19
+ * either); that is recorded as a design delta on XR-086, not silently
20
+ * skipped. What actually ships here is the part that needs no such decision:
21
+ * an explicit warning naming what the file contains and that it is not
22
+ * encrypted, with a real chance to back out, shared by both call sites since
23
+ * they both go through this one hook.
12
24
  */
13
25
  import { useCallback, useRef, useState } from 'react'
14
- import { useWallet } from '@bsv/expo-wallet-toolbox'
26
+ import { i18n, useWallet } from '@bsv/expo-wallet-toolbox'
15
27
  import { exportAllWalletDatabases } from '../exportDatabases'
28
+ import { showAlert } from '../components/ui/AlertCard'
16
29
 
17
30
  export function useExportWalletData(): { exportData: () => Promise<void>; exporting: boolean } {
18
31
  const { storage } = useWallet()
@@ -24,8 +37,18 @@ export function useExportWalletData(): { exportData: () => Promise<void>; export
24
37
  const exportData = useCallback(async () => {
25
38
  if (inFlightRef.current) return
26
39
  inFlightRef.current = true
27
- setExporting(true)
28
40
  try {
41
+ const choice = await showAlert({
42
+ title: i18n.t('export_unencrypted_title'),
43
+ message: i18n.t('export_unencrypted_message'),
44
+ buttons: [
45
+ { text: i18n.t('cancel'), style: 'cancel', key: 'cancel' },
46
+ { text: i18n.t('export_wallet_data'), style: 'destructive', key: 'export' }
47
+ ]
48
+ })
49
+ if (choice !== 'export') return
50
+ // The spinner means "exporting", not "waiting for you to answer".
51
+ setExporting(true)
29
52
  await exportAllWalletDatabases(storage)
30
53
  } catch (e) {
31
54
  console.warn('[exportWalletData] Export failed:', e)