@bsv/expo-wallet-toolbox 0.22.0 → 0.23.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 (64) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +9 -5
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/context/WalletConnectionContext.tsx +7 -1
  41. package/core/context/WalletContext.tsx +258 -133
  42. package/core/context/sessionTeardown.ts +46 -0
  43. package/core/hooks/usePermissionQueue.ts +89 -34
  44. package/core/i18n/translations.tsx +911 -12
  45. package/core/index.ts +15 -0
  46. package/core/services/autoApprovePolicy.ts +7 -1
  47. package/core/services/capWalletArgs.ts +2 -1
  48. package/core/services/permissionPrompts.ts +132 -0
  49. package/core/services/signingPermissionPolicy.ts +230 -2
  50. package/core/services/vault/guard.ts +10 -0
  51. package/core/services/walletArgLimits.ts +17 -2
  52. package/core/storage/encryptedDbImage.ts +325 -0
  53. package/core/toolboxConfig.ts +18 -1
  54. package/package.json +6 -6
  55. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  56. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  57. package/ui/components/ui/PermissionSheet.tsx +534 -158
  58. package/ui/components/ui/Sheet.tsx +59 -7
  59. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  60. package/ui/exportDatabases.ts +94 -5
  61. package/ui/hooks/useExportWalletData.ts +37 -24
  62. package/ui/importDatabases.ts +123 -28
  63. package/ui/index.ts +4 -0
  64. package/ui/screens/WalletConfigScreen.tsx +13 -1
@@ -1,10 +1,21 @@
1
1
  import React, { memo, useEffect, useRef } from 'react'
2
- import { Dimensions, Keyboard, Platform, Pressable, StyleSheet, Text, TouchableOpacity, View } from 'react-native'
2
+ import {
3
+ AppState,
4
+ Dimensions,
5
+ Keyboard,
6
+ Platform,
7
+ Pressable,
8
+ StyleSheet,
9
+ Text,
10
+ TouchableOpacity,
11
+ View
12
+ } from 'react-native'
3
13
  import Animated, { useSharedValue, useAnimatedStyle, withSpring, withTiming, runOnJS } from 'react-native-reanimated'
4
14
  import { Gesture, GestureDetector } from 'react-native-gesture-handler'
5
15
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
6
16
  import { useTheme, spacing, typography } from '@bsv/expo-wallet-toolbox'
7
17
  import ScreenGradient from './ScreenGradient'
18
+ import { onSheetResumed } from './sheetResumeSignal'
8
19
 
9
20
  /**
10
21
  * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
@@ -36,6 +47,12 @@ interface SheetProps {
36
47
  * focus a field inside the sheet — focusing before the sheet has finished
37
48
  * moving into place drops the first keystroke typed into it. */
38
49
  onOpenComplete?: () => void
50
+ /**
51
+ * Whether the user can dismiss the sheet by tapping the backdrop or swiping it down. Default true. When false both do
52
+ * nothing: a swipe springs back to the open position and `onClose` is not called (the Android bridge's overlay, where
53
+ * an outside tap must not answer a prompt).
54
+ */
55
+ dismissible?: boolean
39
56
  children?: React.ReactNode
40
57
  }
41
58
 
@@ -57,6 +74,7 @@ const Sheet: React.FC<SheetProps> = ({
57
74
  fullPage = false,
58
75
  fitContent = false,
59
76
  onOpenComplete,
77
+ dismissible = true,
60
78
  children
61
79
  }) => {
62
80
  const { colors } = useTheme()
@@ -74,6 +92,18 @@ const Sheet: React.FC<SheetProps> = ({
74
92
  // Track whether the sheet is visible for rendering children
75
93
  const [rendered, setRendered] = React.useState(false)
76
94
 
95
+ // Whether the sheet is still meant to be open. The open spring's completion reaches JS a frame or more later; by then
96
+ // a close may have started, and nudging the open position would cancel that close spring and strand the sheet.
97
+ const visibleRef = useRef(visible)
98
+ visibleRef.current = visible
99
+
100
+ // Nudges the open position by half a point and back, which makes a stale paint of the sheet repaint.
101
+ const reapplyOpen = React.useCallback(() => {
102
+ if (!visibleRef.current) return
103
+ translateY.value = 0.5
104
+ translateY.value = withTiming(0, { duration: 60 })
105
+ }, [translateY])
106
+
77
107
  // Open / close driven by `visible` prop. Only PLAY the enter animation on an
78
108
  // actual closed→open transition — not on every re-run of this effect. In
79
109
  // fitContent mode, sheetHeight tracks onLayout-measured content height, which
@@ -87,6 +117,7 @@ const Sheet: React.FC<SheetProps> = ({
87
117
  if (!wasVisibleRef.current) {
88
118
  translateY.value = sheetHeight
89
119
  translateY.value = withSpring(0, { mass: 1, stiffness: 280, damping: 32 }, finished => {
120
+ if (finished) runOnJS(reapplyOpen)()
90
121
  if (finished && onOpenComplete) runOnJS(onOpenComplete)()
91
122
  })
92
123
  }
@@ -98,6 +129,24 @@ const Sheet: React.FC<SheetProps> = ({
98
129
  wasVisibleRef.current = visible
99
130
  }, [visible, sheetHeight]) // eslint-disable-line react-hooks/exhaustive-deps
100
131
 
132
+ // A sheet opened while the activity is not resumed (the Android browser bridge raises the wallet for a request)
133
+ // can stay painted at its hidden offset although its shared value reads 0 (observed on Pixel_9, Android 16: the
134
+ // scrim shows, the sheet does not). Re-apply the open position when the app becomes active again.
135
+ useEffect(() => {
136
+ if (!visible) return
137
+ const sub = AppState.addEventListener('change', state => {
138
+ if (state !== 'active') return
139
+ reapplyOpen()
140
+ })
141
+ // The Android bridge's sheet Activity resumes without an `AppState` change the second root can see (the sheet
142
+ // mounts after `active`); it signals instead. The open spring above also re-applies once it settles on mount.
143
+ const unsignal = onSheetResumed(reapplyOpen)
144
+ return () => {
145
+ sub.remove()
146
+ unsignal()
147
+ }
148
+ }, [visible, reapplyOpen])
149
+
101
150
  // Lift the sheet above the software keyboard so bottom-anchored content
102
151
  // (PIN field, primary button) stays visible. Without this a number-pad — which
103
152
  // has no "done" key — hides the submit button, forcing a tap-outside that
@@ -125,13 +174,14 @@ const Sheet: React.FC<SheetProps> = ({
125
174
  }))
126
175
 
127
176
  const panGesture = Gesture.Pan()
177
+ .withTestId('sheet-pan')
128
178
  .activeOffsetY(10)
129
179
  .failOffsetX([-25, 25])
130
180
  .onUpdate(e => {
131
181
  translateY.value = Math.max(0, e.translationY)
132
182
  })
133
183
  .onEnd(e => {
134
- const shouldClose = e.translationY > sheetHeight / 3 || e.velocityY > 800
184
+ const shouldClose = dismissible && (e.translationY > sheetHeight / 3 || e.velocityY > 800)
135
185
  if (shouldClose) {
136
186
  translateY.value = withSpring(
137
187
  sheetHeight,
@@ -198,11 +248,13 @@ const Sheet: React.FC<SheetProps> = ({
198
248
  {isVisible && (
199
249
  <Pressable
200
250
  style={[styles.backdrop, { backgroundColor: colors.scrim }]}
201
- onPress={onClose}
202
- accessible={true}
203
- accessibilityRole="button"
204
- accessibilityLabel="Close"
205
- accessibilityHint="Dismisses this sheet"
251
+ onPress={dismissible ? onClose : undefined}
252
+ testID="sheet-backdrop"
253
+ accessible={dismissible}
254
+ importantForAccessibility={dismissible ? 'auto' : 'no-hide-descendants'}
255
+ accessibilityRole={dismissible ? 'button' : undefined}
256
+ accessibilityLabel={dismissible ? 'Close' : undefined}
257
+ accessibilityHint={dismissible ? 'Dismisses this sheet' : undefined}
206
258
  />
207
259
  )}
208
260
  <Animated.View
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A host-neutral nudge for `Sheet`. The Android browser bridge shows permission sheets on a second React root inside a
3
+ * translucent Activity; when that Activity resumes, `AppState` may already have gone `active` before the root's sheet
4
+ * mounted, so `Sheet`'s own `AppState` re-apply never fires and the scrim can show without the sheet (SPIKES Task 22).
5
+ * The bridge calls `signalSheetResumed()` when its sheet Activity resumes and every open `Sheet` re-applies its open
6
+ * position. The toolbox does not depend on the bridge: this is the whole seam.
7
+ */
8
+ const listeners = new Set<() => void>()
9
+
10
+ export function onSheetResumed(fn: () => void): () => void {
11
+ listeners.add(fn)
12
+ return () => {
13
+ listeners.delete(fn)
14
+ }
15
+ }
16
+
17
+ export function signalSheetResumed(): void {
18
+ for (const fn of [...listeners]) fn()
19
+ }
@@ -1,5 +1,13 @@
1
1
  import { Platform } from 'react-native'
2
- import { type StorageExpoSQLite, parseDbFilename } from '@bsv/expo-wallet-toolbox'
2
+ import {
3
+ type StorageExpoSQLite,
4
+ type DbExportWallet,
5
+ type ByteSink,
6
+ type ByteSource,
7
+ parseDbFilename,
8
+ encryptDbImage,
9
+ ENCRYPTED_DB_EXTENSION
10
+ } from '@bsv/expo-wallet-toolbox'
3
11
 
4
12
  /**
5
13
  * expo-file-system and expo-sharing both ship untransformed ESM/raw-TS
@@ -39,16 +47,40 @@ function exportFilename(dbName: string): string {
39
47
  return dbName.replace(/\.db$/, `-${ts}.db`)
40
48
  }
41
49
 
50
+ export interface ExportWalletDatabaseOptions {
51
+ /**
52
+ * Encrypt the file to this wallet (`wallet.encrypt`, counterparty `self`)
53
+ * so only the same wallet can import it again. Off by default: the plain
54
+ * `.db` is still useful for development (open it in any SQLite browser).
55
+ */
56
+ encrypt?: boolean
57
+ /** Required with `encrypt`: the wallet whose keys wrap the file key. */
58
+ wallet?: DbExportWallet
59
+ /** The admin originator, so the wrap never raises a permission prompt. */
60
+ originator?: string
61
+ /** Fraction (0..1) of the encryption done, for a progress indicator. */
62
+ onProgress?: (fraction: number) => void
63
+ }
64
+
42
65
  /**
43
66
  * Exports the currently active wallet database as a timestamped `.db` file
44
- * and presents the OS share dialogue so the user can save or send it.
67
+ * (or, with `encrypt: true`, a `.db.enc` file) and presents the OS share
68
+ * dialogue so the user can save or send it.
45
69
  *
46
- * On iOS the file is copied from disk; on Android `serializeAsync` is used
47
- * to avoid filesystem permission issues with the native database directory.
70
+ * Plain export: on iOS the file is copied from disk; on Android
71
+ * `serializeAsync` is used to avoid filesystem permission issues with the
72
+ * native database directory.
48
73
  *
49
74
  * Returns the number of database files exported (0 or 1).
50
75
  */
51
- export async function exportAllWalletDatabases(storage: StorageExpoSQLite | null): Promise<number> {
76
+ export async function exportAllWalletDatabases(
77
+ storage: StorageExpoSQLite | null,
78
+ opts: ExportWalletDatabaseOptions = {}
79
+ ): Promise<number> {
80
+ if (opts.encrypt) {
81
+ return exportEncrypted(storage, opts)
82
+ }
83
+
52
84
  if (Platform.OS === 'android') {
53
85
  return exportAndroid(storage)
54
86
  }
@@ -56,6 +88,63 @@ export async function exportAllWalletDatabases(storage: StorageExpoSQLite | null
56
88
  return exportIOS(storage)
57
89
  }
58
90
 
91
+ /** A `file://` URI as the plain filesystem path SQLite wants. */
92
+ function nativePath(uri: string): string {
93
+ return decodeURI(uri.replace(/^file:\/\//, ''))
94
+ }
95
+
96
+ /**
97
+ * Encrypted export, on both platforms. `VACUUM INTO` writes a consistent,
98
+ * compacted snapshot of the live database (WAL included, concurrent writers
99
+ * unaffected) to a temp file on the native side, which is then encrypted a
100
+ * chunk at a time in native AES — the database is never held whole in JS
101
+ * memory. The plaintext snapshot lives only in the app's own cache and is
102
+ * deleted with the temp directory whether or not the share succeeds.
103
+ */
104
+ async function exportEncrypted(storage: StorageExpoSQLite | null, opts: ExportWalletDatabaseOptions): Promise<number> {
105
+ if (!storage?.db) return 0
106
+ if (!opts.wallet) throw new Error('Encrypted export needs the wallet')
107
+
108
+ const { File, Directory, Paths, FileMode } = loadExpoFileSystem()
109
+ const { shareAsync } = loadExpoSharing()
110
+
111
+ const outName = exportFilename(storage.dbName).replace(/\.db$/, ENCRYPTED_DB_EXTENSION)
112
+ const tempDir = new Directory(Paths.cache, 'bsv-wallet-export')
113
+ if (tempDir.exists) tempDir.delete()
114
+ tempDir.create({ intermediates: true })
115
+
116
+ try {
117
+ const snapshot = new File(tempDir, 'snapshot.db')
118
+ const snapshotPath = nativePath(snapshot.uri).replace(/'/g, "''")
119
+ await storage.db.execAsync(`VACUUM INTO '${snapshotPath}'`)
120
+
121
+ const outFile = new File(tempDir, outName)
122
+ outFile.create()
123
+ const reader = snapshot.open(FileMode.ReadOnly)
124
+ const writer = outFile.open(FileMode.WriteOnly)
125
+ try {
126
+ const src: ByteSource = { size: reader.size ?? snapshot.size, read: n => reader.readBytes(n) }
127
+ const sink: ByteSink = { write: b => writer.writeBytes(b) }
128
+ await encryptDbImage(opts.wallet, src, sink, { originator: opts.originator, onProgress: opts.onProgress })
129
+ } finally {
130
+ reader.close()
131
+ writer.close()
132
+ }
133
+ snapshot.delete()
134
+
135
+ await shareAsync(outFile.uri, {
136
+ mimeType: 'application/octet-stream',
137
+ dialogTitle: outName
138
+ })
139
+ } finally {
140
+ try {
141
+ tempDir.delete()
142
+ } catch {}
143
+ }
144
+
145
+ return 1
146
+ }
147
+
59
148
  async function exportIOS(storage: StorageExpoSQLite | null): Promise<number> {
60
149
  if (!storage?.db?.databasePath) return 0
61
150
 
@@ -8,41 +8,54 @@
8
8
  *
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
- * logged rather than surfaced (a dismissed share sheet is not an error).
11
+ * shown as an error toast (a dismissed share sheet resolves, so is not one).
12
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. Encrypting it needs a product decision on how
17
- * the importing device gets the key back (importDatabases.ts has no decrypt
18
- * step either). The confirmation alert that used to precede the share sheet
19
- * was removed by product decision: the tap goes straight to the native save
20
- * prompt.
13
+ * XR-086: the export is encrypted by default — `wallet.encrypt` (counterparty
14
+ * `self`, through the permissions manager as the admin originator, so no
15
+ * prompt) wraps a per-file AES key, so only this wallet can import it again.
16
+ * `exportData({ encrypt: false })` still writes the raw SQLite image, for
17
+ * development builds that want to open it in a SQLite browser. The
18
+ * confirmation alert that used to precede the share sheet was removed by
19
+ * product decision: the tap goes straight to the native save prompt.
21
20
  */
22
21
  import { useCallback, useRef, useState } from 'react'
23
22
  import { useWallet } from '@bsv/expo-wallet-toolbox'
24
23
  import { exportAllWalletDatabases } from '../exportDatabases'
24
+ import { showToast } from '../components/ui/Toast'
25
25
 
26
- export function useExportWalletData(): { exportData: () => Promise<void>; exporting: boolean } {
27
- const { storage } = useWallet()
26
+ export function useExportWalletData(): {
27
+ exportData: (opts?: { encrypt?: boolean }) => Promise<void>
28
+ exporting: boolean
29
+ } {
30
+ const { storage, managers, adminOriginator } = useWallet()
28
31
  const [exporting, setExporting] = useState(false)
29
32
  // A ref, not the state: two taps in the same tick both see `exporting ===
30
33
  // false` in their closure, and the second must still be refused.
31
34
  const inFlightRef = useRef(false)
32
35
 
33
- const exportData = useCallback(async () => {
34
- if (inFlightRef.current) return
35
- inFlightRef.current = true
36
- setExporting(true)
37
- try {
38
- await exportAllWalletDatabases(storage)
39
- } catch (e) {
40
- console.warn('[exportWalletData] Export failed:', e)
41
- } finally {
42
- inFlightRef.current = false
43
- setExporting(false)
44
- }
45
- }, [storage])
36
+ const exportData = useCallback(
37
+ async ({ encrypt = true }: { encrypt?: boolean } = {}) => {
38
+ if (inFlightRef.current) return
39
+ inFlightRef.current = true
40
+ setExporting(true)
41
+ try {
42
+ await exportAllWalletDatabases(
43
+ storage,
44
+ encrypt ? { encrypt, wallet: managers.permissionsManager, originator: adminOriginator } : {}
45
+ )
46
+ } catch (e) {
47
+ // A dismissed share sheet resolves rather than throws, so anything
48
+ // landing here is a real failure (no crypto backend, no wallet yet,
49
+ // the snapshot refused) the user would otherwise never hear about.
50
+ console.warn('[exportWalletData] Export failed:', e)
51
+ showToast(e instanceof Error ? e.message : String(e), { type: 'error' })
52
+ } finally {
53
+ inFlightRef.current = false
54
+ setExporting(false)
55
+ }
56
+ },
57
+ [storage, managers.permissionsManager, adminOriginator]
58
+ )
46
59
 
47
60
  return { exportData, exporting }
48
61
  }
@@ -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,7 +12,10 @@ 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'
@@ -64,6 +68,38 @@ const MAX_FUTURE_SKEW_SECONDS = 300
64
68
  */
65
69
  const MAX_IMPORT_BYTES = 256 * 1024 * 1024 // 256 MiB
66
70
 
71
+ /**
72
+ * An encrypted backup never passes through JS memory whole — it is decrypted
73
+ * a chunk at a time to a temp file that SQLite opens directly — so its
74
+ * ceiling is about disk, not RAM: the cache holds the picked copy plus the
75
+ * decrypted one while the import runs.
76
+ */
77
+ const MAX_ENCRYPTED_IMPORT_BYTES = 2 * 1024 * 1024 * 1024 // 2 GiB
78
+
79
+ export interface ImportWalletDatabaseOptions {
80
+ /** Required to import an encrypted (`.db.enc`) backup: the wallet that exported it. */
81
+ wallet?: DbExportWallet
82
+ /** The admin originator, so the key unwrap never raises a permission prompt. */
83
+ originator?: string
84
+ /** Fraction (0..1) of the decryption done, for a progress indicator. */
85
+ onProgress?: (fraction: number) => void
86
+ }
87
+
88
+ /** A `file://` URI as the plain filesystem path SQLite wants. */
89
+ function nativePath(uri: string): string {
90
+ return decodeURI(uri.replace(/^file:\/\//, ''))
91
+ }
92
+
93
+ /** Best-effort removal of an encrypted import's picked copy and decrypted temp directory. */
94
+ function cleanupImportFiles(picked: { delete(): void }, tempDir: { exists: boolean; delete(): void }): void {
95
+ try {
96
+ picked.delete()
97
+ } catch {}
98
+ try {
99
+ if (tempDir.exists) tempDir.delete()
100
+ } catch {}
101
+ }
102
+
67
103
  async function rejectAsUntrusted(): Promise<ImportResult> {
68
104
  await showAlert({
69
105
  title: i18n.t('import_untrusted_file'),
@@ -271,18 +307,27 @@ function buildUniqueTargetFilename(keySuffix: string, chain: string, baseTs: num
271
307
  }
272
308
 
273
309
  /**
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.
310
+ * Let the user pick a wallet backup file — a plain `.db` or an encrypted
311
+ * `.db.enc` — and import it alongside any existing databases. The wallet
312
+ * context will use whichever database has the highest timestamp in its
313
+ * filename.
277
314
  *
278
315
  * Platform handling:
279
- * - Cross-platform: reads the picked file as bytes, deserializes into an
316
+ * - Plain `.db`: reads the picked file as bytes, deserializes into an
280
317
  * in-memory SQLite DB, opens a new file-backed DB with the target name,
281
318
  * then uses backupDatabaseAsync to copy the data across. This avoids
282
319
  * filesystem permission issues on Android.
320
+ * - Encrypted `.db.enc`: streams the picked file through native AES into a
321
+ * temp `.db` in the cache (one chunk in memory at a time), opens that
322
+ * file directly, and runs the same checks and backupDatabaseAsync copy.
323
+ * A file another wallet exported, or a damaged one, fails to decrypt and
324
+ * is refused as untrusted.
283
325
  */
284
- export async function importWalletDatabase(storage: StorageExpoSQLite | null): Promise<ImportResult> {
285
- const { File } = loadExpoFileSystem()
326
+ export async function importWalletDatabase(
327
+ storage: StorageExpoSQLite | null,
328
+ opts: ImportWalletDatabaseOptions = {}
329
+ ): Promise<ImportResult> {
330
+ const { File, Directory, Paths, FileMode } = loadExpoFileSystem()
286
331
  const DocumentPicker = loadDocumentPicker()
287
332
 
288
333
  // ── 1. Pick file ──────────────────────────────────────────────────────────
@@ -297,18 +342,20 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
297
342
 
298
343
  const asset = result.assets[0]
299
344
  const pickedName = asset.name
345
+ const encrypted = pickedName.endsWith(ENCRYPTED_DB_EXTENSION)
346
+ const maxBytes = encrypted ? MAX_ENCRYPTED_IMPORT_BYTES : MAX_IMPORT_BYTES
300
347
 
301
348
  // ── 1.5 Enforce a size ceiling ───────────────────────────────────────────
302
349
  // Picker metadata is untrusted, but it is still the cheapest possible
303
350
  // rejection — refuse before ever constructing a File or reading a byte
304
351
  // (XR-087). A missing size is treated the same as an oversized one: fail
305
352
  // closed rather than assume a small file.
306
- if (asset.size == null || asset.size > MAX_IMPORT_BYTES) {
353
+ if (asset.size == null || asset.size > maxBytes) {
307
354
  return rejectAsOversized(asset.uri)
308
355
  }
309
356
 
310
357
  // ── 2. Validate filename ──────────────────────────────────────────────────
311
- const parsed = parseDbFilename(pickedName)
358
+ const parsed = parseDbFilename(encrypted ? pickedName.slice(0, -'.enc'.length) : pickedName)
312
359
  if (!parsed) {
313
360
  await showAlert({
314
361
  title: i18n.t('import_invalid_file'),
@@ -365,22 +412,72 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
365
412
  }
366
413
  }
367
414
 
368
- // ── 4. Read bytes from picked file ────────────────────────────────────────
415
+ // ── 4. Get the source image into SQLite ──────────────────────────────────
416
+ // Plain: the picked bytes, deserialized in memory. Encrypted: decrypted to
417
+ // a temp file first, then opened from disk.
369
418
  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
- }
419
+ let openSource: () => Promise<SQLite.SQLiteDatabase>
420
+ let cleanup = () => {}
421
+ if (encrypted) {
422
+ const tempDir = new Directory(Paths.cache, 'bsv-wallet-import')
423
+ cleanup = () => cleanupImportFiles(pickedFile, tempDir)
424
+ if (!opts.wallet) {
425
+ return rejectAsUntrusted()
426
+ }
427
+ // The file system's byte count, not the picker's claim (XR-087).
428
+ if (pickedFile.size > MAX_ENCRYPTED_IMPORT_BYTES) {
429
+ return rejectAsOversized(asset.uri)
430
+ }
431
+ try {
432
+ if (tempDir.exists) tempDir.delete()
433
+ tempDir.create({ intermediates: true })
434
+ const plainFile = new File(tempDir, 'import.db')
435
+ plainFile.create()
436
+ const reader = pickedFile.open(FileMode.ReadOnly)
437
+ const writer = plainFile.open(FileMode.WriteOnly)
438
+ try {
439
+ await decryptDbImage(
440
+ opts.wallet,
441
+ { size: reader.size ?? pickedFile.size, read: n => reader.readBytes(n) },
442
+ { write: b => writer.writeBytes(b) },
443
+ { originator: opts.originator, onProgress: opts.onProgress }
444
+ )
445
+ } finally {
446
+ reader.close()
447
+ writer.close()
448
+ }
449
+ } catch (e: any) {
450
+ cleanup()
451
+ if (e instanceof EncryptedDbError && e.code !== 'no-native-crypto') {
452
+ console.warn('[importDatabases] Encrypted backup refused:', e.code, e.message)
453
+ return rejectAsUntrusted()
454
+ }
455
+ console.error('[importDatabases] Failed to decrypt picked file:', e.message)
456
+ showToast(e.message, { type: 'error' })
457
+ return { imported: false }
458
+ }
459
+ openSource = () => SQLite.openDatabaseAsync('import.db', undefined, nativePath(tempDir.uri))
460
+ } else {
461
+ let bytes: Uint8Array
462
+ try {
463
+ bytes = await pickedFile.bytes()
464
+ } catch (e: any) {
465
+ console.error('[importDatabases] Failed to read picked file:', e.message)
466
+ showToast(e.message, { type: 'error' })
467
+ return { imported: false }
468
+ }
378
469
 
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)
470
+ // Picker-reported `asset.size` is untrusted metadata — re-check the actual
471
+ // byte count before it ever reaches WAL normalization/deserialization,
472
+ // which can allocate a second full-size copy on top of this one (XR-087).
473
+ if (bytes.length > MAX_IMPORT_BYTES) {
474
+ return rejectAsOversized(asset.uri)
475
+ }
476
+
477
+ // Exports of the WAL-mode wallet DB carry a WAL header, which the
478
+ // in-memory VFS cannot open (SQLITE_CANTOPEN), so the header is
479
+ // rewritten to rollback-journal mode first.
480
+ openSource = () => SQLite.deserializeDatabaseAsync(prepareSqliteImageForDeserialize(bytes))
384
481
  }
385
482
 
386
483
  // ── 5. Place the database via deserialize → backup ────────────────────────
@@ -389,11 +486,7 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
389
486
  let untrusted = false
390
487
  let targetFilename = ''
391
488
  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))
489
+ sourceDb = await openSource()
397
490
 
398
491
  // Authenticate the image against the currently unlocked wallet BEFORE any
399
492
  // of it is written to disk under an authoritative name: exactly one
@@ -476,6 +569,8 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
476
569
  try {
477
570
  await destDb?.closeAsync()
478
571
  } catch {}
572
+ // Neither the picked copy nor the decrypted plaintext outlives the import.
573
+ cleanup()
479
574
  }
480
575
 
481
576
  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'
@@ -436,7 +436,10 @@ export function WalletConfigScreen({ hideLogout = false }: { hideLogout?: boolea
436
436
  if (isImporting) return
437
437
  setIsImporting(true)
438
438
  try {
439
- const result = await importWalletDatabase(storage)
439
+ const result = await importWalletDatabase(storage, {
440
+ wallet: managers.permissionsManager,
441
+ originator: adminOriginator
442
+ })
440
443
  if (result.imported) {
441
444
  showToast(t('import_success'), { type: 'success' })
442
445
  // Not restoreFromBackup: a raw db import already carries a complete
@@ -995,6 +998,15 @@ export function WalletConfigScreen({ hideLogout = false }: { hideLogout?: boolea
995
998
  showChevron={false}
996
999
  trailing={exporting ? <ActivityIndicator size="small" /> : undefined}
997
1000
  />
1001
+ {__DEV__ && (
1002
+ <ListRow
1003
+ label="Export Wallet Data (unencrypted)"
1004
+ icon="share-outline"
1005
+ iconColor="#8E8E93"
1006
+ onPress={() => void exportData({ encrypt: false })}
1007
+ showChevron={false}
1008
+ />
1009
+ )}
998
1010
  <ListRow
999
1011
  label={t('import_wallet_data')}
1000
1012
  icon="download-outline"