@bsv/expo-wallet-toolbox 0.22.0 → 0.24.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 (137) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +10 -9
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  16. package/core/bridge/bindings.ts +459 -0
  17. package/core/bridge/conformance.ts +222 -0
  18. package/core/bridge/consent.ts +494 -0
  19. package/core/bridge/consentSheetSource.ts +98 -0
  20. package/core/bridge/dispatcher.ts +621 -0
  21. package/core/bridge/inbox.ts +569 -0
  22. package/core/bridge/index.ts +48 -0
  23. package/core/bridge/loopback/cors.ts +57 -0
  24. package/core/bridge/loopback/endpoints.ts +11 -0
  25. package/core/bridge/loopback/hostCheck.ts +25 -0
  26. package/core/bridge/loopback/index.ts +7 -0
  27. package/core/bridge/loopback/launchProof.ts +166 -0
  28. package/core/bridge/loopback/router.ts +770 -0
  29. package/core/bridge/loopback/routerTypes.ts +115 -0
  30. package/core/bridge/loopback/status.ts +52 -0
  31. package/core/bridge/memoryInboxStore.ts +231 -0
  32. package/core/bridge/permissionPolicy.ts +247 -0
  33. package/core/bridge/policy.ts +72 -0
  34. package/core/bridge/protocol/base64url.ts +64 -0
  35. package/core/bridge/protocol/connectionError.ts +79 -0
  36. package/core/bridge/protocol/constants.ts +21 -0
  37. package/core/bridge/protocol/continuity.ts +21 -0
  38. package/core/bridge/protocol/descriptor.ts +395 -0
  39. package/core/bridge/protocol/envelopes.ts +188 -0
  40. package/core/bridge/protocol/errorCodec.ts +164 -0
  41. package/core/bridge/protocol/json.ts +237 -0
  42. package/core/bridge/protocol/limits.ts +43 -0
  43. package/core/bridge/protocol/methods.ts +55 -0
  44. package/core/bridge/protocol/origin.ts +130 -0
  45. package/core/bridge/runtime.ts +642 -0
  46. package/core/bridge/runtimeFlags.ts +34 -0
  47. package/core/bridge/testing/conformanceCases.ts +149 -0
  48. package/core/bridge/testing/pageClient.ts +44 -0
  49. package/core/bridge/unverifiedManager.ts +97 -0
  50. package/core/bridge/unverifiedOriginator.ts +79 -0
  51. package/core/config.tsx +1 -16
  52. package/core/constants.ts +7 -11
  53. package/core/context/WalletConnectionContext.tsx +92 -49
  54. package/core/context/WalletContext.tsx +288 -165
  55. package/core/context/sessionTeardown.ts +46 -0
  56. package/core/context/usePairingAttempt.ts +31 -0
  57. package/core/e2e/broadcaster.ts +25 -0
  58. package/core/e2e/consentFixture.ts +46 -0
  59. package/core/e2e/mode.ts +42 -0
  60. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  61. package/core/headers/headerConsensus.ts +230 -0
  62. package/core/headers/headerStore.ts +344 -122
  63. package/core/headers/prewarm.ts +4 -7
  64. package/core/headers/syncHeaders.ts +82 -12
  65. package/core/hooks/usePermissionQueue.ts +89 -34
  66. package/core/i18n/translations.tsx +958 -24
  67. package/core/identity/handleRegistry/client.ts +4 -2
  68. package/core/identity/handleRegistry/resolver.ts +7 -11
  69. package/core/index.ts +17 -0
  70. package/core/localpay/pending.ts +39 -4
  71. package/core/network/boundedFetch.ts +101 -0
  72. package/core/networks.ts +11 -13
  73. package/core/pay/rails/address.ts +5 -4
  74. package/core/pay/rails/handle.ts +3 -1
  75. package/core/pay/rails/sweep.ts +791 -0
  76. package/core/peerpay/brc29.ts +4 -0
  77. package/core/peerpay/handleResendRequests.ts +15 -2
  78. package/core/peerpay/outbox.ts +115 -2
  79. package/core/profiles/assertProfileEmpty.ts +2 -2
  80. package/core/profiles/profileStore.ts +3 -2
  81. package/core/services/arcadeBroadcastProvider.ts +260 -114
  82. package/core/services/autoApprovePolicy.ts +7 -1
  83. package/core/services/capWalletArgs.ts +2 -1
  84. package/core/services/permissionPrompts.ts +132 -0
  85. package/core/services/secrets/kek.ts +5 -0
  86. package/core/services/secrets/migration.ts +27 -2
  87. package/core/services/secrets/policy.ts +6 -0
  88. package/core/services/signingPermissionPolicy.ts +230 -2
  89. package/core/services/vault/VaultKeyService.ts +5 -2
  90. package/core/services/vault/ceremony.ts +2 -2
  91. package/core/services/vault/ceremonyHost.ts +1 -1
  92. package/core/services/vault/guard.ts +20 -0
  93. package/core/services/vault/outputAuthority.ts +76 -0
  94. package/core/services/vault/transfers.ts +52 -28
  95. package/core/services/vault/vaultStore.ts +60 -14
  96. package/core/services/walletArgLimits.ts +17 -2
  97. package/core/services/walletConnectionValidation.ts +13 -1
  98. package/core/services/walletServiceConfig.ts +8 -7
  99. package/core/storage/encryptedDbImage.ts +325 -0
  100. package/core/stores/ConnectionStore.ts +17 -0
  101. package/core/toolboxConfig.ts +78 -2
  102. package/expo-module.config.json +5 -0
  103. package/ios/BoundedBody.swift +15 -0
  104. package/ios/BsvBoundedFetch.podspec +17 -0
  105. package/ios/BsvBoundedFetchModule.swift +121 -0
  106. package/package.json +12 -8
  107. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  108. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  109. package/ui/components/pay/AddressReceive.tsx +6 -2
  110. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  111. package/ui/components/pay/PayCellRow.tsx +3 -1
  112. package/ui/components/pay/PayForm.tsx +12 -2
  113. package/ui/components/pay/RecipientField.tsx +1 -0
  114. package/ui/components/pay/RequestHub.tsx +1 -0
  115. package/ui/components/pay/UniversalSend.tsx +110 -42
  116. package/ui/components/ui/ListRow.tsx +10 -2
  117. package/ui/components/ui/PermissionSheet.tsx +534 -158
  118. package/ui/components/ui/Sheet.tsx +59 -7
  119. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  120. package/ui/components/vault/KeyChooser.tsx +1 -1
  121. package/ui/components/wallet/AmountInput.tsx +4 -1
  122. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  123. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  124. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  125. package/ui/components/wallet/ProfileButton.tsx +1 -0
  126. package/ui/exportDatabases.ts +94 -5
  127. package/ui/hooks/useExportWalletData.ts +37 -24
  128. package/ui/importDatabases.ts +154 -34
  129. package/ui/index.ts +4 -0
  130. package/ui/screens/ConnectionsScreen.tsx +12 -3
  131. package/ui/screens/PairScreen.tsx +10 -3
  132. package/ui/screens/PayScreen.tsx +1 -0
  133. package/ui/screens/TrustScreen.tsx +6 -3
  134. package/ui/screens/VaultScreen.tsx +13 -3
  135. package/ui/screens/VaultTransferScreen.tsx +6 -3
  136. package/ui/screens/WalletConfigScreen.tsx +30 -3
  137. package/ui/screens/WalletHomeScreen.tsx +7 -1
@@ -2,6 +2,7 @@ import { Platform } from 'react-native'
2
2
  import * as SQLite from 'expo-sqlite'
3
3
  import {
4
4
  type StorageExpoSQLite,
5
+ type DbExportWallet,
5
6
  i18n,
6
7
  parseDbFilename,
7
8
  getRegisteredDbs,
@@ -11,10 +12,14 @@ import {
11
12
  prepareSqliteImageForDeserialize,
12
13
  PENDING_KEY,
13
14
  PENDING_SUMMARY_KEY,
14
- createTables
15
+ createTables,
16
+ decryptDbImage,
17
+ EncryptedDbError,
18
+ ENCRYPTED_DB_EXTENSION
15
19
  } from '@bsv/expo-wallet-toolbox'
16
20
  import { showAlert } from './components/ui/AlertCard'
17
21
  import { showToast } from './components/ui/Toast'
22
+ import { OUTBOX_KEY, quarantineImportedOutbox } from '../core/peerpay/outbox'
18
23
 
19
24
  /**
20
25
  * expo-file-system and expo-document-picker both ship untransformed ESM/raw-TS
@@ -64,6 +69,38 @@ const MAX_FUTURE_SKEW_SECONDS = 300
64
69
  */
65
70
  const MAX_IMPORT_BYTES = 256 * 1024 * 1024 // 256 MiB
66
71
 
72
+ /**
73
+ * An encrypted backup never passes through JS memory whole — it is decrypted
74
+ * a chunk at a time to a temp file that SQLite opens directly — so its
75
+ * ceiling is about disk, not RAM: the cache holds the picked copy plus the
76
+ * decrypted one while the import runs.
77
+ */
78
+ const MAX_ENCRYPTED_IMPORT_BYTES = 2 * 1024 * 1024 * 1024 // 2 GiB
79
+
80
+ export interface ImportWalletDatabaseOptions {
81
+ /** Required to import an encrypted (`.db.enc`) backup: the wallet that exported it. */
82
+ wallet?: DbExportWallet
83
+ /** The admin originator, so the key unwrap never raises a permission prompt. */
84
+ originator?: string
85
+ /** Fraction (0..1) of the decryption done, for a progress indicator. */
86
+ onProgress?: (fraction: number) => void
87
+ }
88
+
89
+ /** A `file://` URI as the plain filesystem path SQLite wants. */
90
+ function nativePath(uri: string): string {
91
+ return decodeURI(uri.replace(/^file:\/\//, ''))
92
+ }
93
+
94
+ /** Best-effort removal of an encrypted import's picked copy and decrypted temp directory. */
95
+ function cleanupImportFiles(picked: { delete(): void }, tempDir: { exists: boolean; delete(): void }): void {
96
+ try {
97
+ picked.delete()
98
+ } catch {}
99
+ try {
100
+ if (tempDir.exists) tempDir.delete()
101
+ } catch {}
102
+ }
103
+
67
104
  async function rejectAsUntrusted(): Promise<ImportResult> {
68
105
  await showAlert({
69
106
  title: i18n.t('import_untrusted_file'),
@@ -223,14 +260,21 @@ async function isSchemaTrusted(sourceDb: SQLite.SQLiteDatabase): Promise<boolean
223
260
  try {
224
261
  refDb = await SQLite.openDatabaseAsync(':memory:')
225
262
  await createTables(refDb)
226
- const allowedRows = (await refDb.getAllAsync(
227
- `SELECT type, name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'`
228
- )) as Array<{ type: string; name: string; sql: string | null }>
263
+ const allowedRows = (await refDb.getAllAsync(`SELECT type, name, sql FROM sqlite_master`)) as Array<{
264
+ type: string
265
+ name: string
266
+ sql: string | null
267
+ }>
229
268
  const allowed = new Map(allowedRows.map(r => [r.name, { type: r.type, sql: r.sql }]))
230
269
 
231
- const objects = (await sourceDb.getAllAsync(
232
- `SELECT type, name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'`
233
- )) as Array<{ type: string; name: string; sql: string | null }>
270
+ // Inspect every object. LIKE's '_' wildcard also hides legal attacker
271
+ // names such as sqliteXbackdoor; genuine internal objects must match the
272
+ // canonical reference rather than being exempted by a name prefix.
273
+ const objects = (await sourceDb.getAllAsync(`SELECT type, name, sql FROM sqlite_master`)) as Array<{
274
+ type: string
275
+ name: string
276
+ sql: string | null
277
+ }>
234
278
  for (const obj of objects) {
235
279
  if (obj.type === 'trigger' || obj.type === 'view') return false
236
280
  if (obj.sql && /^\s*create\s+virtual\s+table/i.test(obj.sql)) return false
@@ -271,18 +315,27 @@ function buildUniqueTargetFilename(keySuffix: string, chain: string, baseTs: num
271
315
  }
272
316
 
273
317
  /**
274
- * Let the user pick a wallet `.db` backup file and import it alongside any
275
- * existing databases. The wallet context will use whichever database has the
276
- * highest timestamp in its filename.
318
+ * Let the user pick a wallet backup file — a plain `.db` or an encrypted
319
+ * `.db.enc` — and import it alongside any existing databases. The wallet
320
+ * context will use whichever database has the highest timestamp in its
321
+ * filename.
277
322
  *
278
323
  * Platform handling:
279
- * - Cross-platform: reads the picked file as bytes, deserializes into an
324
+ * - Plain `.db`: reads the picked file as bytes, deserializes into an
280
325
  * in-memory SQLite DB, opens a new file-backed DB with the target name,
281
326
  * then uses backupDatabaseAsync to copy the data across. This avoids
282
327
  * filesystem permission issues on Android.
328
+ * - Encrypted `.db.enc`: streams the picked file through native AES into a
329
+ * temp `.db` in the cache (one chunk in memory at a time), opens that
330
+ * file directly, and runs the same checks and backupDatabaseAsync copy.
331
+ * A file another wallet exported, or a damaged one, fails to decrypt and
332
+ * is refused as untrusted.
283
333
  */
284
- export async function importWalletDatabase(storage: StorageExpoSQLite | null): Promise<ImportResult> {
285
- const { File } = loadExpoFileSystem()
334
+ export async function importWalletDatabase(
335
+ storage: StorageExpoSQLite | null,
336
+ opts: ImportWalletDatabaseOptions = {}
337
+ ): Promise<ImportResult> {
338
+ const { File, Directory, Paths, FileMode } = loadExpoFileSystem()
286
339
  const DocumentPicker = loadDocumentPicker()
287
340
 
288
341
  // ── 1. Pick file ──────────────────────────────────────────────────────────
@@ -297,18 +350,20 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
297
350
 
298
351
  const asset = result.assets[0]
299
352
  const pickedName = asset.name
353
+ const encrypted = pickedName.endsWith(ENCRYPTED_DB_EXTENSION)
354
+ const maxBytes = encrypted ? MAX_ENCRYPTED_IMPORT_BYTES : MAX_IMPORT_BYTES
300
355
 
301
356
  // ── 1.5 Enforce a size ceiling ───────────────────────────────────────────
302
357
  // Picker metadata is untrusted, but it is still the cheapest possible
303
358
  // rejection — refuse before ever constructing a File or reading a byte
304
359
  // (XR-087). A missing size is treated the same as an oversized one: fail
305
360
  // closed rather than assume a small file.
306
- if (asset.size == null || asset.size > MAX_IMPORT_BYTES) {
361
+ if (asset.size == null || asset.size > maxBytes) {
307
362
  return rejectAsOversized(asset.uri)
308
363
  }
309
364
 
310
365
  // ── 2. Validate filename ──────────────────────────────────────────────────
311
- const parsed = parseDbFilename(pickedName)
366
+ const parsed = parseDbFilename(encrypted ? pickedName.slice(0, -'.enc'.length) : pickedName)
312
367
  if (!parsed) {
313
368
  await showAlert({
314
369
  title: i18n.t('import_invalid_file'),
@@ -365,22 +420,72 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
365
420
  }
366
421
  }
367
422
 
368
- // ── 4. Read bytes from picked file ────────────────────────────────────────
423
+ // ── 4. Get the source image into SQLite ──────────────────────────────────
424
+ // Plain: the picked bytes, deserialized in memory. Encrypted: decrypted to
425
+ // a temp file first, then opened from disk.
369
426
  const pickedFile = new File(asset.uri)
370
- let bytes: Uint8Array
371
- try {
372
- bytes = await pickedFile.bytes()
373
- } catch (e: any) {
374
- console.error('[importDatabases] Failed to read picked file:', e.message)
375
- showToast(e.message, { type: 'error' })
376
- return { imported: false }
377
- }
427
+ let openSource: () => Promise<SQLite.SQLiteDatabase>
428
+ let cleanup = () => {}
429
+ if (encrypted) {
430
+ const tempDir = new Directory(Paths.cache, 'bsv-wallet-import')
431
+ cleanup = () => cleanupImportFiles(pickedFile, tempDir)
432
+ if (!opts.wallet) {
433
+ return rejectAsUntrusted()
434
+ }
435
+ // The file system's byte count, not the picker's claim (XR-087).
436
+ if (pickedFile.size > MAX_ENCRYPTED_IMPORT_BYTES) {
437
+ return rejectAsOversized(asset.uri)
438
+ }
439
+ try {
440
+ if (tempDir.exists) tempDir.delete()
441
+ tempDir.create({ intermediates: true })
442
+ const plainFile = new File(tempDir, 'import.db')
443
+ plainFile.create()
444
+ const reader = pickedFile.open(FileMode.ReadOnly)
445
+ const writer = plainFile.open(FileMode.WriteOnly)
446
+ try {
447
+ await decryptDbImage(
448
+ opts.wallet,
449
+ { size: reader.size ?? pickedFile.size, read: n => reader.readBytes(n) },
450
+ { write: b => writer.writeBytes(b) },
451
+ { originator: opts.originator, onProgress: opts.onProgress }
452
+ )
453
+ } finally {
454
+ reader.close()
455
+ writer.close()
456
+ }
457
+ } catch (e: any) {
458
+ cleanup()
459
+ if (e instanceof EncryptedDbError && e.code !== 'no-native-crypto') {
460
+ console.warn('[importDatabases] Encrypted backup refused:', e.code, e.message)
461
+ return rejectAsUntrusted()
462
+ }
463
+ console.error('[importDatabases] Failed to decrypt picked file:', e.message)
464
+ showToast(e.message, { type: 'error' })
465
+ return { imported: false }
466
+ }
467
+ openSource = () => SQLite.openDatabaseAsync('import.db', undefined, nativePath(tempDir.uri))
468
+ } else {
469
+ let bytes: Uint8Array
470
+ try {
471
+ bytes = await pickedFile.bytes()
472
+ } catch (e: any) {
473
+ console.error('[importDatabases] Failed to read picked file:', e.message)
474
+ showToast(e.message, { type: 'error' })
475
+ return { imported: false }
476
+ }
378
477
 
379
- // Picker-reported `asset.size` is untrusted metadata — re-check the actual
380
- // byte count before it ever reaches WAL normalization/deserialization,
381
- // which can allocate a second full-size copy on top of this one (XR-087).
382
- if (bytes.length > MAX_IMPORT_BYTES) {
383
- return rejectAsOversized(asset.uri)
478
+ // Picker-reported `asset.size` is untrusted metadata — re-check the actual
479
+ // byte count before it ever reaches WAL normalization/deserialization,
480
+ // which can allocate a second full-size copy on top of this one (XR-087).
481
+ if (bytes.length > MAX_IMPORT_BYTES) {
482
+ return rejectAsOversized(asset.uri)
483
+ }
484
+
485
+ // Exports of the WAL-mode wallet DB carry a WAL header, which the
486
+ // in-memory VFS cannot open (SQLITE_CANTOPEN), so the header is
487
+ // rewritten to rollback-journal mode first.
488
+ openSource = () => SQLite.deserializeDatabaseAsync(prepareSqliteImageForDeserialize(bytes))
384
489
  }
385
490
 
386
491
  // ── 5. Place the database via deserialize → backup ────────────────────────
@@ -389,11 +494,7 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
389
494
  let untrusted = false
390
495
  let targetFilename = ''
391
496
  try {
392
- // Deserialize the imported bytes into an in-memory database. Exports of
393
- // the WAL-mode wallet DB carry a WAL header, which the in-memory VFS
394
- // cannot open (SQLITE_CANTOPEN), so the header is rewritten to
395
- // rollback-journal mode first.
396
- sourceDb = await SQLite.deserializeDatabaseAsync(prepareSqliteImageForDeserialize(bytes))
497
+ sourceDb = await openSource()
397
498
 
398
499
  // Authenticate the image against the currently unlocked wallet BEFORE any
399
500
  // of it is written to disk under an authoritative name: exactly one
@@ -464,6 +565,23 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
464
565
  // never delete or otherwise mutate the row, since it may already have
465
566
  // been broadcast (XR-085).
466
567
  await destDb.runAsync(`UPDATE offline_actions SET status = 'import_hold' WHERE status IN ('queued', 'posting')`)
568
+
569
+ // Preserve signed PeerPay history, but never restore old outgoing
570
+ // authority (including a snapshot taken before cancellation).
571
+ const importedDb = destDb
572
+ await quarantineImportedOutbox({
573
+ getKeyValue: async key => {
574
+ const row = await importedDb.getFirstAsync<{ value: string }>(
575
+ 'SELECT value FROM key_value_store WHERE key = ?',
576
+ [key]
577
+ )
578
+ return row?.value
579
+ },
580
+ setKeyValue: async (key, value) => {
581
+ if (key !== OUTBOX_KEY) throw new Error('Unexpected import quarantine key')
582
+ await importedDb.runAsync('UPDATE key_value_store SET value = ? WHERE key = ?', [value, key])
583
+ }
584
+ })
467
585
  }
468
586
  } catch (e: any) {
469
587
  console.error('[importDatabases] Failed to place database:', e.message)
@@ -476,6 +594,8 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
476
594
  try {
477
595
  await destDb?.closeAsync()
478
596
  } catch {}
597
+ // Neither the picked copy nor the decrypted plaintext outlives the import.
598
+ cleanup()
479
599
  }
480
600
 
481
601
  if (untrusted) {
package/ui/index.ts CHANGED
@@ -219,3 +219,7 @@ export { AVATAR_ICON_GROUPS, type AvatarIconOption, type AvatarIconGroup } from
219
219
 
220
220
  export { default as IconPickerSheet } from './components/wallet/IconPickerSheet'
221
221
  export { default as EditPictureSheet, type EditPictureOption } from './components/wallet/EditPictureSheet'
222
+
223
+ // Android bridge sheet: relays the first React root's contexts to the sheet's second root.
224
+ export { ContextRelayPublisher, ContextRelaySubscriber, resetContextRelay } from './bridgeSheet/ContextRelay'
225
+ export { RELAYED_CONTEXTS } from './bridgeSheet/relayedContexts'
@@ -2,7 +2,6 @@ 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'
5
- import * as SecureStore from 'expo-secure-store'
6
5
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
7
6
  import { useTranslation } from 'react-i18next'
8
7
  import { GroupedSection } from '../components/ui/GroupedList'
@@ -28,6 +27,7 @@ import {
28
27
  import { validateStoredConnectionAuthorityTag } from '../../core/services/walletConnectionValidation'
29
28
  import { computeConnectionAuthorityTag, verifyConnectionAuthorityTag } from '../../core/services/connectionAuthority'
30
29
  import { revokeConnection } from '../../core/services/revokeConnection'
30
+ import { usePairingAttempt } from '../../core/context/usePairingAttempt'
31
31
 
32
32
  /**
33
33
  * expo-clipboard ships an untransformed ESM build (its Clipboard.js imports
@@ -156,6 +156,7 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
156
156
  const { t } = useTranslation()
157
157
  const { managers } = useWallet()
158
158
  const { connect, reconnect, disconnect, sessionMeta } = useWalletConnection()
159
+ const pairingAttempt = usePairingAttempt()
159
160
  const insets = useSafeAreaInsets()
160
161
  const [scanning, setScanning] = useState(false)
161
162
  const { router } = loadExpoRouter()
@@ -180,6 +181,7 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
180
181
  showToast(`${t('wallet_not_ready')}: ${t('please_log_in_first')}`, { type: 'error' })
181
182
  return
182
183
  }
184
+ const isCurrent = pairingAttempt.begin(result.params.topic)
183
185
  try {
184
186
  const external = parseExternalOrigin(result.params.origin)
185
187
  const wallet = new WalletClient(
@@ -200,13 +202,16 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
200
202
  protocolID: result.params.protocolID,
201
203
  backendIdentityKey: result.params.backendIdentityKey
202
204
  })
205
+ if (!isCurrent()) return
203
206
  connectionStore.stageAuthorityTag(result.params.topic, tag)
204
207
  } catch (err) {
208
+ if (!isCurrent()) return
205
209
  console.warn('[connections] failed to compute connection authority tag', err)
206
210
  connectionStore.discardStagedAuthorityTag(result.params.topic)
207
211
  }
208
212
  await connect({ ...result.params, origin: external.origin }, wallet)
209
213
  } catch (err) {
214
+ if (!isCurrent()) return
210
215
  showToast(`${t('connection_failed')}: ${err instanceof Error ? err.message : t('unknown_error')}`, {
211
216
  type: 'error'
212
217
  })
@@ -230,6 +235,7 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
230
235
 
231
236
  async function handleReconnect(conn: Connection) {
232
237
  if (!managers.permissionsManager) return
238
+ const isCurrent = pairingAttempt.begin(conn.sessionId)
233
239
  let external: ReturnType<typeof parseExternalOrigin>
234
240
  try {
235
241
  external = parseExternalOrigin(conn.origin)
@@ -268,6 +274,7 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
268
274
  },
269
275
  storedTag
270
276
  )
277
+ if (!isCurrent()) return
271
278
  if (!authentic) {
272
279
  showToast(t('reconnect_needs_reapproval'), { type: 'error' })
273
280
  return
@@ -284,7 +291,7 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
284
291
  { text: t('cancel'), key: 'cancel', style: 'cancel' }
285
292
  ]
286
293
  })
287
- if (choice !== 'reconnect') return
294
+ if (choice !== 'reconnect' || !isCurrent()) return
288
295
  try {
289
296
  const wallet = new WalletClient(
290
297
  capWalletArgs(guardVaultAccess(managers.permissionsManager as any, ADMIN_ORIGINATOR)),
@@ -293,6 +300,7 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
293
300
  conn = { ...conn, origin: external.origin }
294
301
  await reconnect(conn, wallet)
295
302
  } catch (err) {
303
+ if (!isCurrent()) return
296
304
  showToast(`${t('reconnect_failed')}: ${err instanceof Error ? err.message : t('unknown_error')}`, {
297
305
  type: 'error'
298
306
  })
@@ -367,7 +375,6 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
367
375
  </TouchableOpacity>
368
376
  <TouchableOpacity
369
377
  onPress={() => {
370
- void SecureStore.deleteItemAsync(lastSeqKey(item.sessionId))
371
378
  connectionStore.remove(item.sessionId)
372
379
  }}
373
380
  style={[styles.trailingAction, { marginLeft: spacing.md }]}
@@ -396,7 +403,9 @@ export const ConnectionsScreen = observer(function ConnectionsScreen() {
396
403
  <TouchableOpacity
397
404
  style={[styles.pasteBtn, { borderColor: colors.separator }]}
398
405
  onPress={async () => {
406
+ const isCurrent = pairingAttempt.begin()
399
407
  const text = await loadExpoClipboard().getStringAsync()
408
+ if (!isCurrent()) return
400
409
  if (text) handleScan(text.trim())
401
410
  }}
402
411
  >
@@ -20,6 +20,7 @@ import {
20
20
  } from '@bsv/expo-wallet-toolbox'
21
21
  import { computeConnectionAuthorityTag } from '../../core/services/connectionAuthority'
22
22
  import { profileScopedKey } from '../../core/profiles/profileStore'
23
+ import { usePairingAttempt } from '../../core/context/usePairingAttempt'
23
24
 
24
25
  /**
25
26
  * expo-router is required lazily rather than imported at module scope: this
@@ -54,6 +55,7 @@ export function PairScreen() {
54
55
  }>()
55
56
 
56
57
  const { status, sessionMeta, errorMsg, connect, disconnect, startNavTimer, cancelNavTimer } = useWalletConnection()
58
+ const pairingAttempt = usePairingAttempt()
57
59
 
58
60
  // Pre-connection validation error (before connect() is called)
59
61
  const [preConnectError, setPreConnectError] = useState<string | null>(null)
@@ -130,6 +132,7 @@ export function PairScreen() {
130
132
  setPreConnectError('Wallet not ready — please log in first')
131
133
  return
132
134
  }
135
+ const isCurrent = pairingAttempt.begin(params.topic)
133
136
  try {
134
137
  const external = parseExternalOrigin(params.origin)
135
138
  // Guarded exactly like every sibling call site (connections.tsx): this is
@@ -160,8 +163,10 @@ export function PairScreen() {
160
163
  protocolID: params.protocolID,
161
164
  backendIdentityKey: params.backendIdentityKey
162
165
  })
166
+ if (!isCurrent()) return
163
167
  connectionStore.stageAuthorityTag(params.topic, tag)
164
168
  } catch (err) {
169
+ if (!isCurrent()) return
165
170
  console.warn('[PairScreen] failed to compute connection authority tag', err)
166
171
  connectionStore.discardStagedAuthorityTag(params.topic)
167
172
  }
@@ -177,11 +182,13 @@ export function PairScreen() {
177
182
  wallet
178
183
  )
179
184
  } catch (err) {
185
+ if (!isCurrent()) return
180
186
  setPreConnectError(err instanceof Error ? err.message : 'Connection failed')
181
187
  }
182
188
  }
183
189
 
184
190
  function handleReject() {
191
+ pairingAttempt.cancel()
185
192
  disconnect()
186
193
  router.back()
187
194
  }
@@ -242,7 +249,7 @@ export function PairScreen() {
242
249
  keeps the registrable-domain suffix visible even for a long
243
250
  attacker-chosen hostname designed to hide it behind a
244
251
  trustworthy-looking prefix. */}
245
- <Text style={styles.infoValue} numberOfLines={1} ellipsizeMode="middle">
252
+ <Text testID="pair-origin" style={styles.infoValue} numberOfLines={1} ellipsizeMode="middle">
246
253
  {canonicalOrigin ?? ''}
247
254
  </Text>
248
255
  </View>
@@ -266,10 +273,10 @@ export function PairScreen() {
266
273
  </View>
267
274
 
268
275
  <View style={styles.buttonRow}>
269
- <TouchableOpacity style={styles.rejectBtn} onPress={handleReject}>
276
+ <TouchableOpacity testID="pair-reject" style={styles.rejectBtn} onPress={handleReject}>
270
277
  <Text style={styles.rejectBtnText}>Reject</Text>
271
278
  </TouchableOpacity>
272
- <TouchableOpacity style={styles.approveBtn} onPress={() => void handleApprove()}>
279
+ <TouchableOpacity testID="pair-approve" style={styles.approveBtn} onPress={() => void handleApprove()}>
273
280
  <Text style={styles.approveBtnText}>Approve</Text>
274
281
  </TouchableOpacity>
275
282
  </View>
@@ -569,6 +569,7 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
569
569
  <PressableScale
570
570
  onPress={goBack}
571
571
  haptic="tap"
572
+ testID="pay-back"
572
573
  style={styles.headerBtn}
573
574
  accessibilityRole="button"
574
575
  accessibilityLabel={t('go_back')}
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next'
9
9
  import type { Certifier as WalletCertifier } from '@bsv/wallet-toolbox-mobile'
10
10
  import validateTrust from '../validateTrust'
11
11
  import { isPublicHttpsUrl } from '../../core/net/publicDestination'
12
+ import { createBoundedNativeFetch } from '../../core/network/boundedFetch'
12
13
  import { GroupedSection } from '../components/ui/GroupedList'
13
14
  import { showAlert } from '../components/ui/AlertCard'
14
15
  import { haptics, useTheme, spacing, radii, typography, useWallet } from '@bsv/expo-wallet-toolbox'
@@ -156,7 +157,7 @@ const fetchWithTimeout = async (url: string, ms: number) => {
156
157
  // a trust-provider manifest is fetched from by redirecting the entered
157
158
  // HTTPS origin somewhere else (XR-076 / SEC2-011) — a legitimate provider
158
159
  // has no reason to redirect its own manifest.json.
159
- res = await fetch(url, { signal: controller.signal, redirect: 'error' })
160
+ res = await createBoundedNativeFetch(MAX_TRUST_MANIFEST_BYTES)(url, { signal: controller.signal, redirect: 'error' })
160
161
  } finally {
161
162
  clearTimeout(id)
162
163
  }
@@ -198,12 +199,14 @@ const fetchWithTimeout = async (url: string, ms: number) => {
198
199
  const MAX_TRUST_MANIFEST_BYTES = 64 * 1024
199
200
 
200
201
  /**
201
- * Mirrors core/identity/handleRegistry/resolver.ts's readBoundedJson: a
202
+ * The native receiver enforces the actual byte ceiling before returning this
203
+ * Response, including on runtimes without WHATWG streams. This additional
204
+ * reader check bounds trusted injected transports in tests. A
202
205
  * declared Content-Length over the cap is refused before anything is read;
203
206
  * otherwise, when the runtime exposes the body as a stream, chunks are
204
207
  * counted as they arrive and the read is aborted the instant the running
205
208
  * total crosses the cap. `fallback` (the runtime's own `response.json`) is
206
- * used only when no stream is available to count from.
209
+ * used on native Response implementations after receive-time enforcement.
207
210
  */
208
211
  async function readBoundedManifestJson(res: Response, fallback: () => Promise<unknown>): Promise<unknown> {
209
212
  const declared = res.headers?.get?.('content-length')
@@ -749,11 +749,21 @@ export function VaultScreen() {
749
749
  const currentMeta = metaRef.current
750
750
  if (!currentMeta) throw new VaultError('not-enrolled', 'Vault is not set up')
751
751
  const scopeToken = vaultStore.captureScopeToken()
752
- await requireAuthenticatedMeta(pm as unknown as VaultWallet, adminOriginator, scopeToken, currentMeta)
752
+ const authenticatedMeta = await requireAuthenticatedMeta(
753
+ pm as unknown as VaultWallet,
754
+ adminOriginator,
755
+ scopeToken,
756
+ currentMeta
757
+ )
753
758
  const scope = vaultStore.getScope()
754
759
  if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
755
- await vaultStore.renameKey(renaming.serial, next, scopeToken, nextMeta =>
756
- computeVaultMetaAuthorityTag(pm as unknown as HmacCapableWallet, adminOriginator, nextMeta, scope)
760
+ await vaultStore.renameKey(
761
+ renaming.serial,
762
+ next,
763
+ scopeToken,
764
+ nextMeta =>
765
+ computeVaultMetaAuthorityTag(pm as unknown as HmacCapableWallet, adminOriginator, nextMeta, scope),
766
+ authenticatedMeta
757
767
  )
758
768
  await reload()
759
769
  } catch (e) {
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Direction comes from the `direction` search param ('deposit' | 'withdraw').
5
5
  *
6
- * Deposit needs no hardware: the wallet builds an R1C output committed to every
6
+ * Deposit proves a live enrolled key, then builds an R1C output committed to every
7
7
  * enrolled key and broadcasts it (depositToVault). The screen shows the floor
8
8
  * and the fee inline, confirms the FIRST deposit into an empty vault, and
9
9
  * refuses while encrypted private backup is unavailable. The salt is
@@ -219,7 +219,8 @@ export function VaultTransferScreen() {
219
219
  !(isDeposit && overLockLimit) &&
220
220
  !!pm &&
221
221
  balance !== null &&
222
- (isDeposit ? released : chosen !== undefined)
222
+ chosen !== undefined &&
223
+ (!isDeposit || released)
223
224
 
224
225
  /** `nickname · …tail4` for each referenced key; a key no longer in meta shows its pubkey tail. */
225
226
  const namesFor = useCallback(
@@ -312,6 +313,7 @@ export function VaultTransferScreen() {
312
313
  setError(null)
313
314
  try {
314
315
  if (isDeposit) {
316
+ if (!chosen) return
315
317
  // XR-003: checked before privateBackupEnabled and before the
316
318
  // first-deposit confirmation, for the same reason both of those run
317
319
  // early — the user must never be asked to approve a transfer that a
@@ -343,6 +345,7 @@ export function VaultTransferScreen() {
343
345
  }
344
346
  setBusy(true)
345
347
  await depositToVault(w, adminOriginator, sats, {
348
+ outputKeySerial: chosen.serial,
346
349
  isOnline: getOnline,
347
350
  backupEnabled: privateBackupEnabled
348
351
  })
@@ -526,7 +529,7 @@ export function VaultTransferScreen() {
526
529
  {isDeposit ? t('vault_deposit_sub') : t('vault_withdraw_sub')}
527
530
  </Text>
528
531
 
529
- {!isDeposit && keys.length > 0 && (
532
+ {keys.length > 0 && (
530
533
  <View style={styles.chooser}>
531
534
  <Text style={[styles.chooserLabel, { color: colors.textPrimary }]}>{t('vault_choose_key')}</Text>
532
535
  {/* Frozen while a ceremony runs: the highlighted key must stay the