@bsv/expo-wallet-toolbox 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +9 -5
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/context/WalletConnectionContext.tsx +7 -1
  41. package/core/context/WalletContext.tsx +258 -133
  42. package/core/context/sessionTeardown.ts +46 -0
  43. package/core/hooks/usePermissionQueue.ts +89 -34
  44. package/core/i18n/translations.tsx +911 -12
  45. package/core/index.ts +15 -0
  46. package/core/services/autoApprovePolicy.ts +7 -1
  47. package/core/services/capWalletArgs.ts +2 -1
  48. package/core/services/permissionPrompts.ts +132 -0
  49. package/core/services/signingPermissionPolicy.ts +230 -2
  50. package/core/services/vault/guard.ts +10 -0
  51. package/core/services/walletArgLimits.ts +17 -2
  52. package/core/storage/encryptedDbImage.ts +325 -0
  53. package/core/toolboxConfig.ts +18 -1
  54. package/package.json +6 -6
  55. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  56. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  57. package/ui/components/ui/PermissionSheet.tsx +534 -158
  58. package/ui/components/ui/Sheet.tsx +59 -7
  59. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  60. package/ui/exportDatabases.ts +94 -5
  61. package/ui/hooks/useExportWalletData.ts +37 -24
  62. package/ui/importDatabases.ts +123 -28
  63. package/ui/index.ts +4 -0
  64. package/ui/screens/WalletConfigScreen.tsx +13 -1
@@ -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
+ }
@@ -2,6 +2,7 @@ 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'
5
6
 
6
7
  /**
7
8
  * Service endpoints and API keys for one chain.
@@ -165,8 +166,17 @@ 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 }
168
176
  }
169
177
 
178
+ export type BrowserBridgeHostConfig = NonNullable<ToolboxConfig['browserBridge']>
179
+
170
180
  interface ResolvedConfig {
171
181
  backupUrl: string
172
182
  services: Partial<Record<AppChain, ToolboxServiceConfig>>
@@ -176,6 +186,7 @@ interface ResolvedConfig {
176
186
  vaultEnabled: boolean
177
187
  push: PushAdapter | undefined
178
188
  directPay: DirectPayHostConfig | undefined
189
+ browserBridge: BrowserBridgeHostConfig | undefined
179
190
  }
180
191
 
181
192
  let current: ResolvedConfig | null = null
@@ -271,7 +282,8 @@ export function configureToolbox(config: ToolboxConfig): void {
271
282
  handleMinLength: config.handleMinLength === 1 || config.handleMinLength === 2 ? config.handleMinLength : 3,
272
283
  vaultEnabled: config.vaultEnabled === true,
273
284
  push: config.push,
274
- directPay: config.directPay
285
+ directPay: config.directPay,
286
+ browserBridge: config.browserBridge
275
287
  }
276
288
  }
277
289
 
@@ -444,6 +456,11 @@ export function getDirectPayConfig(): DirectPayHostConfig | undefined {
444
456
  return current?.directPay
445
457
  }
446
458
 
459
+ /** What the host stated about the browser bridge; `{}` when it stated nothing. Never throws. */
460
+ export function getBrowserBridgeConfig(): BrowserBridgeHostConfig {
461
+ return current?.browserBridge ?? {}
462
+ }
463
+
447
464
  /**
448
465
  * Whether the vault may be used on this network.
449
466
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -31,15 +31,15 @@
31
31
  "peerDependencies": {
32
32
  "@bsv/air-gap": "^0.1.3",
33
33
  "@bsv/backup-cache-client": "^0.1.0",
34
- "@bsv/btms-permission-module": "^1.2.1",
34
+ "@bsv/btms-permission-module": "^1.2.4",
35
35
  "@bsv/color-permission-module": "^0.2.0",
36
36
  "@bsv/mandala": "^0.5.0",
37
- "@bsv/message-box-client": "^2.5.3",
37
+ "@bsv/message-box-client": "^2.7.0",
38
38
  "@bsv/react-native-localpay-transport": "*",
39
- "@bsv/sdk": "^4.0.0",
39
+ "@bsv/sdk": "^4.0.1",
40
40
  "@bsv/templates": "^2.2.0",
41
- "@bsv/wallet-toolbox-mobile": "^2.15.0",
42
- "@bsv/webrtpay": "^0.2.1",
41
+ "@bsv/wallet-toolbox-mobile": "^2.15.1",
42
+ "@bsv/webrtpay": "^0.2.3",
43
43
  "@expo/vector-icons": "^15.0.3",
44
44
  "@noble/curves": "^2.3.0",
45
45
  "@react-native-async-storage/async-storage": "^2.2.0",
@@ -0,0 +1,86 @@
1
+ import React, { useContext, useLayoutEffect, useSyncExternalStore } from 'react'
2
+ import { RELAYED_CONTEXTS } from './relayedContexts'
3
+
4
+ /**
5
+ * Feeds a second React root the contexts of the first (spec 7.4, 10). `ContextRelayPublisher` is rendered inside
6
+ * the first root's providers and writes each relayed context's current value into a module-level store;
7
+ * `ContextRelaySubscriber` is the second root's top and re-provides those values to its children. Both roots live
8
+ * in one JS runtime, so the store is shared by module identity and a value change (a theme switch, a wallet state
9
+ * update) reaches the subscriber without remounting it.
10
+ *
11
+ * The subscriber renders nothing until every entry has been published once: a child must never read a context
12
+ * default (the default of `WalletContext` is a wallet that is not there).
13
+ */
14
+
15
+ type Snapshot = { readonly values: ReadonlyArray<unknown>; readonly published: ReadonlyArray<boolean> }
16
+
17
+ const EMPTY: Snapshot = {
18
+ values: RELAYED_CONTEXTS.map(() => undefined),
19
+ published: RELAYED_CONTEXTS.map(() => false)
20
+ }
21
+
22
+ let snapshot: Snapshot = EMPTY
23
+ const listeners = new Set<() => void>()
24
+
25
+ function emit(): void {
26
+ for (const fn of [...listeners]) fn()
27
+ }
28
+
29
+ function subscribe(fn: () => void): () => void {
30
+ listeners.add(fn)
31
+ return () => {
32
+ listeners.delete(fn)
33
+ }
34
+ }
35
+
36
+ function getSnapshot(): Snapshot {
37
+ return snapshot
38
+ }
39
+
40
+ function publish(values: ReadonlyArray<unknown>): void {
41
+ const changed = values.some((v, i) => !snapshot.published[i] || !Object.is(v, snapshot.values[i]))
42
+ if (!changed) return
43
+ snapshot = { values: [...values], published: values.map(() => true) }
44
+ emit()
45
+ }
46
+
47
+ /** Publishes one entry only; tests use it to prove the subscriber waits for every entry. Not exported from the barrel. */
48
+ export function publishRelayedContextForTest(name: string, value: unknown): void {
49
+ const i = RELAYED_CONTEXTS.findIndex(e => e.name === name)
50
+ if (i < 0) throw new Error(`not a relayed context: ${name}`)
51
+ const values = [...snapshot.values]
52
+ const published = [...snapshot.published]
53
+ values[i] = value
54
+ published[i] = true
55
+ snapshot = { values, published }
56
+ emit()
57
+ }
58
+
59
+ /** Clears the store: tests, and sign-out (a later sheet must not render a signed-out wallet's values). */
60
+ export function resetContextRelay(): void {
61
+ snapshot = EMPTY
62
+ emit()
63
+ }
64
+
65
+ /** Rendered once inside the first root's providers. Renders nothing. */
66
+ export const ContextRelayPublisher: React.FC = () => {
67
+ // The list is a module constant, so the number of hooks never changes between renders.
68
+ const values = RELAYED_CONTEXTS.map(entry => useContext(entry.context)) // eslint-disable-line react-hooks/rules-of-hooks
69
+ // Layout effect: the second root learns the value before the next paint, so a theme switch never shows one frame
70
+ // of mixed colours across the two roots.
71
+ useLayoutEffect(() => {
72
+ publish(values)
73
+ })
74
+ return null
75
+ }
76
+
77
+ /** The second root's top: re-provides each relayed context with the live value. */
78
+ export const ContextRelaySubscriber: React.FC<{ children: React.ReactNode }> = ({ children }) => {
79
+ const snap = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
80
+ if (!snap.published.every(Boolean)) return null
81
+ // The nesting is stable (same order, same types), so a value change updates providers in place and never remounts.
82
+ return RELAYED_CONTEXTS.reduceRight<React.ReactNode>(
83
+ (inner, entry, i) => <entry.context.Provider value={snap.values[i]}>{inner}</entry.context.Provider>,
84
+ children
85
+ ) as React.ReactElement
86
+ }
@@ -0,0 +1,21 @@
1
+ import type React from 'react'
2
+ import { ThemeContext } from '../../core/theme/ThemeContext'
3
+ import { WalletContext } from '../../core/context/WalletContext'
4
+ import { ExchangeRateContext } from '../../core/context/ExchangeRateContext'
5
+ import { UserContext } from '../../core/context/UserContext'
6
+
7
+ /**
8
+ * The React contexts `PermissionSheet` (and the cards it renders) read. The Android bridge sheet runs on a second
9
+ * React root of the same React host (spec 7.4), and a second root does not see the first root's providers, so each
10
+ * context listed here is copied across by `ContextRelay`. A context the sheet reads that is not listed here would
11
+ * silently fall back to its default value on the second root: `relayedContexts.test.tsx` scans the sheet's import
12
+ * closure and fails until the new context is added.
13
+ *
14
+ * Language is intentionally not listed: i18n is a module singleton and `useTranslation` reads it without a provider.
15
+ */
16
+ export const RELAYED_CONTEXTS: ReadonlyArray<{ name: string; context: React.Context<any> }> = [
17
+ { name: 'ThemeContext', context: ThemeContext },
18
+ { name: 'WalletContext', context: WalletContext },
19
+ { name: 'ExchangeRateContext', context: ExchangeRateContext },
20
+ { name: 'UserContext', context: UserContext }
21
+ ]