@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
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Encrypted wallet database export format ("Export Wallet Data" with
3
+ * `encrypt: true`).
4
+ *
5
+ * Envelope encryption: a fresh random 32-byte file key encrypts the database
6
+ * image, and the wallet itself encrypts (wraps) that file key with BRC-2
7
+ * `wallet.encrypt` under counterparty `self`. Only the wallet that exported a
8
+ * file can open it again — the same rule import already enforces on the
9
+ * plaintext image (its storageIdentityKey must match).
10
+ *
11
+ * The body is a STREAM-style chunked AES-256-GCM: every chunk is sealed on
12
+ * its own with nonce `prefix(7) || u32 BE chunk index || last-flag(1)`, so
13
+ * chunks can be encrypted, written and decrypted one at a time (memory stays
14
+ * at one chunk, never the whole database), and any reordered, dropped,
15
+ * duplicated or truncated chunk fails authentication. The header fields
16
+ * (version, chunk size, nonce prefix) ride inside the wallet-encrypted blob
17
+ * next to the file key, so they are authenticated by it rather than through
18
+ * AAD.
19
+ *
20
+ * Wire layout:
21
+ *
22
+ * magic "BSVWDBE1" (8) | u16 BE wrappedLen | wrapped (wrappedLen) | chunk*
23
+ * chunk = ciphertext (chunkSize, the last one 0..chunkSize) | GCM tag (16)
24
+ *
25
+ * wrapped = wallet.encrypt( version(1) | u32 BE chunkSize | prefix(7) | fileKey(32) )
26
+ *
27
+ * AES runs in native code: react-native-quick-crypto's OpenSSL backend that
28
+ * the host app installs as `globalThis.__bsvNativeCrypto` (Node's own crypto
29
+ * under Jest). Without one, encryption refuses rather than crawl through a
30
+ * pure-JS AES over a whole database.
31
+ */
32
+ import type { WalletInterface, WalletProtocol } from '@bsv/sdk'
33
+
34
+ export const ENCRYPTED_DB_MAGIC = [0x42, 0x53, 0x56, 0x57, 0x44, 0x42, 0x45, 0x31] // "BSVWDBE1"
35
+ export const ENCRYPTED_DB_EXTENSION = '.db.enc'
36
+ export const DB_EXPORT_PROTOCOL: WalletProtocol = [2, 'wallet db export']
37
+ export const DB_EXPORT_KEY_ID = '1'
38
+
39
+ const FORMAT_VERSION = 1
40
+ const DEFAULT_CHUNK_SIZE = 1024 * 1024
41
+ /** A decrypt never allocates more than this per chunk, whatever the header claims. */
42
+ const MAX_CHUNK_SIZE = 16 * 1024 * 1024
43
+ const TAG_LEN = 16
44
+ const KEY_LEN = 32
45
+ const PREFIX_LEN = 7
46
+ const HEADER_PLAIN_LEN = 1 + 4 + PREFIX_LEN + KEY_LEN
47
+ /** BRC-2 adds a 32-byte IV and a 16-byte tag; anything far outside that is not ours. */
48
+ const MAX_WRAPPED_LEN = 1024
49
+
50
+ export type EncryptedDbErrorCode = 'no-native-crypto' | 'not-encrypted' | 'wrong-wallet' | 'unsupported' | 'corrupt'
51
+
52
+ /** All the wallet this needs: a ProtoWallet or the permissions manager both fit. */
53
+ export type DbExportWallet = Pick<WalletInterface, 'encrypt' | 'decrypt'>
54
+
55
+ export class EncryptedDbError extends Error {
56
+ constructor(
57
+ readonly code: EncryptedDbErrorCode,
58
+ message: string
59
+ ) {
60
+ super(message)
61
+ this.name = 'EncryptedDbError'
62
+ }
63
+ }
64
+
65
+ /** Sequential reader over the input; `read` returns fewer bytes only at EOF. */
66
+ export interface ByteSource {
67
+ readonly size: number
68
+ read(length: number): Uint8Array
69
+ }
70
+
71
+ export interface ByteSink {
72
+ write(bytes: Uint8Array): void
73
+ }
74
+
75
+ export interface EncryptedDbOptions {
76
+ /** Origin the wallet call is made as — the admin originator, so it never prompts. */
77
+ originator?: string
78
+ /** Called after each chunk with the fraction done (0..1). */
79
+ onProgress?: (fraction: number) => void
80
+ /** Test seam; defaults to 1 MiB. */
81
+ chunkSize?: number
82
+ }
83
+
84
+ interface GcmCipher {
85
+ update(data: Uint8Array): ArrayBuffer | Uint8Array
86
+ final(): ArrayBuffer | Uint8Array
87
+ getAuthTag(): ArrayBuffer | Uint8Array
88
+ }
89
+ interface GcmDecipher {
90
+ setAuthTag(tag: Uint8Array): void
91
+ update(data: Uint8Array): ArrayBuffer | Uint8Array
92
+ final(): ArrayBuffer | Uint8Array
93
+ }
94
+ interface NativeCrypto {
95
+ createCipheriv(alg: 'aes-256-gcm', key: Uint8Array, iv: Uint8Array): GcmCipher
96
+ createDecipheriv(alg: 'aes-256-gcm', key: Uint8Array, iv: Uint8Array): GcmDecipher
97
+ randomBytes(n: number): ArrayBuffer | Uint8Array
98
+ }
99
+
100
+ /** Backends already seen to refuse a wrong GCM tag. */
101
+ const authenticating = new WeakSet<NativeCrypto>()
102
+
103
+ /**
104
+ * Every integrity property of this format rests on `final()` throwing for a
105
+ * wrong tag — which react-native-quick-crypto 0.7.17 did not do until this
106
+ * repo patched it (patches/react-native-quick-crypto+0.7.17.patch). A host
107
+ * app without that patch would accept a tampered file, so check once per
108
+ * backend and refuse rather than trust it.
109
+ */
110
+ function assertAuthenticates(backend: NativeCrypto): void {
111
+ if (authenticating.has(backend)) return
112
+ const key = toBuf(toU8(backend.randomBytes(KEY_LEN)))
113
+ const iv = toBuf(toU8(backend.randomBytes(12)))
114
+ const cipher = backend.createCipheriv('aes-256-gcm', key, iv)
115
+ const body = toU8(cipher.update(toBuf(new Uint8Array(16))))
116
+ cipher.final()
117
+ const tag = Uint8Array.from(toU8(cipher.getAuthTag()))
118
+ tag[0] ^= 1
119
+ const decipher = backend.createDecipheriv('aes-256-gcm', key, iv)
120
+ decipher.setAuthTag(toBuf(tag))
121
+ let refused = false
122
+ try {
123
+ decipher.update(toBuf(body))
124
+ decipher.final()
125
+ } catch {
126
+ refused = true
127
+ }
128
+ if (!refused) {
129
+ throw new EncryptedDbError('no-native-crypto', 'The crypto backend does not authenticate AES-GCM')
130
+ }
131
+ authenticating.add(backend)
132
+ }
133
+
134
+ function nativeCrypto(): NativeCrypto {
135
+ const g = globalThis as {
136
+ __bsvNativeCrypto?: NativeCrypto
137
+ process?: { getBuiltinModule?: (id: string) => unknown }
138
+ }
139
+ const backend = g.__bsvNativeCrypto ?? (g.process?.getBuiltinModule?.('node:crypto') as NativeCrypto | undefined)
140
+ if (!backend?.createCipheriv) {
141
+ throw new EncryptedDbError(
142
+ 'no-native-crypto',
143
+ 'Encrypted export needs the native crypto backend (react-native-quick-crypto installed as globalThis.__bsvNativeCrypto)'
144
+ )
145
+ }
146
+ assertAuthenticates(backend)
147
+ return backend
148
+ }
149
+
150
+ /** quick-crypto hands back ArrayBuffers and wants Buffers in; Node wants Buffers too. */
151
+ function toU8(x: ArrayBuffer | Uint8Array): Uint8Array {
152
+ return x instanceof Uint8Array ? x : new Uint8Array(x)
153
+ }
154
+ function toBuf(x: Uint8Array): Uint8Array {
155
+ const B = (globalThis as { Buffer?: { from(b: ArrayBufferLike, o: number, l: number): Uint8Array } }).Buffer
156
+ return B ? B.from(x.buffer, x.byteOffset, x.byteLength) : x
157
+ }
158
+
159
+ function concat(parts: Uint8Array[]): Uint8Array {
160
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
161
+ let off = 0
162
+ for (const p of parts) {
163
+ out.set(p, off)
164
+ off += p.length
165
+ }
166
+ return out
167
+ }
168
+
169
+ function chunkNonce(prefix: Uint8Array, index: number, last: boolean): Uint8Array {
170
+ const n = new Uint8Array(12)
171
+ n.set(prefix, 0)
172
+ new DataView(n.buffer).setUint32(PREFIX_LEN, index, false)
173
+ n[11] = last ? 1 : 0
174
+ return n
175
+ }
176
+
177
+ /** Let the UI thread render between chunks: every crypto/file call here is synchronous JSI. */
178
+ const yieldToUi = () => new Promise<void>(resolve => setTimeout(resolve, 0))
179
+
180
+ /** True when `head` (the first bytes of a file) starts with this format's magic. */
181
+ export function isEncryptedDbImage(head: Uint8Array): boolean {
182
+ if (head.length < ENCRYPTED_DB_MAGIC.length) return false
183
+ return ENCRYPTED_DB_MAGIC.every((b, i) => head[i] === b)
184
+ }
185
+
186
+ /** Stream `src` (a plaintext SQLite image) into `sink` as an encrypted export. */
187
+ export async function encryptDbImage(
188
+ wallet: DbExportWallet,
189
+ src: ByteSource,
190
+ sink: ByteSink,
191
+ opts: EncryptedDbOptions = {}
192
+ ): Promise<void> {
193
+ const crypto = nativeCrypto()
194
+ const chunkSize = opts.chunkSize ?? DEFAULT_CHUNK_SIZE
195
+ const fileKey = toU8(crypto.randomBytes(KEY_LEN))
196
+ const prefix = toU8(crypto.randomBytes(PREFIX_LEN))
197
+
198
+ const headerPlain = new Uint8Array(HEADER_PLAIN_LEN)
199
+ const hv = new DataView(headerPlain.buffer)
200
+ headerPlain[0] = FORMAT_VERSION
201
+ hv.setUint32(1, chunkSize, false)
202
+ headerPlain.set(prefix, 5)
203
+ headerPlain.set(fileKey, 5 + PREFIX_LEN)
204
+
205
+ const { ciphertext: wrapped } = await wallet.encrypt(
206
+ {
207
+ plaintext: Array.from(headerPlain),
208
+ protocolID: DB_EXPORT_PROTOCOL,
209
+ keyID: DB_EXPORT_KEY_ID,
210
+ counterparty: 'self',
211
+ seekPermission: false
212
+ },
213
+ opts.originator
214
+ )
215
+ headerPlain.fill(0)
216
+ if (wrapped.length > MAX_WRAPPED_LEN) throw new EncryptedDbError('unsupported', 'Wrapped key unexpectedly large')
217
+
218
+ const lead = new Uint8Array(ENCRYPTED_DB_MAGIC.length + 2)
219
+ lead.set(ENCRYPTED_DB_MAGIC, 0)
220
+ new DataView(lead.buffer).setUint16(ENCRYPTED_DB_MAGIC.length, wrapped.length, false)
221
+ sink.write(lead)
222
+ sink.write(Uint8Array.from(wrapped))
223
+
224
+ // An empty input still gets one (empty, final) chunk, so a decrypt can tell
225
+ // "nothing" apart from "cut off after the header".
226
+ const total = src.size
227
+ const chunks = Math.max(1, Math.ceil(total / chunkSize))
228
+ const key = toBuf(fileKey)
229
+ try {
230
+ for (let i = 0; i < chunks; i++) {
231
+ const last = i === chunks - 1
232
+ const plain = src.read(last ? total - i * chunkSize : chunkSize)
233
+ if (plain.length !== (last ? total - i * chunkSize : chunkSize)) {
234
+ throw new EncryptedDbError('corrupt', 'Database changed size while it was being exported')
235
+ }
236
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, toBuf(chunkNonce(prefix, i, last)))
237
+ const body = toU8(cipher.update(toBuf(plain)))
238
+ const tail = toU8(cipher.final())
239
+ sink.write(tail.length ? concat([body, tail]) : body)
240
+ sink.write(toU8(cipher.getAuthTag()))
241
+ opts.onProgress?.((i + 1) / chunks)
242
+ if (!last) await yieldToUi()
243
+ }
244
+ } finally {
245
+ fileKey.fill(0)
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Stream an encrypted export in `src` back into its plaintext SQLite image in
251
+ * `sink`. Plaintext reaches the sink a chunk at a time, each one only after
252
+ * its own tag verified; a failure part-way leaves a prefix in the sink, which
253
+ * the caller must discard (it throws, it never returns a partial image).
254
+ */
255
+ export async function decryptDbImage(
256
+ wallet: DbExportWallet,
257
+ src: ByteSource,
258
+ sink: ByteSink,
259
+ opts: EncryptedDbOptions = {}
260
+ ): Promise<void> {
261
+ const crypto = nativeCrypto()
262
+ const leadLen = ENCRYPTED_DB_MAGIC.length + 2
263
+ const lead = src.read(leadLen)
264
+ if (lead.length < leadLen || !isEncryptedDbImage(lead)) {
265
+ throw new EncryptedDbError('not-encrypted', 'Not an encrypted wallet database export')
266
+ }
267
+ const wrappedLen = new DataView(lead.buffer, lead.byteOffset).getUint16(ENCRYPTED_DB_MAGIC.length, false)
268
+ if (wrappedLen === 0 || wrappedLen > MAX_WRAPPED_LEN) throw new EncryptedDbError('corrupt', 'Bad key header')
269
+ const wrapped = src.read(wrappedLen)
270
+ if (wrapped.length !== wrappedLen) throw new EncryptedDbError('corrupt', 'File is truncated')
271
+
272
+ let headerPlain: Uint8Array
273
+ try {
274
+ const { plaintext } = await wallet.decrypt(
275
+ {
276
+ ciphertext: Array.from(wrapped),
277
+ protocolID: DB_EXPORT_PROTOCOL,
278
+ keyID: DB_EXPORT_KEY_ID,
279
+ counterparty: 'self'
280
+ },
281
+ opts.originator
282
+ )
283
+ headerPlain = Uint8Array.from(plaintext)
284
+ } catch {
285
+ throw new EncryptedDbError('wrong-wallet', 'This export was made by a different wallet')
286
+ }
287
+ if (headerPlain.length !== HEADER_PLAIN_LEN || headerPlain[0] !== FORMAT_VERSION) {
288
+ throw new EncryptedDbError('unsupported', 'Unsupported export format version')
289
+ }
290
+ const chunkSize = new DataView(headerPlain.buffer).getUint32(1, false)
291
+ if (chunkSize === 0 || chunkSize > MAX_CHUNK_SIZE) throw new EncryptedDbError('corrupt', 'Bad chunk size')
292
+ const prefix = headerPlain.slice(5, 5 + PREFIX_LEN)
293
+ const key = toBuf(headerPlain.slice(5 + PREFIX_LEN))
294
+ headerPlain.fill(0)
295
+
296
+ let remaining = src.size - leadLen - wrappedLen
297
+ const bodyTotal = remaining
298
+ try {
299
+ for (let i = 0; ; i++) {
300
+ const sealedLen = Math.min(chunkSize + TAG_LEN, remaining)
301
+ if (sealedLen < TAG_LEN) throw new EncryptedDbError('corrupt', 'File is truncated')
302
+ const last = sealedLen === remaining
303
+ const sealed = src.read(sealedLen)
304
+ if (sealed.length !== sealedLen) throw new EncryptedDbError('corrupt', 'File is truncated')
305
+ remaining -= sealedLen
306
+
307
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, toBuf(chunkNonce(prefix, i, last)))
308
+ decipher.setAuthTag(toBuf(sealed.subarray(sealedLen - TAG_LEN)))
309
+ let plain: Uint8Array
310
+ try {
311
+ const body = toU8(decipher.update(toBuf(sealed.subarray(0, sealedLen - TAG_LEN))))
312
+ const tail = toU8(decipher.final())
313
+ plain = tail.length ? concat([body, tail]) : body
314
+ } catch {
315
+ throw new EncryptedDbError('corrupt', 'File is damaged or was modified')
316
+ }
317
+ sink.write(plain)
318
+ opts.onProgress?.(bodyTotal ? (bodyTotal - remaining) / bodyTotal : 1)
319
+ if (last) break
320
+ await yieldToUi()
321
+ }
322
+ } finally {
323
+ key.fill(0)
324
+ }
325
+ }
@@ -34,6 +34,20 @@ class ConnectionStore {
34
34
  * list; mobx wraps it as an ObservableMap, but nothing here relies on
35
35
  * that reactivity. */
36
36
  private pendingAuthorityTags = new Map<string, string>()
37
+ private revocations = new Map<string, number>()
38
+ private allRevocations = 0
39
+
40
+ revocationVersion(sessionId?: string): number {
41
+ // Clipboard approval starts before its topic is known. Any intervening
42
+ // revocation must invalidate that gesture before it can claim a new topic.
43
+ if (sessionId === undefined) return this.allRevocations
44
+ return this.revocations.get(sessionId) ?? 0
45
+ }
46
+
47
+ private revokePending(sessionId: string) {
48
+ this.allRevocations++
49
+ this.revocations.set(sessionId, this.revocationVersion(sessionId) + 1)
50
+ }
37
51
 
38
52
  constructor() {
39
53
  makeAutoObservable(this)
@@ -68,6 +82,7 @@ class ConnectionStore {
68
82
  }
69
83
 
70
84
  setStatus(sessionId: string, status: Connection['status']) {
85
+ if (status === 'disconnected') this.revokePending(sessionId)
71
86
  const conn = this.connections.find(c => c.sessionId === sessionId)
72
87
  if (conn) {
73
88
  conn.status = status
@@ -76,6 +91,8 @@ class ConnectionStore {
76
91
  }
77
92
 
78
93
  remove(sessionId: string) {
94
+ this.revokePending(sessionId)
95
+ this.pendingAuthorityTags.delete(sessionId)
79
96
  this.connections = this.connections.filter(c => c.sessionId !== sessionId)
80
97
  void this.save()
81
98
  }
@@ -2,6 +2,8 @@ import type { AppChain } from './config'
2
2
  import type { PushAdapter } from './push/types'
3
3
  import { trimTrailingSlashes } from './net/trimTrailingSlashes'
4
4
  import { isRelayUrl, isStunUrl } from './directpay/settings'
5
+ import type { PermissionPolicyOverride } from './bridge/permissionPolicy'
6
+ import { resetE2eMode, setE2eMode } from './e2e/mode'
5
7
 
6
8
  /**
7
9
  * Service endpoints and API keys for one chain.
@@ -15,7 +17,6 @@ export interface ToolboxServiceConfig {
15
17
  arcApiKey?: string
16
18
  chaintracksUrl?: string
17
19
  whatsOnChainApiKey?: string
18
- taalApiKey?: string
19
20
  /**
20
21
  * The chain's default MessageBox origin. A user's own choice in Settings
21
22
  * still wins; this only replaces the built-in default in `NETWORKS`.
@@ -165,8 +166,28 @@ export interface ToolboxConfig {
165
166
  * change.
166
167
  */
167
168
  directPay?: DirectPayHostConfig
169
+ /**
170
+ * The browser bridge (BRC-185). Optional; a host that omits it gets the built-in policy.
171
+ * `allowLocalhostHttp` lets a development build accept `http://localhost` origins.
172
+ * `permissionPolicy` states this build's default prompt settings for verified and
173
+ * unverified origins; the user's own stored policy wins over it.
174
+ */
175
+ browserBridge?: { allowLocalhostHttp?: boolean; permissionPolicy?: PermissionPolicyOverride }
176
+ /**
177
+ * End-to-end harness. Omit it in every build that can hold funds.
178
+ *
179
+ * Presence locks the wallet off mainnet, stores new keys without a biometric
180
+ * prompt, and points Pay's confirm button at `broadcasterUrl` instead of a
181
+ * real broadcaster. The host sets it only when `EXPO_PUBLIC_E2E` is the
182
+ * string `"true"`. A harness build also has to disable backup, the vault
183
+ * and push, and must not pass mainnet service endpoints — `configureToolbox`
184
+ * throws otherwise, so a copied production profile cannot boot as E2E.
185
+ */
186
+ e2e?: { broadcasterUrl: string }
168
187
  }
169
188
 
189
+ export type BrowserBridgeHostConfig = NonNullable<ToolboxConfig['browserBridge']>
190
+
170
191
  interface ResolvedConfig {
171
192
  backupUrl: string
172
193
  services: Partial<Record<AppChain, ToolboxServiceConfig>>
@@ -176,6 +197,7 @@ interface ResolvedConfig {
176
197
  vaultEnabled: boolean
177
198
  push: PushAdapter | undefined
178
199
  directPay: DirectPayHostConfig | undefined
200
+ browserBridge: BrowserBridgeHostConfig | undefined
179
201
  }
180
202
 
181
203
  let current: ResolvedConfig | null = null
@@ -238,6 +260,51 @@ function normalizeBackupUrl(raw: string): string {
238
260
  return trimmed
239
261
  }
240
262
 
263
+ /**
264
+ * The mock broadcaster has to be a local or private origin. `10.0.2.2` is the
265
+ * Android emulator's alias for its host and is not an RFC 1918 address, so it
266
+ * is named here. It is not added to the general service-origin policy.
267
+ * Public hosts are refused even over https: the harness must not post a
268
+ * payment description off the machine running the tests.
269
+ */
270
+ function isE2eBroadcasterUrl(raw: string): boolean {
271
+ let parsed: URL
272
+ try {
273
+ parsed = new URL(raw)
274
+ } catch {
275
+ return false
276
+ }
277
+ if (parsed.username || parsed.password) return false
278
+ if (parsed.pathname !== '' && parsed.pathname !== '/') return false
279
+ if (parsed.search !== '' || parsed.hash !== '') return false
280
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false
281
+ const host = parsed.hostname
282
+ return host === '10.0.2.2' || host === 'localhost' || host === '127.0.0.1' || PRIVATE_HOST.test(host)
283
+ }
284
+
285
+ function checkE2eConfig(config: ToolboxConfig): string | undefined {
286
+ if (config.e2e === undefined) return undefined
287
+ const url = config.e2e.broadcasterUrl?.trim() ?? ''
288
+ if (!isE2eBroadcasterUrl(url)) {
289
+ throw new Error(
290
+ `configureToolbox: e2e.broadcasterUrl must be a loopback, 10.0.2.2, or private-network origin: ${config.e2e.broadcasterUrl}`
291
+ )
292
+ }
293
+ if (config.backupUrl != null) {
294
+ throw new Error('configureToolbox: an E2E build must pass backupUrl: null')
295
+ }
296
+ if (config.vaultEnabled === true) {
297
+ throw new Error('configureToolbox: an E2E build must not enable the vault')
298
+ }
299
+ if (config.push !== undefined) {
300
+ throw new Error('configureToolbox: an E2E build must not install a push adapter')
301
+ }
302
+ if (config.services?.main !== undefined) {
303
+ throw new Error('configureToolbox: an E2E build must not configure mainnet services')
304
+ }
305
+ return url.replace(/\/$/, '')
306
+ }
307
+
241
308
  /** Throws unless the host's direct pay addresses are acceptable; unset fields are fine. */
242
309
  function checkDirectPayHostConfig(directPay: DirectPayHostConfig | undefined): void {
243
310
  if (directPay === undefined) return
@@ -262,6 +329,7 @@ export function configureToolbox(config: ToolboxConfig): void {
262
329
  if (config == null || !('backupUrl' in config)) {
263
330
  throw new Error('configureToolbox: backupUrl is required. Pass null to disable backup.')
264
331
  }
332
+ const e2eBroadcasterUrl = checkE2eConfig(config)
265
333
  checkDirectPayHostConfig(config.directPay)
266
334
  current = {
267
335
  backupUrl: config.backupUrl == null ? '' : normalizeBackupUrl(config.backupUrl),
@@ -271,8 +339,10 @@ export function configureToolbox(config: ToolboxConfig): void {
271
339
  handleMinLength: config.handleMinLength === 1 || config.handleMinLength === 2 ? config.handleMinLength : 3,
272
340
  vaultEnabled: config.vaultEnabled === true,
273
341
  push: config.push,
274
- directPay: config.directPay
342
+ directPay: config.directPay,
343
+ browserBridge: config.browserBridge
275
344
  }
345
+ setE2eMode(e2eBroadcasterUrl)
276
346
  }
277
347
 
278
348
  /**
@@ -444,6 +514,11 @@ export function getDirectPayConfig(): DirectPayHostConfig | undefined {
444
514
  return current?.directPay
445
515
  }
446
516
 
517
+ /** What the host stated about the browser bridge; `{}` when it stated nothing. Never throws. */
518
+ export function getBrowserBridgeConfig(): BrowserBridgeHostConfig {
519
+ return current?.browserBridge ?? {}
520
+ }
521
+
447
522
  /**
448
523
  * Whether the vault may be used on this network.
449
524
  *
@@ -471,4 +546,5 @@ export function isVaultAvailable(chain: AppChain, profileIndex: number): boolean
471
546
  /** Test-only: drop the installed configuration. */
472
547
  export function resetToolboxConfig(): void {
473
548
  current = null
549
+ resetE2eMode()
474
550
  }
@@ -0,0 +1,5 @@
1
+ {
2
+ "platforms": ["apple", "android"],
3
+ "apple": { "modules": ["BsvBoundedFetchModule"] },
4
+ "android": { "modules": ["org.bsv.boundedfetch.BsvBoundedFetchModule"] }
5
+ }
@@ -0,0 +1,15 @@
1
+ import Foundation
2
+
3
+ /// Counts decoded response bytes before they enter the accumulated body.
4
+ final class BoundedBody {
5
+ enum Error: Swift.Error { case tooLarge }
6
+ let limit: Int
7
+ private(set) var data = Data()
8
+
9
+ init(limit: Int) { self.limit = limit }
10
+
11
+ func append(_ chunk: Data) throws {
12
+ guard chunk.count <= limit - data.count else { throw Error.tooLarge }
13
+ data.append(chunk)
14
+ }
15
+ }
@@ -0,0 +1,17 @@
1
+ require 'json'
2
+ package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
3
+ Pod::Spec.new do |s|
4
+ s.name = 'BsvBoundedFetch'
5
+ s.version = package['version']
6
+ s.summary = 'Native receive-time byte limits for wallet HTTP responses'
7
+ s.description = s.summary
8
+ s.license = package['license']
9
+ s.author = 'BSV Association'
10
+ s.homepage = 'https://github.com/bsv-blockchain/bsv-wallet'
11
+ s.platforms = { :ios => '15.1' }
12
+ s.swift_version = '5.9'
13
+ s.source = { :git => 'https://github.com/bsv-blockchain/bsv-wallet.git' }
14
+ s.static_framework = true
15
+ s.dependency 'ExpoModulesCore'
16
+ s.source_files = '*.swift'
17
+ end
@@ -0,0 +1,121 @@
1
+ import ExpoModulesCore
2
+ import Foundation
3
+
4
+ public final class BsvBoundedFetchModule: Module {
5
+ private let lock = NSLock()
6
+ private var requests: [String: BoundedRequest] = [:]
7
+
8
+ public func definition() -> ModuleDefinition {
9
+ Name("BsvBoundedFetch")
10
+
11
+ AsyncFunction("request") { (options: [String: Any], promise: Promise) in
12
+ guard let id = options["id"] as? String,
13
+ let address = options["url"] as? String,
14
+ let url = URL(string: address), url.scheme == "https",
15
+ let limit = options["maxBytes"] as? Int, (0...67108864).contains(limit) else {
16
+ promise.reject("ERR_INVALID_REQUEST", "Invalid bounded HTTPS request")
17
+ return
18
+ }
19
+ var request = URLRequest(url: url)
20
+ request.httpMethod = options["method"] as? String ?? "GET"
21
+ for header in options["headers"] as? [[String]] ?? [] where header.count == 2 {
22
+ request.setValue(header[1], forHTTPHeaderField: header[0])
23
+ }
24
+ if let encoded = options["body"] as? String { request.httpBody = Data(base64Encoded: encoded) }
25
+ let receiver = BoundedRequest(limit: limit) { result in
26
+ self.lock.lock()
27
+ self.requests.removeValue(forKey: id)
28
+ self.lock.unlock()
29
+ switch result {
30
+ case .success(let reply): promise.resolve(reply)
31
+ case .failure(let error): promise.reject("ERR_BOUNDED_FETCH", error.localizedDescription)
32
+ }
33
+ }
34
+ self.lock.lock()
35
+ self.requests[id] = receiver
36
+ self.lock.unlock()
37
+ receiver.start(request)
38
+ }
39
+
40
+ AsyncFunction("cancel") { (id: String) in
41
+ self.lock.lock()
42
+ let receiver = self.requests[id]
43
+ self.lock.unlock()
44
+ receiver?.cancel()
45
+ }
46
+
47
+ OnDestroy {
48
+ self.lock.lock()
49
+ let active = Array(self.requests.values)
50
+ self.requests.removeAll()
51
+ self.lock.unlock()
52
+ active.forEach { $0.cancel() }
53
+ }
54
+ }
55
+ }
56
+
57
+ /// URLSession supplies decoded chunks; the only accumulating buffer is capped
58
+ /// synchronously on its serial delegate queue, before bytes can cross to JS.
59
+ private final class BoundedRequest: NSObject, URLSessionDataDelegate {
60
+ private let body: BoundedBody
61
+ private let completion: (Result<[String: Any], Swift.Error>) -> Void
62
+ private var session: URLSession?
63
+ private var response: HTTPURLResponse?
64
+ private var failure: Swift.Error?
65
+
66
+ init(limit: Int, completion: @escaping (Result<[String: Any], Swift.Error>) -> Void) {
67
+ self.body = BoundedBody(limit: limit)
68
+ self.completion = completion
69
+ }
70
+
71
+ func start(_ request: URLRequest) {
72
+ let config = URLSessionConfiguration.ephemeral
73
+ config.timeoutIntervalForRequest = 30
74
+ config.timeoutIntervalForResource = 30
75
+ config.httpCookieStorage = nil
76
+ config.urlCache = nil
77
+ let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
78
+ self.session = session
79
+ session.dataTask(with: request).resume()
80
+ }
81
+
82
+ func cancel() { session?.invalidateAndCancel() }
83
+
84
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
85
+ didReceive response: URLResponse,
86
+ completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
87
+ self.response = response as? HTTPURLResponse
88
+ if response.expectedContentLength > Int64(body.limit) {
89
+ failure = NSError(domain: "ERR_RESPONSE_TOO_LARGE", code: 1,
90
+ userInfo: [NSLocalizedDescriptionKey: "ERR_RESPONSE_TOO_LARGE"])
91
+ completionHandler(.cancel)
92
+ } else {
93
+ completionHandler(.allow)
94
+ }
95
+ }
96
+
97
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
98
+ do { try body.append(data) } catch {
99
+ failure = NSError(domain: "ERR_RESPONSE_TOO_LARGE", code: 1,
100
+ userInfo: [NSLocalizedDescriptionKey: "ERR_RESPONSE_TOO_LARGE"])
101
+ dataTask.cancel()
102
+ }
103
+ }
104
+
105
+ func urlSession(_ session: URLSession, task: URLSessionTask,
106
+ willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest,
107
+ completionHandler: @escaping (URLRequest?) -> Void) {
108
+ completionHandler(nil)
109
+ }
110
+
111
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Swift.Error?) {
112
+ defer { session.finishTasksAndInvalidate() }
113
+ if let error = failure ?? error { completion(.failure(error)); return }
114
+ guard let response = response else {
115
+ completion(.failure(URLError(.badServerResponse)))
116
+ return
117
+ }
118
+ let headers = response.allHeaderFields.map { [String(describing: $0.key), String(describing: $0.value)] }
119
+ completion(.success(["status": response.statusCode, "headers": headers, "body": body.data.base64EncodedString()]))
120
+ }
121
+ }