@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -8,7 +8,10 @@ import {
8
8
  registerDb,
9
9
  selectLatestDb,
10
10
  parseTimestampFromFilename,
11
- prepareSqliteImageForDeserialize
11
+ prepareSqliteImageForDeserialize,
12
+ PENDING_KEY,
13
+ PENDING_SUMMARY_KEY,
14
+ createTables
12
15
  } from '@bsv/expo-wallet-toolbox'
13
16
  import { showAlert } from './components/ui/AlertCard'
14
17
  import { showToast } from './components/ui/Toast'
@@ -39,6 +42,234 @@ export interface ImportResult {
39
42
  chain?: string
40
43
  }
41
44
 
45
+ /**
46
+ * How far a filename's embedded timestamp may sit in the future before the
47
+ * import is refused outright. Without this, a forged timestamp is a way to
48
+ * make an attacker-authored database permanently win `selectLatestDb` on
49
+ * every later build (XR-079).
50
+ */
51
+ const MAX_FUTURE_SKEW_SECONDS = 300
52
+
53
+ /**
54
+ * A conservative ceiling on how large a picked wallet backup may be. Without
55
+ * one, `DocumentPicker` accepts any file type at all and the import path
56
+ * unconditionally materializes the whole thing into a JS byte array
57
+ * (`pickedFile.bytes()`) before any format check, and `prepareSqliteImageForDeserialize`
58
+ * can then allocate a second full-size copy on top of that for any
59
+ * WAL-header-shaped input — so an oversized file (deliberately crafted or
60
+ * merely a bad pick) can exhaust device memory/storage and freeze or kill the
61
+ * app during an explicit, user-initiated import (XR-087). Comfortably above
62
+ * any real wallet database this app would ever produce, while still bounding
63
+ * the worst case.
64
+ */
65
+ const MAX_IMPORT_BYTES = 256 * 1024 * 1024 // 256 MiB
66
+
67
+ async function rejectAsUntrusted(): Promise<ImportResult> {
68
+ await showAlert({
69
+ title: i18n.t('import_untrusted_file'),
70
+ message: i18n.t('import_untrusted_file_detail'),
71
+ buttons: [{ text: i18n.t('done'), key: 'ok' }]
72
+ })
73
+ return { imported: false }
74
+ }
75
+
76
+ /**
77
+ * Reject a picked file that is too large (or whose size the picker did not
78
+ * report at all — untrusted metadata that fails closed) to safely read into
79
+ * memory, and best-effort delete whatever `copyToCacheDirectory: true`
80
+ * already placed in the cache for it (XR-087).
81
+ */
82
+ async function rejectAsOversized(cacheUri: string | undefined): Promise<ImportResult> {
83
+ if (cacheUri) {
84
+ try {
85
+ const { File } = loadExpoFileSystem()
86
+ new File(cacheUri).delete()
87
+ } catch {}
88
+ }
89
+ await showAlert({
90
+ title: i18n.t('import_oversized_file'),
91
+ message: i18n.t('import_oversized_file_detail'),
92
+ buttons: [{ text: i18n.t('done'), key: 'ok' }]
93
+ })
94
+ return { imported: false }
95
+ }
96
+
97
+ /**
98
+ * Read the (sole) settings row directly out of the deserialized source
99
+ * image, before any of its bytes are written to disk under an authoritative
100
+ * name. Returns `null` if the row is missing, duplicated, or unreadable —
101
+ * any of which means the image cannot be trusted to belong to this wallet
102
+ * (XR-079/XR-080).
103
+ */
104
+ async function readSourceIdentity(
105
+ sourceDb: SQLite.SQLiteDatabase
106
+ ): Promise<{ storageIdentityKey: string; chain: string } | null> {
107
+ try {
108
+ const rows = (await sourceDb.getAllAsync('SELECT storageIdentityKey, chain FROM settings')) as Array<{
109
+ storageIdentityKey: string
110
+ chain: string
111
+ }>
112
+ if (rows.length !== 1) return null
113
+ const { storageIdentityKey, chain } = rows[0]
114
+ if (!storageIdentityKey || !chain) return null
115
+ return { storageIdentityKey, chain }
116
+ } catch {
117
+ return null
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Collapse insignificant whitespace so two `sqlite_master.sql` texts that
123
+ * differ only in formatting still compare equal. SQLite already strips a
124
+ * leading `IF NOT EXISTS` from the stored text on its own, so this is the
125
+ * only normalization needed before an exact structural comparison.
126
+ */
127
+ function normalizeSql(sql: string | null): string {
128
+ if (!sql) return ''
129
+ return sql.replace(/\s+/g, ' ').trim()
130
+ }
131
+
132
+ /**
133
+ * Split a `CREATE TABLE`'s parenthesized body into its top-level
134
+ * column/constraint definitions, respecting nested parens (a `CHECK (x IN
135
+ * (...))`'s internal commas, a table-level `FOREIGN KEY (...) REFERENCES
136
+ * t(...)`'s, etc. must never cause a false split).
137
+ */
138
+ function splitTopLevel(inner: string): string[] {
139
+ const parts: string[] = []
140
+ let depth = 0
141
+ let current = ''
142
+ for (const ch of inner) {
143
+ if (ch === '(') depth++
144
+ else if (ch === ')') depth--
145
+ if (ch === ',' && depth === 0) {
146
+ parts.push(current)
147
+ current = ''
148
+ } else {
149
+ current += ch
150
+ }
151
+ }
152
+ parts.push(current)
153
+ return parts
154
+ }
155
+
156
+ /**
157
+ * Extract a `CREATE TABLE ... (...)` statement's column/constraint
158
+ * definitions as an order-independent, whitespace-normalized multiset (a
159
+ * sorted array). Returns `null` if `sql` does not look like a single
160
+ * parenthesized table body (e.g. no `(` at all), in which case callers must
161
+ * fail closed rather than treat two un-parseable strings as equivalent.
162
+ *
163
+ * Column ORDER is deliberately not part of the comparison: SQLite's `ALTER
164
+ * TABLE ADD COLUMN` rewrites a table's stored `sqlite_master.sql` by
165
+ * inserting the new column just before any trailing table-level constraint
166
+ * clause, or — when the table has none — appending it at the very end of the
167
+ * column list. `createTables()`'s own inline definitions place some
168
+ * migrated-in columns earlier for readability, so a genuine device that ran
169
+ * the real, shipped additive migration (e.g. `ensureTokenSettlementColumns`)
170
+ * ends up with the exact same set of column/constraint definitions as a
171
+ * fresh `createTables()` run, just in a different order — not tampering, and
172
+ * not something `isSchemaTrusted` should reject. Every individual
173
+ * column/constraint's own text (type, NOT NULL, UNIQUE, CHECK, default,
174
+ * FOREIGN KEY, ...) is still compared exactly, so a weakened or removed
175
+ * constraint, a retyped or dropped column, or an added one is still caught.
176
+ */
177
+ function extractTableDefParts(sql: string | null): string[] | null {
178
+ if (!sql) return null
179
+ const start = sql.indexOf('(')
180
+ const end = sql.lastIndexOf(')')
181
+ if (start === -1 || end === -1 || end <= start) return null
182
+ const inner = sql.slice(start + 1, end)
183
+ return splitTopLevel(inner)
184
+ .map(normalizeSql)
185
+ .filter(p => p.length > 0)
186
+ .sort()
187
+ }
188
+
189
+ function sameParts(a: string[] | null, b: string[] | null): boolean {
190
+ if (!a || !b) return false
191
+ if (a.length !== b.length) return false
192
+ return a.every((part, i) => part === b[i])
193
+ }
194
+
195
+ /**
196
+ * Reject a picked image that carries any schema object this wallet did not
197
+ * itself create: a trigger, a view, a virtual table, any table/index name
198
+ * outside its own real schema, or — just as dangerous — an allow-listed
199
+ * table/index whose own definition was weakened (e.g. a dropped UNIQUE, a
200
+ * retyped or removed column, a redefined index). `CREATE TABLE/INDEX IF NOT
201
+ * EXISTS` (the whole of createTables()'s migration) is a no-op once an
202
+ * object with that name already exists, so either kind of tampering would
203
+ * otherwise survive forever and stay live for every later write this device
204
+ * makes — so this runs against the deserialized image BEFORE it is ever
205
+ * copied into the real, on-disk database directory (XR-082).
206
+ *
207
+ * The allow-list — both the set of names AND each name's exact canonical
208
+ * `sql` text — is built by running the wallet's own createTables() against a
209
+ * disposable reference database, rather than a hand-maintained copy, so it
210
+ * can never drift out of sync with the real schema.
211
+ *
212
+ * A `table` object's `sql` is compared column-set-wise rather than as raw
213
+ * text (see `extractTableDefParts`), because a genuine device that ran a
214
+ * real, shipped `ALTER TABLE ADD COLUMN` migration (e.g.
215
+ * `ensureTokenSettlementColumns`) ends up with its migrated-in columns in a
216
+ * different position than `createTables()`'s current inline definition, with
217
+ * no tampering involved (XR-082 follow-up). Every other object type (index,
218
+ * and anything else that reaches this point) is still compared as exact
219
+ * normalized text, since those are never rewritten by an additive migration.
220
+ */
221
+ async function isSchemaTrusted(sourceDb: SQLite.SQLiteDatabase): Promise<boolean> {
222
+ let refDb: SQLite.SQLiteDatabase | undefined
223
+ try {
224
+ refDb = await SQLite.openDatabaseAsync(':memory:')
225
+ 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 }>
229
+ const allowed = new Map(allowedRows.map(r => [r.name, { type: r.type, sql: r.sql }]))
230
+
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 }>
234
+ for (const obj of objects) {
235
+ if (obj.type === 'trigger' || obj.type === 'view') return false
236
+ if (obj.sql && /^\s*create\s+virtual\s+table/i.test(obj.sql)) return false
237
+ const canonical = allowed.get(obj.name)
238
+ if (canonical === undefined) return false
239
+ if (obj.type !== canonical.type) return false
240
+ if (obj.type === 'table') {
241
+ if (!sameParts(extractTableDefParts(obj.sql), extractTableDefParts(canonical.sql))) return false
242
+ } else if (normalizeSql(obj.sql) !== normalizeSql(canonical.sql)) {
243
+ return false
244
+ }
245
+ }
246
+ return true
247
+ } catch {
248
+ return false
249
+ } finally {
250
+ try {
251
+ await refDb?.closeAsync()
252
+ } catch {}
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Build a destination filename guaranteed not to collide with the currently
258
+ * active database or any already-registered one. An import must never place
259
+ * its bytes under a name another connection could already have open, and
260
+ * must never silently become indistinguishable from — or overwrite — a file
261
+ * already in the registry (XR-079/XR-084).
262
+ */
263
+ function buildUniqueTargetFilename(keySuffix: string, chain: string, baseTs: number, taken: Set<string>): string {
264
+ let ts = baseTs
265
+ let name = `wallet-${keySuffix}-${chain}net-${ts}.db`
266
+ while (taken.has(name)) {
267
+ ts += 1
268
+ name = `wallet-${keySuffix}-${chain}net-${ts}.db`
269
+ }
270
+ return name
271
+ }
272
+
42
273
  /**
43
274
  * Let the user pick a wallet `.db` backup file and import it alongside any
44
275
  * existing databases. The wallet context will use whichever database has the
@@ -67,38 +298,48 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
67
298
  const asset = result.assets[0]
68
299
  const pickedName = asset.name
69
300
 
301
+ // ── 1.5 Enforce a size ceiling ───────────────────────────────────────────
302
+ // Picker metadata is untrusted, but it is still the cheapest possible
303
+ // rejection — refuse before ever constructing a File or reading a byte
304
+ // (XR-087). A missing size is treated the same as an oversized one: fail
305
+ // closed rather than assume a small file.
306
+ if (asset.size == null || asset.size > MAX_IMPORT_BYTES) {
307
+ return rejectAsOversized(asset.uri)
308
+ }
309
+
70
310
  // ── 2. Validate filename ──────────────────────────────────────────────────
71
311
  const parsed = parseDbFilename(pickedName)
72
312
  if (!parsed) {
73
313
  await showAlert({
74
314
  title: i18n.t('import_invalid_file'),
75
315
  message: i18n.t('import_invalid_file_detail'),
76
- buttons: [{ text: i18n.t('done'), key: 'ok' }],
316
+ buttons: [{ text: i18n.t('done'), key: 'ok' }]
77
317
  })
78
318
  return { imported: false }
79
319
  }
80
320
 
81
321
  const { keySuffix, chain } = parsed
82
322
 
83
- // If the imported file has no timestamp (legacy format), assign the current
84
- // time so it gets a unique filename and participates in timestamp selection.
85
- let targetFilename: string
86
- if (parsed.timestamp === 0) {
87
- const ts = Math.floor(Date.now() / 1000)
88
- targetFilename = `wallet-${keySuffix}-${chain}net-${ts}.db`
89
- } else {
90
- targetFilename = pickedName
323
+ const nowSec = Math.floor(Date.now() / 1000)
324
+ if (parsed.timestamp > nowSec + MAX_FUTURE_SKEW_SECONDS) {
325
+ // A filename timestamp from the future can only be forged — reject
326
+ // before it ever gets a chance to compete in selectLatestDb (XR-079).
327
+ return rejectAsUntrusted()
91
328
  }
92
329
 
330
+ // Used only for the conflict dialog's "will this become active" messaging
331
+ // below — the actual on-disk destination filename is always synthesized
332
+ // fresh in step 5, never reused from the picked name (XR-079/XR-084).
333
+ const displayTs = parsed.timestamp === 0 ? nowSec : parsed.timestamp
334
+
93
335
  // ── 3. Check for conflicts ────────────────────────────────────────────────
94
336
  const existingDbs = await getRegisteredDbs(keySuffix, chain)
95
- const importTs = parseTimestampFromFilename(targetFilename)
96
337
 
97
338
  if (existingDbs.length > 0) {
98
339
  const currentBest = selectLatestDb(existingDbs)
99
340
  const currentBestTs = parseTimestampFromFilename(currentBest)
100
341
 
101
- if (currentBestTs >= importTs) {
342
+ if (currentBestTs >= displayTs) {
102
343
  // Existing DB has a higher or equal timestamp — imported file will NOT
103
344
  // become the active database.
104
345
  const choice = await showAlert({
@@ -106,8 +347,8 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
106
347
  message: i18n.t('import_conflict_message'),
107
348
  buttons: [
108
349
  { text: i18n.t('cancel'), style: 'cancel', key: 'cancel' },
109
- { text: i18n.t('import_anyway'), style: 'destructive', key: 'import' },
110
- ],
350
+ { text: i18n.t('import_anyway'), style: 'destructive', key: 'import' }
351
+ ]
111
352
  })
112
353
  if (choice !== 'import') return { imported: false }
113
354
  } else {
@@ -117,8 +358,8 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
117
358
  message: i18n.t('import_confirm_message'),
118
359
  buttons: [
119
360
  { text: i18n.t('cancel'), style: 'cancel', key: 'cancel' },
120
- { text: i18n.t('import_wallet_data'), key: 'import' },
121
- ],
361
+ { text: i18n.t('import_wallet_data'), key: 'import' }
362
+ ]
122
363
  })
123
364
  if (choice !== 'import') return { imported: false }
124
365
  }
@@ -135,9 +376,18 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
135
376
  return { imported: false }
136
377
  }
137
378
 
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)
384
+ }
385
+
138
386
  // ── 5. Place the database via deserialize → backup ────────────────────────
139
387
  let sourceDb: SQLite.SQLiteDatabase | undefined
140
388
  let destDb: SQLite.SQLiteDatabase | undefined
389
+ let untrusted = false
390
+ let targetFilename = ''
141
391
  try {
142
392
  // Deserialize the imported bytes into an in-memory database. Exports of
143
393
  // the WAL-mode wallet DB carry a WAL header, which the in-memory VFS
@@ -145,15 +395,76 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
145
395
  // rollback-journal mode first.
146
396
  sourceDb = await SQLite.deserializeDatabaseAsync(prepareSqliteImageForDeserialize(bytes))
147
397
 
148
- // Open (or create) a file-backed database with the target filename.
149
- // This places the file in the default expo-sqlite database directory.
150
- destDb = await SQLite.openDatabaseAsync(targetFilename)
398
+ // Authenticate the image against the currently unlocked wallet BEFORE any
399
+ // of it is written to disk under an authoritative name: exactly one
400
+ // settings row, whose storageIdentityKey and chain match this wallet's
401
+ // own. A same-suffix foreign database, a multi-identity image, or a
402
+ // picked file with no wallet schema at all are all rejected here
403
+ // (XR-079/XR-080). `storage` is required — with no active wallet to
404
+ // authenticate against, the image cannot be trusted either.
405
+ const sourceIdentity = await readSourceIdentity(sourceDb)
406
+ const expectedIdentityKey = storage?.getSettings().storageIdentityKey
407
+ const expectedChain = storage?.chain
408
+ const schemaTrusted = await isSchemaTrusted(sourceDb)
409
+ if (
410
+ !schemaTrusted ||
411
+ !sourceIdentity ||
412
+ !expectedIdentityKey ||
413
+ !expectedChain ||
414
+ sourceIdentity.storageIdentityKey !== expectedIdentityKey ||
415
+ sourceIdentity.chain !== expectedChain
416
+ ) {
417
+ untrusted = true
418
+ } else {
419
+ // Always synthesize a fresh destination name: never the picked name,
420
+ // never a name already registered, never the live database's own
421
+ // filename. This is what actually stops a same-filename import from
422
+ // overwriting (or racing) the active database (XR-079/XR-084).
423
+ const taken = new Set<string>(existingDbs)
424
+ if (storage.dbName) taken.add(storage.dbName)
425
+ targetFilename = buildUniqueTargetFilename(keySuffix, chain, displayTs, taken)
426
+
427
+ // Open (or create) a file-backed database with the target filename.
428
+ // This places the file in the default expo-sqlite database directory.
429
+ destDb = await SQLite.openDatabaseAsync(targetFilename)
151
430
 
152
- // Copy all data from the in-memory source into the file-backed dest
153
- await SQLite.backupDatabaseAsync({
154
- sourceDatabase: sourceDb,
155
- destDatabase: destDb
156
- })
431
+ // Copy all data from the in-memory source into the file-backed dest
432
+ await SQLite.backupDatabaseAsync({
433
+ sourceDatabase: sourceDb,
434
+ destDatabase: destDb
435
+ })
436
+
437
+ // backupDatabaseAsync just copied key_value_store verbatim, including
438
+ // any localpay_pending queue the source had — a record placed there by
439
+ // whoever wrote that file, never re-verified by processPending before
440
+ // it is drained into internalizeAction/onTokenHeld. Quarantine at this
441
+ // boundary, before the copy is ever registered or read: an imported
442
+ // backup must never be able to seed the live queue (XR-081).
443
+ await destDb.runAsync('DELETE FROM key_value_store WHERE key IN (?, ?)', [PENDING_KEY, PENDING_SUMMARY_KEY])
444
+
445
+ // prewarmOwnRoots (core/headers/prewarm.ts) reads proven_txs's own
446
+ // (height, merkleRoot) pairs straight off this device's active
447
+ // database and trusts a match against them offline, forever, with no
448
+ // further check — so an imported file's proven_txs rows would become
449
+ // permanently-trusted chain proof for whatever heights it names. This
450
+ // device already re-derives every proof it needs from its own header
451
+ // sync and recordProof (see unprovenWithoutReqSql.ts's doc comment for
452
+ // that self-healing path), so nothing legitimate is lost by refusing to
453
+ // carry an import's copy of this table forward (XR-083).
454
+ await destDb.runAsync('DELETE FROM proven_txs')
455
+
456
+ // A 'queued'/'posting' offline_actions row is a signed, possibly
457
+ // already-handed-off spend that only the automatic post-build drain
458
+ // (WalletContext's TaskSendOffline) is waiting to rebroadcast. Nothing
459
+ // distinguishes a row copied in by this import from one this device
460
+ // queued itself, so without this, an imported snapshot that predates
461
+ // the user aborting a payment would have it posted again, unattended,
462
+ // the next time the app is online. Downgrade to 'import_hold' — a
463
+ // status no drain query ever selects — so it stays put until reviewed;
464
+ // never delete or otherwise mutate the row, since it may already have
465
+ // been broadcast (XR-085).
466
+ await destDb.runAsync(`UPDATE offline_actions SET status = 'import_hold' WHERE status IN ('queued', 'posting')`)
467
+ }
157
468
  } catch (e: any) {
158
469
  console.error('[importDatabases] Failed to place database:', e.message)
159
470
  showToast(e.message, { type: 'error' })
@@ -167,6 +478,10 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
167
478
  } catch {}
168
479
  }
169
480
 
481
+ if (untrusted) {
482
+ return rejectAsUntrusted()
483
+ }
484
+
170
485
  // ── 6. Register in the wallet DB registry ─────────────────────────────────
171
486
  await registerDb(keySuffix, chain, targetFilename)
172
487
 
package/ui/index.ts CHANGED
@@ -4,6 +4,7 @@ export const CANARY_UI = 'ui'
4
4
  export type { DismissTarget } from './dismissTarget'
5
5
  export { showAlert, AlertHost } from './components/ui/AlertCard'
6
6
  export type { AlertButton, AlertOptions } from './components/ui/AlertCard'
7
+ export { restorePrompts } from './recoveryPrompts'
7
8
  export { showChoiceSheet, choiceSheetOrder } from './components/ui/ChoiceSheet'
8
9
  export { default as AppLogo } from './components/ui/AppLogo'
9
10
  export { BlurChrome } from './components/ui/BlurChrome'
@@ -131,7 +132,7 @@ export { VaultTransferScreen } from './screens/VaultTransferScreen'
131
132
  // app/connections.tsx, app/pair.tsx, app/trust.tsx, app/logs.tsx).
132
133
  // validateTrust.ts/isImageUrl.ts moved alongside TrustScreen as its only
133
134
  // dependency in app-root utils/ (deterministicColor.ts/deterministicImage.ts
134
- // stayed put — nothing moving in this task references them). QRScanner was
135
+ // were unused dead code and have since been deleted). QRScanner was
135
136
  // already pulled forward in Task 21; see the components section above.
136
137
  export { ConnectionsScreen } from './screens/ConnectionsScreen'
137
138
  export { PairScreen } from './screens/PairScreen'
@@ -163,7 +164,13 @@ export {
163
164
  tokenAmountMask,
164
165
  tokenAmountParts
165
166
  } from './tokenFormat'
166
- export { tokenStatusKey, tokenStatusTone, tokenStatusDetailKey, type TokenStatusTone } from './tokenStatus'
167
+ export {
168
+ tokenStatusKey,
169
+ tokenRowStatusView,
170
+ tokenStatusTone,
171
+ tokenStatusDetailKey,
172
+ type TokenStatusTone
173
+ } from './tokenStatus'
167
174
  export { SEEN_ASSETS_KEY, SEEN_EVICTIONS_KEY, markSeen, readSeen, useSeenSet, type SeenSet } from './tokenSeen'
168
175
  export { default as AssetAmount, type AssetAmountProps } from './components/wallet/AssetAmount'
169
176
  export { announceEviction, evictionsFrom, type EvictionNotice } from './components/wallet/tokenEviction'
@@ -179,3 +186,27 @@ export {
179
186
  } from './components/pay/tokenSendCopy'
180
187
  export type { HandleReceiveProps } from './components/pay/HandleReceive'
181
188
  export type { AmountInputAsset } from './components/wallet/AmountInput'
189
+
190
+ // Contacts, profile, and the pencil-edit affordance they share (2026-09-18)
191
+ export { ContactsScreen } from './screens/ContactsScreen'
192
+ export { ContactScreen } from './screens/ContactScreen'
193
+ export { NewContactScreen } from './screens/NewContactScreen'
194
+ export { ProfileScreen } from './screens/ProfileScreen'
195
+ export { IdentifierScreen } from './screens/IdentifierScreen'
196
+ export { default as ProfileButton } from './components/wallet/ProfileButton'
197
+ export { default as ContactSigil } from './components/wallet/ContactSigil'
198
+ export { PencilEditField, type PencilEditFieldProps } from './components/ui/PencilEditField'
199
+
200
+ export {
201
+ default as TransactionDetailScreen,
202
+ type TransactionDetailParams,
203
+ type TransactionAction
204
+ } from './screens/TransactionDetailScreen'
205
+
206
+ export { default as SlideOverFromRight } from './components/ui/SlideOverFromRight'
207
+
208
+ export { default as UserAvatar, AvatarGlyph } from './components/wallet/UserAvatar'
209
+ export { AVATAR_ICON_GROUPS, type AvatarIconOption, type AvatarIconGroup } from './components/wallet/avatarIcons'
210
+
211
+ export { default as IconPickerSheet } from './components/wallet/IconPickerSheet'
212
+ export { default as EditPictureSheet, type EditPictureOption } from './components/wallet/EditPictureSheet'
package/ui/isImageUrl.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  * is reached from the `ui` barrel. TrustScreen gives its Image the same
5
5
  * treatment.
6
6
  */
7
+ import { isPublicHttpsUrl } from '../core/net/publicDestination'
8
+
7
9
  type ExpoImageModule = typeof import('expo-image')
8
10
  let expoImage: ExpoImageModule | undefined
9
11
  function loadExpoImage(): ExpoImageModule {
@@ -15,6 +17,10 @@ function loadExpoImage(): ExpoImageModule {
15
17
  }
16
18
 
17
19
  export default async (url: string): Promise<boolean> => {
20
+ // A trust manifest's icon URL is exactly as untrusted as the rest of the
21
+ // manifest — prefetching it must not be able to reach a loopback or
22
+ // private-network service (XR-073 / SEC2-057, SEC2-076).
23
+ if (!isPublicHttpsUrl(url)) return false
18
24
  try {
19
25
  return await loadExpoImage().Image.prefetch(url)
20
26
  } catch {
@@ -19,12 +19,7 @@
19
19
  * formats apart on recovery.
20
20
  */
21
21
  import { Mnemonic, PrivateKey } from '@bsv/sdk'
22
- import {
23
- ENTROPY_BYTES,
24
- generateEntropyShares,
25
- generateLegacyKeyShares,
26
- generatePrintHTML
27
- } from './backupShares'
22
+ import { ENTROPY_BYTES, generateEntropyShares, generateLegacyKeyShares, generatePrintHTML } from './backupShares'
28
23
  import { recoverMnemonicWallet } from '@bsv/expo-wallet-toolbox'
29
24
 
30
25
  /**
@@ -64,9 +59,7 @@ export type PrintSharesResult =
64
59
  * message. A dismissed print sheet still rejects from expo-print and is the
65
60
  * caller's business.
66
61
  */
67
- export async function printRecoveryShares(
68
- sources: PrintSharesSources
69
- ): Promise<PrintSharesResult> {
62
+ export async function printRecoveryShares(sources: PrintSharesSources): Promise<PrintSharesResult> {
70
63
  const Print = loadExpoPrint()
71
64
  let shares: string[]
72
65
  let identityKey: string
@@ -88,6 +81,12 @@ export async function printRecoveryShares(
88
81
  return { ok: false, reason: 'no-material' }
89
82
  }
90
83
 
91
- await Print.printAsync({ html: await generatePrintHTML(shares, identityKey, format, sources.appName) })
84
+ // XR-110: one native print job per share, never all of them in a single
85
+ // document. The 2-of-3 threshold means any single job — spooled, retained
86
+ // or logged anywhere along the OS print pipeline — must not by itself carry
87
+ // enough shares to reconstruct the wallet.
88
+ for (let i = 0; i < shares.length; i++) {
89
+ await Print.printAsync({ html: await generatePrintHTML(shares, identityKey, format, sources.appName, i) })
90
+ }
92
91
  return { ok: true, format }
93
92
  }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * restorePrompts(t) — the ONE copy of both recovery dialogs recoverWallet
3
+ * needs (`RestorePrompts` from core/recovery/recoverWallet.ts), built on
4
+ * `showAlert`. Both the mnemonic screen and the scan-shares screen pass
5
+ * `restorePrompts(t)` straight through to `recoverWallet`, so the copy for
6
+ * a refused biometric or a failed backup replay exists exactly once.
7
+ *
8
+ * Dismissing an alert (Android back button, tapping outside) resolves
9
+ * `showAlert` to something other than one of the declared button keys —
10
+ * each prompt here maps that to the SAFER of its two choices, not the
11
+ * literal "closest" one:
12
+ *
13
+ * - biometricRefused: dismiss → 'cancel'. Nothing has been written yet at
14
+ * this point (a refused store attempt touches nothing — see
15
+ * restoreWallet.ts), so treating an ambiguous dismissal as "give up" costs
16
+ * the user nothing they had.
17
+ * - restoreFailed: dismiss → 'retry', never 'skip'. 'skip' proceeds WITHOUT
18
+ * replaying the encrypted backup, which can leave real coins unspendable
19
+ * (see recoverWallet.ts's docs) — an accidental tap-outside must never be
20
+ * read as "I accept that risk". 'retry' just returns the user to their
21
+ * input, which is always safe to default to.
22
+ * - confirmReplace: dismiss → 'keep', never 'replace'. 'replace' overwrites
23
+ * the device's only copy of an existing secret (see recoverWallet.ts's
24
+ * docs) — an accidental tap-outside must never be read as "yes, destroy
25
+ * my current wallet". 'keep' leaves the device exactly as it was.
26
+ *
27
+ * A fourth dialog, `restoreUnverified`, is not part of `RestorePrompts` — it
28
+ * has nothing to do with the retry/skip policy `recoverWallet.ts` drives, and
29
+ * is never called there (see its own docs: the policy stays headless).
30
+ * Single-button, so there is nothing for a dismissal to choose between; it
31
+ * just resolves once acknowledged. The two screens (mnemonic, scan-shares)
32
+ * call it themselves, after a successful `recoverWallet` whose outcome came
33
+ * back `verified: false`, before showing their own celebration.
34
+ *
35
+ * Does NOT decide the retry/skip POLICY (that's recoverWallet.ts, which
36
+ * calls these and interprets the result) — this module only renders the
37
+ * dialogs and reports which button was pressed.
38
+ */
39
+ import { showAlert } from './components/ui/AlertCard'
40
+ import type { RestorePrompts } from '../core/recovery/recoverWallet'
41
+
42
+ /** Loose structural type: whatever `useTranslation()`'s `t` looks like here. */
43
+ type TFunctionLike = (key: string) => string
44
+
45
+ export function restorePrompts(t: TFunctionLike): RestorePrompts & { restoreUnverified(): Promise<void> } {
46
+ return {
47
+ async biometricRefused() {
48
+ const choice = await showAlert({
49
+ title: t('scan_shares_biometric_title'),
50
+ message: t('scan_shares_biometric_message'),
51
+ buttons: [
52
+ { text: t('cancel'), style: 'cancel', key: 'cancel' },
53
+ { text: t('retry'), key: 'retry' }
54
+ ]
55
+ })
56
+ return choice === 'retry' ? 'retry' : 'cancel'
57
+ },
58
+
59
+ async restoreFailed(error?: string) {
60
+ const choice = await showAlert({
61
+ title: t('restore_backup_failed_title'),
62
+ message: t('restore_backup_failed_message') + (error ? '\n\n' + error : ''),
63
+ buttons: [
64
+ { text: t('restore_backup_retry'), key: 'retry' },
65
+ { text: t('restore_backup_skip'), key: 'skip', style: 'destructive' }
66
+ ]
67
+ })
68
+ return choice === 'skip' ? 'skip' : 'retry'
69
+ },
70
+
71
+ async confirmReplace() {
72
+ const choice = await showAlert({
73
+ title: t('recovery_replace_wallet_title'),
74
+ message: t('recovery_replace_wallet_body'),
75
+ buttons: [
76
+ { text: t('cancel'), style: 'cancel', key: 'keep' },
77
+ { text: t('recovery_replace_wallet_confirm'), style: 'destructive', key: 'replace' }
78
+ ]
79
+ })
80
+ return choice === 'replace' ? 'replace' : 'keep'
81
+ },
82
+
83
+ async restoreUnverified() {
84
+ await showAlert({
85
+ title: t('restore_backup_unverified_title'),
86
+ message: t('restore_backup_unverified_body'),
87
+ buttons: [{ text: t('dismiss'), key: 'dismiss' }]
88
+ })
89
+ }
90
+ }
91
+ }