@bsv/expo-wallet-toolbox 0.4.0 → 0.5.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 (118) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +0 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +9 -1
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +409 -20
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +97 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/storage/StorageExpoSQLite.ts +382 -56
  54. package/core/storage/dbImage.ts +48 -0
  55. package/core/storage/methods/findSql.ts +0 -54
  56. package/core/storage/methods/listOutputsSql.ts +7 -3
  57. package/core/storage/methods/offlineActions.ts +15 -0
  58. package/core/storage/methods/processOfflineActions.ts +263 -6
  59. package/core/storage/methods/walletBalanceSql.ts +16 -4
  60. package/core/storage/schema/createTables.ts +123 -0
  61. package/core/storage/sqlUpdateValue.ts +24 -0
  62. package/core/toolboxConfig.ts +112 -1
  63. package/core/walletRepair/runWalletCheck.ts +19 -2
  64. package/package.json +25 -24
  65. package/ui/components/QRScanner.tsx +1 -1
  66. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  67. package/ui/components/pay/AssetPicker.tsx +184 -0
  68. package/ui/components/pay/AvailableBalance.tsx +33 -2
  69. package/ui/components/pay/HandleReceive.tsx +213 -50
  70. package/ui/components/pay/NearbyFlow.tsx +616 -69
  71. package/ui/components/pay/PayForm.tsx +73 -8
  72. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  73. package/ui/components/pay/RecipientField.tsx +49 -4
  74. package/ui/components/pay/RequestHub.tsx +68 -8
  75. package/ui/components/pay/ResultBanner.tsx +41 -4
  76. package/ui/components/pay/UniversalSend.tsx +534 -30
  77. package/ui/components/pay/tokenSendCopy.ts +116 -0
  78. package/ui/components/pay/useRecipientInput.ts +36 -7
  79. package/ui/components/ui/PermissionSheet.tsx +65 -4
  80. package/ui/components/ui/Sheet.tsx +9 -2
  81. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  82. package/ui/components/vault/KeyChooser.tsx +96 -0
  83. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  84. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  85. package/ui/components/wallet/ActivityRow.tsx +101 -17
  86. package/ui/components/wallet/AmountInput.tsx +77 -25
  87. package/ui/components/wallet/AssetAmount.tsx +95 -0
  88. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  89. package/ui/components/wallet/tokenEviction.ts +65 -0
  90. package/ui/hooks/useExportWalletData.ts +39 -0
  91. package/ui/hooks/useMandala.ts +303 -0
  92. package/ui/hooks/useVaultBalance.ts +105 -7
  93. package/ui/hooks/useVaultCoverage.ts +52 -0
  94. package/ui/importDatabases.ts +7 -3
  95. package/ui/index.ts +50 -7
  96. package/ui/screens/ConnectionsScreen.tsx +46 -29
  97. package/ui/screens/PairScreen.tsx +12 -12
  98. package/ui/screens/PayScreen.tsx +130 -10
  99. package/ui/screens/SettingsScreen.tsx +18 -9
  100. package/ui/screens/VaultScreen.tsx +925 -171
  101. package/ui/screens/VaultTransferScreen.tsx +376 -123
  102. package/ui/screens/WalletCheckScreen.tsx +10 -1
  103. package/ui/screens/WalletConfigScreen.tsx +38 -16
  104. package/ui/screens/WalletHomeScreen.tsx +417 -86
  105. package/ui/screens/homeBadges.ts +9 -1
  106. package/ui/screens/tokenRowTitle.ts +68 -0
  107. package/ui/tokenFormat.ts +108 -0
  108. package/ui/tokenSeen.ts +75 -0
  109. package/ui/tokenStatus.ts +79 -0
  110. package/assets/sounds/vault-close.wav +0 -0
  111. package/assets/sounds/vault-open.wav +0 -0
  112. package/core/services/vault/k1.ts +0 -75
  113. package/core/services/vault/sealing.ts +0 -84
  114. package/core/services/vault/vaultDerivation.ts +0 -152
  115. package/core/services/vault/vaultPassphrase.ts +0 -287
  116. package/ui/components/vault/PassphraseField.tsx +0 -306
  117. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  118. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -4,6 +4,13 @@
4
4
  * excludes vault funds). Refreshes on txStatusVersion bumps and on demand
5
5
  * after a transfer.
6
6
  *
7
+ * The figure lives in a module-level store rather than in each caller's state,
8
+ * so every mounted reader shows the same number and a screen that mounts after
9
+ * a read starts from it instead of from "unknown" — which both screens render
10
+ * as `balance ?? 0`, making a funded vault look emptied. The store is keyed to
11
+ * the permissions manager it was read through, so a wallet switch reads as
12
+ * unknown rather than showing the previous wallet's vault.
13
+ *
7
14
  * FROZEN while a transfer is mid-flight (ceremony phase 'preparing' /
8
15
  * 'broadcasting'): in that window the spent vault UTXO is gone and its change
9
16
  * is still unsent, so a fetch reads 0 — a partial withdrawal would flash
@@ -11,18 +18,110 @@
11
18
  * transition refetches, covering any txStatusVersion bumps the freeze
12
19
  * swallowed.
13
20
  */
14
- import { useCallback, useEffect, useRef, useState } from 'react'
21
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
15
22
  import { useWallet, useVault, getVaultBalance, type VaultWallet } from '@bsv/expo-wallet-toolbox'
16
23
 
24
+ /**
25
+ * How long the store keeps showing a transfer's expected figure while reads
26
+ * still disagree with it. The freeze above covers the ceremony itself; this
27
+ * covers the tail AFTER it, where a read is successful and wrong.
28
+ *
29
+ * Measured in TIME, not in reads. Every mounted screen answers every
30
+ * invalidation and the monitor bumps txStatusVersion besides, so a budget
31
+ * counted in reads is spent in a second or two by sheer traffic — nothing to
32
+ * do with how long the wallet actually takes to agree. Retries back off so a
33
+ * long window costs a handful of reads rather than a hundred; each one is a
34
+ * full authenticated vault scan over 45 KB scripts.
35
+ */
36
+ const SETTLE_WINDOW_MS = 30_000
37
+ const SETTLE_FIRST_DELAY_MS = 300
38
+ const SETTLE_MAX_DELAY_MS = 5_000
39
+
40
+ /** The manager `cached` was read through; a different one reads as unknown. */
41
+ let cacheKey: unknown = null
42
+ let cached: number | null = null
43
+ /** The figure a transfer says is coming, and the moment the store stops
44
+ * discarding reads that disagree with it. */
45
+ let expected: number | null = null
46
+ let expectedUntil = 0
47
+ let settleDelay = SETTLE_FIRST_DELAY_MS
48
+ let settleTimer: ReturnType<typeof setTimeout> | undefined
49
+ /** Bumped to ask every mounted reader to fetch again. */
50
+ let version = 0
51
+
52
+ const readers = new Set<() => void>()
53
+ const notify = (): void => {
54
+ for (const onStoreChange of [...readers]) onStoreChange()
55
+ }
56
+ const subscribe = (onStoreChange: () => void): (() => void) => {
57
+ readers.add(onStoreChange)
58
+ return () => {
59
+ readers.delete(onStoreChange)
60
+ }
61
+ }
62
+
63
+ const bumpVersion = (): void => {
64
+ version++
65
+ notify()
66
+ }
67
+
68
+ const clearSettle = (): void => {
69
+ expected = null
70
+ expectedUntil = 0
71
+ settleDelay = SETTLE_FIRST_DELAY_MS
72
+ if (settleTimer !== undefined) {
73
+ clearTimeout(settleTimer)
74
+ settleTimer = undefined
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Publish the figure a just-completed transfer produces, before any read can
80
+ * confirm it. Callers own the arithmetic: they know what they moved.
81
+ *
82
+ * It publishes under whichever manager last read a balance, which is always
83
+ * the current one by the time a transfer can run — `canRun` requires a
84
+ * non-null balance, so a successful read has already happened.
85
+ */
86
+ export function expectVaultBalance(satoshis: number): void {
87
+ clearSettle()
88
+ cached = satoshis
89
+ expected = satoshis
90
+ expectedUntil = Date.now() + SETTLE_WINDOW_MS
91
+ notify()
92
+ }
93
+
94
+ /** Commit a successful read, unless it still disagrees with what a transfer
95
+ * said was coming and the budget for waiting it out is not yet spent. */
96
+ function commitRead(key: unknown, satoshis: number): void {
97
+ if (key !== cacheKey) clearSettle()
98
+ if (expected !== null && satoshis !== expected && Date.now() < expectedUntil) {
99
+ if (settleTimer === undefined) {
100
+ const delay = settleDelay
101
+ settleDelay = Math.min(settleDelay * 2, SETTLE_MAX_DELAY_MS)
102
+ settleTimer = setTimeout(() => {
103
+ settleTimer = undefined
104
+ bumpVersion()
105
+ }, delay)
106
+ }
107
+ return
108
+ }
109
+ clearSettle()
110
+ cacheKey = key
111
+ cached = satoshis
112
+ notify()
113
+ }
114
+
17
115
  export function useVaultBalance(): { balance: number | null; loading: boolean; refresh: () => void } {
18
116
  const { managers, adminOriginator, txStatusVersion } = useWallet()
19
117
  const { state: vaultState } = useVault()
118
+ const pm = managers?.permissionsManager
20
119
  // The zero-read window: both transfer paths note 'preparing' BEFORE their
21
120
  // createAction and stay busy until the broadcast settles (transfers.ts).
22
121
  const transferInFlight = vaultState.phase === 'preparing' || vaultState.phase === 'broadcasting'
23
- const [balance, setBalance] = useState<number | null>(null)
122
+ const balance = useSyncExternalStore(subscribe, () => (cacheKey === pm ? cached : null))
123
+ const refreshVersion = useSyncExternalStore(subscribe, () => version)
24
124
  const [loading, setLoading] = useState(false)
25
- const [refreshVersion, setRefreshVersion] = useState(0)
26
125
  // Read the latest figure without making balance changes trigger another read.
27
126
  const balanceRef = useRef<number | null>(null)
28
127
  balanceRef.current = balance
@@ -30,12 +129,11 @@ export function useVaultBalance(): { balance: number | null; loading: boolean; r
30
129
  const pendingRef = useRef<(() => Promise<void>) | null>(null)
31
130
 
32
131
  const refresh = useCallback(() => {
33
- setRefreshVersion(prev => prev + 1)
132
+ bumpVersion()
34
133
  }, [])
35
134
 
36
135
  useEffect(() => {
37
136
  let cancelled = false
38
- const pm = managers?.permissionsManager
39
137
  if (transferInFlight || !pm) {
40
138
  setLoading(false)
41
139
  return
@@ -45,7 +143,7 @@ export function useVaultBalance(): { balance: number | null; loading: boolean; r
45
143
  if (balanceRef.current === null) setLoading(true)
46
144
  try {
47
145
  const next = await getVaultBalance(pm as unknown as VaultWallet, adminOriginator)
48
- if (!cancelled) setBalance(next)
146
+ if (!cancelled) commitRead(pm, next)
49
147
  } catch {
50
148
  // Leave the last known balance in place on a transient failure.
51
149
  } finally {
@@ -75,7 +173,7 @@ export function useVaultBalance(): { balance: number | null; loading: boolean; r
75
173
  cancelled = true
76
174
  if (pendingRef.current === read) pendingRef.current = null
77
175
  }
78
- }, [managers?.permissionsManager, adminOriginator, txStatusVersion, transferInFlight, refreshVersion])
176
+ }, [pm, adminOriginator, txStatusVersion, transferInFlight, refreshVersion])
79
177
 
80
178
  return { balance, loading, refresh }
81
179
  }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Which vault outputs are committed to the current key set — the source of the
3
+ * vault screen's badges ("{{count}} deposits not yet open to {{nickname}}",
4
+ * "{{count}} deposits still open to a removed key") and of the Remove-key
5
+ * safety check (spec §3.4).
6
+ *
7
+ * Same invalidation contract as useVaultBalance: read on mount, on every
8
+ * txStatusVersion bump and on refresh(); frozen while a transfer is in flight
9
+ * (the spent outputs are gone and the re-vaulted remainder not yet visible, so
10
+ * a read in that window is wrong), with one read when the window closes.
11
+ *
12
+ * `null` means "nothing readable yet": before the first read lands, and
13
+ * whenever there is no built wallet. It is deliberately not an empty coverage
14
+ * record — a caller deciding whether a key removal would orphan an output
15
+ * must not mistake "could not look" for "looked and saw nothing".
16
+ */
17
+ import { useCallback, useEffect, useState } from 'react'
18
+ import { useWallet, useVault, getVaultKeyCoverage, type VaultKeyCoverage, type VaultWallet } from '@bsv/expo-wallet-toolbox'
19
+
20
+ export function useVaultCoverage(): { coverage: VaultKeyCoverage | null; refresh: () => void } {
21
+ const { managers, adminOriginator, txStatusVersion } = useWallet()
22
+ const { state: vaultState } = useVault()
23
+ const transferInFlight = vaultState.phase === 'preparing' || vaultState.phase === 'broadcasting'
24
+ const [coverage, setCoverage] = useState<VaultKeyCoverage | null>(null)
25
+ const [refreshVersion, setRefreshVersion] = useState(0)
26
+
27
+ const refresh = useCallback(() => {
28
+ setRefreshVersion(prev => prev + 1)
29
+ }, [])
30
+
31
+ useEffect(() => {
32
+ const pm = managers?.permissionsManager
33
+ if (!pm) {
34
+ setCoverage(null)
35
+ return
36
+ }
37
+ if (transferInFlight) return
38
+ let cancelled = false
39
+ getVaultKeyCoverage(pm as unknown as VaultWallet, adminOriginator)
40
+ .then(next => {
41
+ if (!cancelled) setCoverage(next)
42
+ })
43
+ .catch(() => {
44
+ // Leave the last known coverage in place on a transient failure.
45
+ })
46
+ return () => {
47
+ cancelled = true
48
+ }
49
+ }, [managers?.permissionsManager, adminOriginator, txStatusVersion, transferInFlight, refreshVersion])
50
+
51
+ return { coverage, refresh }
52
+ }
@@ -7,7 +7,8 @@ import {
7
7
  getRegisteredDbs,
8
8
  registerDb,
9
9
  selectLatestDb,
10
- parseTimestampFromFilename
10
+ parseTimestampFromFilename,
11
+ prepareSqliteImageForDeserialize
11
12
  } from '@bsv/expo-wallet-toolbox'
12
13
  import { showAlert } from './components/ui/AlertCard'
13
14
  import { showToast } from './components/ui/Toast'
@@ -138,8 +139,11 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
138
139
  let sourceDb: SQLite.SQLiteDatabase | undefined
139
140
  let destDb: SQLite.SQLiteDatabase | undefined
140
141
  try {
141
- // Deserialize the imported bytes into an in-memory database
142
- sourceDb = await SQLite.deserializeDatabaseAsync(bytes)
142
+ // Deserialize the imported bytes into an in-memory database. Exports of
143
+ // the WAL-mode wallet DB carry a WAL header, which the in-memory VFS
144
+ // cannot open (SQLITE_CANTOPEN), so the header is rewritten to
145
+ // rollback-journal mode first.
146
+ sourceDb = await SQLite.deserializeDatabaseAsync(prepareSqliteImageForDeserialize(bytes))
143
147
 
144
148
  // Open (or create) a file-backed database with the target filename.
145
149
  // This places the file in the default expo-sqlite database directory.
package/ui/index.ts CHANGED
@@ -78,6 +78,7 @@ export {
78
78
  useRecipientInput,
79
79
  type RecipientTarget,
80
80
  type RecipientInlineError,
81
+ type PeerPayRequest,
81
82
  type UseRecipientInputOptions
82
83
  } from './components/pay/useRecipientInput'
83
84
 
@@ -108,20 +109,22 @@ export {
108
109
  type RecoveredSecret
109
110
  } from './backupShares'
110
111
 
111
- // Vault UI (components/vault) + vault screens (Task 23 — extracted from
112
- // app/vault.tsx, app/vault-recover.tsx, app/vault-transfer.tsx). Also home
113
- // to VaultCeremonySheet, mounted at the app-shell level (app/_layout.tsx)
114
- // alongside PermissionSheet/ToastHost above.
112
+ // Vault UI (components/vault) + vault screens (app/vault.tsx,
113
+ // app/vault-transfer.tsx). Also home to VaultCeremonySheet, mounted at the
114
+ // app-shell level (app/_layout.tsx) alongside PermissionSheet/ToastHost above.
115
+ // The 1-of-N YubiKey vault has no phrase path: PassphraseField,
116
+ // PhraseBackupSheet and VaultRecoverScreen are gone (spec §3.5).
115
117
  export { EnrollWizard } from './components/vault/EnrollWizard'
116
- export { PassphraseField, type PassphraseFieldProps } from './components/vault/PassphraseField'
117
- export { PhraseBackupSheet } from './components/vault/PhraseBackupSheet'
118
+ export { KeyChooser, vaultKeyLabel } from './components/vault/KeyChooser'
119
+ export { vaultErrorCopy, RETRYABLE_VAULT_ERRORS, type VaultErrorParams } from './components/vault/vaultErrorCopy'
118
120
  export { BackupReminderSheet } from './components/wallet/BackupReminderSheet'
119
121
  export { BiometricAdvisoryModal } from './components/wallet/BiometricAdvisoryModal'
120
122
  export { ImportFromBackupPrompt } from './components/wallet/ImportFromBackupPrompt'
121
123
  export { VaultCeremonySheet } from './components/vault/VaultCeremonySheet'
122
124
  export { useVaultBalance } from './hooks/useVaultBalance'
125
+ export { useVaultCoverage } from './hooks/useVaultCoverage'
126
+ export { useExportWalletData } from './hooks/useExportWalletData'
123
127
  export { VaultScreen } from './screens/VaultScreen'
124
- export { VaultRecoverScreen } from './screens/VaultRecoverScreen'
125
128
  export { VaultTransferScreen } from './screens/VaultTransferScreen'
126
129
 
127
130
  // Connections, pair, trust, and logs screens (Task 24 — extracted from
@@ -136,3 +139,43 @@ export { TrustScreen } from './screens/TrustScreen'
136
139
  export { LogsScreen } from './screens/LogsScreen'
137
140
  export { default as validateTrust } from './validateTrust'
138
141
  export { default as isImageUrl } from './isImageUrl'
142
+
143
+ // ── Stablecoins ──────────────────────────────────────────────────────
144
+ //
145
+ // Every token surface in this package, and the one hook they all read from.
146
+ // `useMandala()` resolves the runtime from `useWallet().mandala`; a host that
147
+ // builds its own runtime (or a test) can wrap in `MandalaProvider` instead.
148
+ // Nothing here imports `@bsv/mandala`: the runtime is the only door.
149
+ export {
150
+ MandalaProvider,
151
+ useMandala,
152
+ useMandalaRuntime,
153
+ useTokenActivity,
154
+ tokenActivityByTxid,
155
+ type MandalaState,
156
+ type MandalaActivityState
157
+ } from './hooks/useMandala'
158
+ export {
159
+ formatTokenAmount,
160
+ formatTokenAmountWithUnit,
161
+ parseTokenAmount,
162
+ tokenAmountInputText,
163
+ tokenAmountMask,
164
+ tokenAmountParts
165
+ } from './tokenFormat'
166
+ export { tokenStatusKey, tokenStatusTone, tokenStatusDetailKey, type TokenStatusTone } from './tokenStatus'
167
+ export { SEEN_ASSETS_KEY, SEEN_EVICTIONS_KEY, markSeen, readSeen, useSeenSet, type SeenSet } from './tokenSeen'
168
+ export { default as AssetAmount, type AssetAmountProps } from './components/wallet/AssetAmount'
169
+ export { announceEviction, evictionsFrom, type EvictionNotice } from './components/wallet/tokenEviction'
170
+ export { default as AssetPicker, type AssetPickerProps } from './components/pay/AssetPicker'
171
+ export { default as AdmissionNotice, type AdmissionNoticeProps } from './components/pay/AdmissionNotice'
172
+ export {
173
+ tokenSendCopy,
174
+ tokenRefusalCopy,
175
+ tokenThrowCopy,
176
+ tokenUnavailableCopy,
177
+ type TokenSendCopy,
178
+ type TokenSendContext
179
+ } from './components/pay/tokenSendCopy'
180
+ export type { HandleReceiveProps } from './components/pay/HandleReceive'
181
+ export type { AmountInputAsset } from './components/wallet/AmountInput'
@@ -2,7 +2,6 @@ import React, { useEffect, 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'
5
- import type { WalletProtocol } from '@bsv/sdk'
6
5
  import * as SecureStore from 'expo-secure-store'
7
6
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
8
7
  import { useTranslation } from 'react-i18next'
@@ -19,11 +18,19 @@ import {
19
18
  guardVaultAccess,
20
19
  capWalletArgs,
21
20
  ADMIN_ORIGINATOR,
21
+ parseExternalOrigin,
22
22
  connectionStore,
23
23
  type Connection,
24
24
  useWalletConnection,
25
25
  lastSeqKey
26
26
  } from '@bsv/expo-wallet-toolbox'
27
+ import {
28
+ buildRelayWebSocketUrl,
29
+ validateMobileIdentityKey,
30
+ validateRelayUrl,
31
+ validateStoredConnectionFields,
32
+ validateStoredConnectionSequence
33
+ } from '../../core/services/walletConnectionValidation'
27
34
 
28
35
  /**
29
36
  * expo-clipboard ships an untransformed ESM build (its Clipboard.js imports
@@ -113,14 +120,10 @@ function parsePairingUri(raw: string): ParseResult {
113
120
  return { params: null, error: 'This QR code has expired — ask the desktop to generate a new one' }
114
121
  }
115
122
 
116
- let originUrl: URL
117
123
  try {
118
- originUrl = new URL(origin)
119
- } catch {
120
- return { params: null, error: 'Origin URL is not valid' }
121
- }
122
- if (originUrl.protocol !== 'http:' && originUrl.protocol !== 'https:') {
123
- return { params: null, error: 'Origin must use http:// or https://' }
124
+ parseExternalOrigin(origin)
125
+ } catch (e) {
126
+ return { params: null, error: e instanceof Error ? e.message : 'Origin URL is not valid' }
124
127
  }
125
128
 
126
129
  if (!/^0[23][0-9a-fA-F]{64}$/.test(backendIdentityKey)) {
@@ -143,12 +146,8 @@ function parsePairingUri(raw: string): ParseResult {
143
146
  }
144
147
  }
145
148
 
146
- function domainFromOrigin(origin: string): string {
147
- try {
148
- return new URL(origin).hostname
149
- } catch {
150
- return origin
151
- }
149
+ function displayDomain(origin: string): string {
150
+ try { return parseExternalOrigin(origin).originator } catch { return 'Invalid origin' }
152
151
  }
153
152
 
154
153
  export const ConnectionsScreen = observer(function ConnectionsScreen() {
@@ -188,10 +187,13 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
188
187
  showToast(`${t('wallet_not_ready')}: ${t('please_log_in_first')}`, { type: 'error' })
189
188
  return
190
189
  }
191
- const originator = domainFromOrigin(result.params.origin)
192
- const wallet = new WalletClient(capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)), originator)
193
190
  try {
194
- await connect(result.params, wallet)
191
+ const external = parseExternalOrigin(result.params.origin)
192
+ const wallet = new WalletClient(
193
+ capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)),
194
+ external.originator
195
+ )
196
+ await connect({ ...result.params, origin: external.origin }, wallet)
195
197
  } catch (err) {
196
198
  showToast(`${t('connection_failed')}: ${err instanceof Error ? err.message : t('unknown_error')}`, { type: 'error' })
197
199
  }
@@ -202,14 +204,24 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
202
204
 
203
205
  if (!managers.permissionsManager) return
204
206
  try {
205
- const protocolID = JSON.parse(conn.protocolID) as WalletProtocol
206
- const wallet = new WalletClient(capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)), domainFromOrigin(conn.origin))
207
- const ws = new WebSocket(`${conn.relay}/ws?topic=${conn.sessionId}&role=mobile`)
207
+ const validated = validateStoredConnectionFields(conn)
208
+ const relay = validateRelayUrl(conn.relay)
209
+ const storedSeq = await SecureStore.getItemAsync(lastSeqKey(validated.topic))
210
+ const initialSeq = validateStoredConnectionSequence(storedSeq)
211
+ const wallet = new WalletClient(
212
+ capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)),
213
+ validated.external.originator
214
+ )
215
+ const identityResult = await wallet.getPublicKey({ identityKey: true })
216
+ const currentMobileIdentityKey = validateMobileIdentityKey(identityResult.publicKey)
217
+ if (currentMobileIdentityKey !== validated.mobileIdentityKey) {
218
+ throw new Error('Stored connection belongs to a different wallet identity')
219
+ }
220
+ const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.topic))
208
221
 
209
222
  ws.onopen = async () => {
210
223
  try {
211
- const storedSeq = await SecureStore.getItemAsync(lastSeqKey(conn.sessionId))
212
- const seq = storedSeq ? Number(storedSeq) + 1 : 1
224
+ const seq = initialSeq + 1
213
225
  const payload = JSON.stringify({
214
226
  id: crypto.randomUUID(),
215
227
  seq,
@@ -218,14 +230,14 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
218
230
  })
219
231
  const plaintext = Array.from(new TextEncoder().encode(payload))
220
232
  const { ciphertext } = await wallet.encrypt({
221
- protocolID,
222
- keyID: conn.sessionId,
223
- counterparty: conn.backendIdentityKey,
233
+ protocolID: validated.protocolID,
234
+ keyID: validated.topic,
235
+ counterparty: validated.backendIdentityKey,
224
236
  plaintext
225
237
  })
226
238
  ws.send(
227
239
  JSON.stringify({
228
- topic: conn.sessionId,
240
+ topic: validated.topic,
229
241
  ciphertext: Buffer.from(ciphertext).toString('base64url')
230
242
  })
231
243
  )
@@ -241,8 +253,13 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
241
253
 
242
254
  async function handleReconnect(conn: Connection) {
243
255
  if (!managers.permissionsManager) return
244
- const wallet = new WalletClient(capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)), domainFromOrigin(conn.origin))
245
256
  try {
257
+ const external = parseExternalOrigin(conn.origin)
258
+ const wallet = new WalletClient(
259
+ capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)),
260
+ external.originator
261
+ )
262
+ conn = { ...conn, origin: external.origin }
246
263
  await reconnect(conn, wallet)
247
264
  } catch (err) {
248
265
  showToast(`${t('reconnect_failed')}: ${err instanceof Error ? err.message : t('unknown_error')}`, { type: 'error' })
@@ -279,7 +296,7 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
279
296
  {active.map((item, idx) => (
280
297
  <ListRow
281
298
  key={item.sessionId}
282
- label={domainFromOrigin(item.origin)}
299
+ label={displayDomain(item.origin)}
283
300
  value={new Date(item.connectedAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}
284
301
  icon="wifi-outline"
285
302
  iconColor={colors.success}
@@ -303,7 +320,7 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
303
320
  {inactive.map((item, idx) => (
304
321
  <ListRow
305
322
  key={item.sessionId}
306
- label={domainFromOrigin(item.origin)}
323
+ label={displayDomain(item.origin)}
307
324
  icon="wifi-outline"
308
325
  iconColor={colors.textTertiary}
309
326
  showChevron={false}
@@ -17,7 +17,8 @@ import {
17
17
  useWalletConnection,
18
18
  guardVaultAccess,
19
19
  capWalletArgs,
20
- ADMIN_ORIGINATOR
20
+ ADMIN_ORIGINATOR,
21
+ parseExternalOrigin
21
22
  } from '@bsv/expo-wallet-toolbox'
22
23
 
23
24
  /**
@@ -38,10 +39,6 @@ function loadExpoRouter(): ExpoRouterModule {
38
39
  return expoRouterMod
39
40
  }
40
41
 
41
- function domainFromOrigin(origin: string): string {
42
- try { return new URL(origin).hostname } catch { return origin }
43
- }
44
-
45
42
  export function PairScreen() {
46
43
  const { colors } = useTheme()
47
44
  const { managers } = useWallet()
@@ -107,18 +104,21 @@ export function PairScreen() {
107
104
  setPreConnectError('Wallet not ready — please log in first')
108
105
  return
109
106
  }
110
- const originator = domainFromOrigin(params.origin)
111
- // Guarded exactly like every sibling call site (connections.tsx): this is
112
- // an external surface (the desktop/browser pairing peer dispatches
113
- // BRC-100 methods by name), so it must never receive the unguarded
114
- // manager — see guard.ts for what that would otherwise expose.
115
- const wallet = new WalletClient(capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)), originator)
116
107
  try {
108
+ const external = parseExternalOrigin(params.origin)
109
+ // Guarded exactly like every sibling call site (connections.tsx): this is
110
+ // an external surface (the desktop/browser pairing peer dispatches
111
+ // BRC-100 methods by name), so it must never receive the unguarded
112
+ // manager — see guard.ts for what that would otherwise expose.
113
+ const wallet = new WalletClient(
114
+ capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)),
115
+ external.originator
116
+ )
117
117
  await connect({
118
118
  topic: params.topic,
119
119
  backendIdentityKey: params.backendIdentityKey,
120
120
  protocolID: params.protocolID,
121
- origin: params.origin,
121
+ origin: external.origin,
122
122
  expiry: params.expiry,
123
123
  sig: params.sig,
124
124
  }, wallet)