@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
@@ -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,6 +1,6 @@
1
1
  /**
2
2
  * "Which key will you tap?" — a radio list of the vault's enrolled keys, used
3
- * before a withdrawal (spec §4.2 step 1) and before a re-lock (§4.3). Keys are
3
+ * before a deposit, a withdrawal (spec §4.2 step 1), or a re-lock (§4.3). Keys are
4
4
  * shown everywhere as `nickname · …serialTail4` (§3.3), which is what
5
5
  * `vaultKeyLabel` produces; the wizard, the vault screen and the transfer
6
6
  * screen all import it from here so the format is written once.
@@ -75,6 +75,7 @@ interface AmountInputProps {
75
75
  * fee comes out of BSV.
76
76
  */
77
77
  maxValue?: string
78
+ testID?: string
78
79
  }
79
80
 
80
81
  /**
@@ -93,7 +94,8 @@ export const AmountInput: React.FC<AmountInputProps> = ({
93
94
  showMax = true,
94
95
  maxLabelKey = 'entire_wallet_balance',
95
96
  asset,
96
- maxValue
97
+ maxValue,
98
+ testID
97
99
  }) => {
98
100
  const { t } = useTranslation()
99
101
  const { colors } = useTheme()
@@ -245,6 +247,7 @@ export const AmountInput: React.FC<AmountInputProps> = ({
245
247
  placeholderTextColor={colors.textTertiary}
246
248
  keyboardType={keyboardType}
247
249
  returnKeyType="done"
250
+ testID={testID}
248
251
  style={[styles.input, { color: colors.textPrimary }]}
249
252
  />
250
253
  <View style={styles.unitLabelPressable}>
@@ -83,7 +83,14 @@ export const BackupReminderSheet: React.FC<{
83
83
  <Animated.View
84
84
  style={[styles.card, { backgroundColor: colors.sheetBackground, borderColor: colors.warning }, cardStyle]}
85
85
  >
86
- <PressableScale haptic="tap" onPress={onClose} style={styles.closeButton}>
86
+ <PressableScale
87
+ haptic="tap"
88
+ onPress={onClose}
89
+ testID="backup-reminder-close"
90
+ accessibilityRole="button"
91
+ accessibilityLabel="Close"
92
+ style={styles.closeButton}
93
+ >
87
94
  <Ionicons name="close" size={20} color={colors.textSecondary} />
88
95
  </PressableScale>
89
96
 
@@ -88,6 +88,7 @@ export const BiometricAdvisoryModal: React.FC<{
88
88
  haptic="confirm"
89
89
  onPress={loading ? undefined : onContinue}
90
90
  disabled={loading}
91
+ testID="biometric-continue"
91
92
  style={[styles.primary, { backgroundColor: colors.accent, opacity: loading ? 0.7 : 1 }]}
92
93
  >
93
94
  {loading ? (
@@ -101,6 +102,7 @@ export const BiometricAdvisoryModal: React.FC<{
101
102
  haptic="tap"
102
103
  onPress={loading ? undefined : onCancel}
103
104
  disabled={loading}
105
+ testID="biometric-cancel"
104
106
  style={styles.secondary}
105
107
  >
106
108
  <Text style={[styles.secondaryLabel, { color: loading ? colors.textTertiary : colors.textSecondary }]}>
@@ -46,7 +46,12 @@ export const ImportFromBackupPrompt: React.FC<{
46
46
  <Text style={[styles.title, { color: colors.textPrimary }]}>{t('import_prompt_title')}</Text>
47
47
  <Text style={[styles.body, { color: colors.textSecondary }]}>{t('import_prompt_body')}</Text>
48
48
  </View>
49
- <PressableScale haptic="tap" onPress={onImport} style={[styles.button, { borderColor: colors.accent }]}>
49
+ <PressableScale
50
+ haptic="tap"
51
+ onPress={onImport}
52
+ testID="import-from-backup"
53
+ style={[styles.button, { borderColor: colors.accent }]}
54
+ >
50
55
  <Text style={[styles.buttonLabel, { color: colors.accent }]}>{t('import_prompt_action')}</Text>
51
56
  </PressableScale>
52
57
  </View>
@@ -86,6 +86,7 @@ export default function ProfileButton() {
86
86
  onPress={onPress}
87
87
  haptic="tap"
88
88
  hitSlop={5}
89
+ testID="profile-button"
89
90
  style={[styles.disc, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
90
91
  accessibilityRole="button"
91
92
  accessibilityLabel={profilesSupported ? t('profile_switcher_a11y') : t('profile')}
@@ -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
  }