@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,642 @@
1
+ /**
2
+ * Bridge runtime (spec 6.2, 6.7, 6.9): the process-wide meeting point between transports, the
3
+ * binding registry and the wallet the host built.
4
+ *
5
+ * `BrowserBridgeProvider` publishes the managers, readiness, network and account context here.
6
+ * Transports register once and learn about closes. The runtime owns the wallet revision: a
7
+ * persisted, install-wide counter bumped whenever a built wallet's managers are replaced inside a
8
+ * process (not on the first build after launch). A bump closes every binding with
9
+ * `account-changed`, withdraws the departed wallet's prompts and drops pending site consent. That
10
+ * is what covers a same-wallet rebuild, where the account context stays the same.
11
+ *
12
+ * Module state, like `sessionTeardown`: one wallet session exists per process. Tests reset it with
13
+ * `resetBridgeRuntimeForTests`.
14
+ */
15
+ import AsyncStorage from '@react-native-async-storage/async-storage'
16
+ import { Hash, Utils, type WalletInterface } from '@bsv/sdk'
17
+ import * as SecureStore from 'expo-secure-store'
18
+ import { AppState } from 'react-native'
19
+ import { registerSessionTeardown } from '../context/sessionTeardown'
20
+ import type { SigningPolicyPermissionsManager } from '../services/signingPermissionPolicy'
21
+ import { createBindingRegistry, type Binding, type BindingRegistry, type CloseEvent } from './bindings'
22
+ import {
23
+ sweepConsentStorage,
24
+ type ConnectedSite,
25
+ type ConsentStore,
26
+ type HmacCapableWallet,
27
+ type KeyValue
28
+ } from './consent'
29
+ import { loadStoredPolicy, resolvePermissionPolicy, saveStoredPolicy, type PermissionPolicy } from './permissionPolicy'
30
+ import { connectionError } from './protocol/connectionError'
31
+ import type { Attestation } from './protocol/origin'
32
+ import { getBrowserBridgeConfig } from '../toolboxConfig'
33
+ import { setUnattestedTransportPresent } from './runtimeFlags'
34
+
35
+ export type BridgeReadiness = 'ready' | 'building' | 'blocked' | 'none'
36
+
37
+ /** What the cross-process mirror (project 2) reads. `schema` changes only incompatibly. */
38
+ export interface BridgeSnapshot {
39
+ schema: 1
40
+ baseVersion: string
41
+ network: string
42
+ accountContext: string
43
+ walletRevision: string
44
+ readiness: BridgeReadiness
45
+ closeSeq: number
46
+ /**
47
+ * True while a host is attached AND the runtime has loaded (`isBridgeHostAttached()`), false at
48
+ * start and again after the detach function. It is a snapshot field so a transport hears the
49
+ * change even when readiness does not move (`none` is also the state of a cold start with no
50
+ * wallet, so readiness alone cannot say "the host is gone").
51
+ */
52
+ hostAttached: boolean
53
+ }
54
+
55
+ /**
56
+ * The static `getVersion` answer: a BRC-205 base of 7 to 30 bytes (spec 6.6). The host can
57
+ * override it through the provider.
58
+ */
59
+ export const DEFAULT_BASE_VERSION = 'bsv-wallet-bridge-1'
60
+
61
+ /** A published manager: the callable wallet stack and the signing manager under it. */
62
+ export interface BridgeManager {
63
+ /** What a request is dispatched against (the guarded, conformance-wrapped manager). */
64
+ wallet: WalletInterface
65
+ /** The manager itself. Its object identity detects a replacement, and it is what gets retired. */
66
+ signing: SigningPolicyPermissionsManager
67
+ }
68
+
69
+ export interface PublishInput {
70
+ attestedManager?: BridgeManager
71
+ unverifiedManager?: BridgeManager
72
+ readiness: BridgeReadiness
73
+ network: string
74
+ accountContext: string
75
+ }
76
+
77
+ export interface TransportRegistration {
78
+ id: string
79
+ attestation: Attestation
80
+ bindingMode: 'implicit' | 'explicit'
81
+ /** Called when a request is parked: waiting for consent, for the wallet, or for a prompt in the background. */
82
+ requestAttention(reason: AttentionReason, binding: Binding): void
83
+ onClosed?(event: CloseEvent): void
84
+ /**
85
+ * A manager permission prompt was raised for the binding's originator. Called for every live binding of
86
+ * that originator whether or not the app is active (a transport can use it for receipts); unlike
87
+ * `requestAttention('prompt')` it is not behind the active-app gate. A throw is logged and isolated.
88
+ */
89
+ onPromptRaised?(binding: Binding): void
90
+ /** Mandatory for `unattested`, absent otherwise: delivers the token the core minted at approval. */
91
+ deliverReconnectToken?(binding: Binding, token: string): void
92
+ }
93
+
94
+ export type AttentionReason = 'consent' | 'wallet-not-ready' | 'prompt'
95
+
96
+ export interface TransportHandle {
97
+ readonly id: string
98
+ readonly attestation: Attestation
99
+ readonly bindingMode: 'implicit' | 'explicit'
100
+ unregister(): void
101
+ }
102
+
103
+ /** What the provider attaches: the way to withdraw prompts and pending consent for a departed wallet. */
104
+ export interface BridgeHostHooks {
105
+ withdrawPrompts(oldManagers: SigningPolicyPermissionsManager[]): void
106
+ /**
107
+ * True when the install may have a wallet that has not been built yet (a cold start). The
108
+ * snapshot is then `building` from attach, never `none`, until the first publish reports what
109
+ * the provider actually has (spec 6.15 item 9).
110
+ */
111
+ hasWallet?: boolean
112
+ }
113
+
114
+ const REVISION_KEY = 'bsv-bridge-wallet-revision'
115
+ const SECRET_KEY = 'bsv-bridge-install-secret'
116
+ const CONTEXT_DOMAIN = 'bsv-bridge-account-context-v1'
117
+ const secureOptions = { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY }
118
+
119
+ /** What the provider registers so the site and policy APIs can reach the store without React. */
120
+ export interface ActiveConsent {
121
+ store: Pick<ConsentStore, 'listConnectedSites' | 'revokeSite' | 'dropRequestsFor' | 'onChange'>
122
+ /** Admin-scoped, guarded wallet: authenticates the stored policy. */
123
+ adminWallet: Pick<HmacCapableWallet, 'createHmac' | 'verifyHmac'>
124
+ adminOriginator: string
125
+ profileKey: () => string
126
+ }
127
+
128
+ interface RuntimeState {
129
+ storage: KeyValue
130
+ bindings: BindingRegistry
131
+ transports: Map<string, TransportRegistration>
132
+ closeListeners: Set<(e: CloseEvent) => void>
133
+ snapshotListeners: Set<(s: BridgeSnapshot) => void>
134
+ connectedSitesListeners: Set<() => void>
135
+ /** Unsubscribes the forward from the active store's `onChange`. */
136
+ consentForward: (() => void) | undefined
137
+ hooks: BridgeHostHooks | undefined
138
+ consentWithdrawals: Set<() => void>
139
+ /** The provider's current consent store and the admin wallet that authenticates it. */
140
+ consent: ActiveConsent | undefined
141
+ snapshot: BridgeSnapshot
142
+ attested: BridgeManager | undefined
143
+ unverified: BridgeManager | undefined
144
+ /** The signing managers of the last build seen in this process; undefined until the first. */
145
+ lastSigning: SigningPolicyPermissionsManager[] | undefined
146
+ loaded: Promise<void> | undefined
147
+ isLoaded: boolean
148
+ secretQueue: Promise<unknown>
149
+ }
150
+
151
+ function freshSnapshot(): BridgeSnapshot {
152
+ return {
153
+ schema: 1,
154
+ baseVersion: DEFAULT_BASE_VERSION,
155
+ network: '',
156
+ accountContext: '',
157
+ walletRevision: '0',
158
+ readiness: 'none',
159
+ closeSeq: 0,
160
+ hostAttached: false
161
+ }
162
+ }
163
+
164
+ function createState(storage: KeyValue): RuntimeState {
165
+ const state: RuntimeState = {
166
+ storage,
167
+ transports: new Map(),
168
+ closeListeners: new Set(),
169
+ snapshotListeners: new Set(),
170
+ connectedSitesListeners: new Set(),
171
+ consentForward: undefined,
172
+ hooks: undefined,
173
+ consentWithdrawals: new Set(),
174
+ consent: undefined,
175
+ snapshot: freshSnapshot(),
176
+ attested: undefined,
177
+ unverified: undefined,
178
+ lastSigning: undefined,
179
+ loaded: undefined,
180
+ isLoaded: false,
181
+ secretQueue: Promise.resolve(),
182
+ bindings: undefined as unknown as BindingRegistry
183
+ }
184
+ state.bindings = createBindingRegistry({
185
+ tombstoneStorage: storage,
186
+ now: () => Date.now(),
187
+ onClosed: e => fanOutClose(e),
188
+ transportInfo: id => {
189
+ const t = state.transports.get(id)
190
+ return t === undefined ? undefined : { attestation: t.attestation, bindingMode: t.bindingMode }
191
+ },
192
+ allowLocalhostHttp: () =>
193
+ typeof __DEV__ !== 'undefined' && __DEV__ === true && getBrowserBridgeConfig().allowLocalhostHttp === true
194
+ })
195
+ return state
196
+ }
197
+
198
+ let rt = createState(AsyncStorage as unknown as KeyValue)
199
+ let unregisterTeardown: (() => void) | undefined
200
+
201
+ /* --------------------------------- snapshot -------------------------------- */
202
+
203
+ function setSnapshot(patch: Partial<BridgeSnapshot>): void {
204
+ const next = { ...rt.snapshot, ...patch }
205
+ const changed = (Object.keys(next) as Array<keyof BridgeSnapshot>).some(k => next[k] !== rt.snapshot[k])
206
+ if (!changed) return
207
+ rt.snapshot = next
208
+ for (const fn of [...rt.snapshotListeners]) {
209
+ try {
210
+ fn(next)
211
+ } catch (e) {
212
+ console.warn('[bridge] snapshot listener failed', e)
213
+ }
214
+ }
215
+ }
216
+
217
+ export function getBridgeSnapshot(): BridgeSnapshot {
218
+ return rt.snapshot
219
+ }
220
+
221
+ /** Returns the unsubscribe function. */
222
+ export function onSnapshotChange(fn: (s: BridgeSnapshot) => void): () => void {
223
+ rt.snapshotListeners.add(fn)
224
+ return () => {
225
+ rt.snapshotListeners.delete(fn)
226
+ }
227
+ }
228
+
229
+ /* ---------------------------------- closes --------------------------------- */
230
+
231
+ function fanOutClose(e: CloseEvent): void {
232
+ // Synchronous: a replacement binding is never admitted ahead of this.
233
+ setSnapshot({ closeSeq: Math.max(rt.snapshot.closeSeq, e.closeSeq) })
234
+ try {
235
+ rt.transports.get(e.transportId)?.onClosed?.(e)
236
+ } catch (err) {
237
+ console.warn('[bridge] transport onClosed failed', err)
238
+ }
239
+ for (const fn of [...rt.closeListeners]) {
240
+ try {
241
+ fn(e)
242
+ } catch (err) {
243
+ console.warn('[bridge] close listener failed', err)
244
+ }
245
+ }
246
+ }
247
+
248
+ /** The dispatcher settles in-flight calls from here. Returns the unsubscribe function. */
249
+ export function onBindingClosed(fn: (e: CloseEvent) => void): () => void {
250
+ rt.closeListeners.add(fn)
251
+ return () => {
252
+ rt.closeListeners.delete(fn)
253
+ }
254
+ }
255
+
256
+ /* ---------------------------------- loading -------------------------------- */
257
+
258
+ /**
259
+ * Reads the persisted wallet revision and the tombstone ring. Idempotent; the provider calls it
260
+ * before publishing anything. A storage failure rejects and leaves the runtime unloaded, so it
261
+ * fails closed (requests keep answering `CONFIGURATION_ERROR`).
262
+ */
263
+ export function initBridgeRuntime(): Promise<void> {
264
+ const state = rt
265
+ if (!state.loaded) {
266
+ state.loaded = (async () => {
267
+ const raw = await state.storage.getItem(REVISION_KEY)
268
+ const n = raw === null ? 0 : Number(raw)
269
+ await state.bindings.load()
270
+ // The close counter comes back from the persisted ring too, so the mirrored value never
271
+ // goes backwards across a restart.
272
+ state.isLoaded = true
273
+ setSnapshotOf(state, {
274
+ walletRevision: String(Number.isSafeInteger(n) && n >= 0 ? n : 0),
275
+ closeSeq: state.bindings.closeSeq(),
276
+ hostAttached: state.hooks !== undefined
277
+ })
278
+ })()
279
+ state.loaded.catch(() => {
280
+ state.loaded = undefined
281
+ })
282
+ }
283
+ return state.loaded
284
+ }
285
+
286
+ function setSnapshotOf(state: RuntimeState, patch: Partial<BridgeSnapshot>) {
287
+ if (state === rt) setSnapshot(patch)
288
+ }
289
+
290
+ /* -------------------------------- transports ------------------------------- */
291
+
292
+ export function registerTransport(t: TransportRegistration): TransportHandle {
293
+ if (t.attestation === 'unattested' && t.bindingMode === 'implicit') {
294
+ throw connectionError('CONFIGURATION_ERROR', 'An unattested transport must bind explicitly', 'not-sent')
295
+ }
296
+ if (t.attestation === 'unattested' && typeof t.deliverReconnectToken !== 'function') {
297
+ throw connectionError('CONFIGURATION_ERROR', 'An unattested transport must deliver reconnect tokens', 'not-sent')
298
+ }
299
+ if (t.attestation !== 'unattested' && t.deliverReconnectToken !== undefined) {
300
+ throw connectionError('CONFIGURATION_ERROR', 'Only an unattested transport delivers reconnect tokens', 'not-sent')
301
+ }
302
+ if (typeof t.requestAttention !== 'function') {
303
+ throw connectionError('CONFIGURATION_ERROR', 'A transport must provide requestAttention', 'not-sent')
304
+ }
305
+ if (rt.transports.has(t.id)) {
306
+ throw connectionError('CONFIGURATION_ERROR', 'Transport already registered', 'not-sent')
307
+ }
308
+ const state = rt
309
+ const registration = { ...t }
310
+ state.transports.set(t.id, registration)
311
+ refreshUnattestedFlag()
312
+ return {
313
+ id: t.id,
314
+ attestation: t.attestation,
315
+ bindingMode: t.bindingMode,
316
+ unregister() {
317
+ if (state.transports.get(t.id) !== registration) return
318
+ state.transports.delete(t.id)
319
+ if (state === rt) refreshUnattestedFlag()
320
+ }
321
+ }
322
+ }
323
+
324
+ function refreshUnattestedFlag(): void {
325
+ let any = false
326
+ for (const t of rt.transports.values()) if (t.attestation === 'unattested') any = true
327
+ setUnattestedTransportPresent(any)
328
+ }
329
+
330
+ export function getTransport(id: string): TransportRegistration | undefined {
331
+ return rt.transports.get(id)
332
+ }
333
+
334
+ /* ----------------------------- host (provider) side ------------------------ */
335
+
336
+ /**
337
+ * Called by the provider when it mounts. Registers the session teardown that closes every binding
338
+ * when the wallet session ends. Returns the detach function (provider unmount).
339
+ */
340
+ export function attachBridgeHost(hooks: BridgeHostHooks): () => void {
341
+ rt.hooks = hooks
342
+ setSnapshot({
343
+ hostAttached: isBridgeHostAttached(),
344
+ ...(hooks.hasWallet === true && rt.snapshot.readiness === 'none' ? { readiness: 'building' as const } : {})
345
+ })
346
+ unregisterTeardown?.()
347
+ const state = rt
348
+ unregisterTeardown = registerSessionTeardown(['logout', 'profile', 'network', 'rebuild'], reason => {
349
+ // Pending consent and bindings belong to the departing wallet. The prompts themselves are
350
+ // withdrawn by WalletContext at the same sites, and again at the next rising edge.
351
+ if (rt.isLoaded) rt.bindings.closeAll('account-changed')
352
+ withdrawConsent()
353
+ // The managers are being retired and the wallet torn down behind an await. Drop them from the
354
+ // published set now, so nothing dispatches to a retired manager over a wallet that is being
355
+ // destroyed, and park (or fail) new requests until the provider publishes the next build.
356
+ rt.attested = undefined
357
+ rt.unverified = undefined
358
+ setSnapshot({ readiness: reason === 'logout' ? 'none' : 'building' })
359
+ if (reason === 'logout') {
360
+ void deleteInstallSecret()
361
+ // Logout and Delete Wallet end the session: remembered sites go with it, every profile's
362
+ // key, so restoring the same seed does not reconnect a site silently (spec 6.4).
363
+ sweepConsentStorage(state.storage).catch(e => console.warn('[bridge] could not clear connected sites', e))
364
+ }
365
+ })
366
+ return () => {
367
+ if (state !== rt || rt.hooks !== hooks) return
368
+ unregisterTeardown?.()
369
+ unregisterTeardown = undefined
370
+ rt.hooks = undefined
371
+ rt.attested = undefined
372
+ rt.unverified = undefined
373
+ if (rt.isLoaded) rt.bindings.closeAll('lost')
374
+ setSnapshot({ readiness: 'none', hostAttached: false })
375
+ }
376
+ }
377
+
378
+ export function isBridgeHostAttached(): boolean {
379
+ return rt.hooks !== undefined && rt.isLoaded
380
+ }
381
+
382
+ /** Sets the static `getVersion` string (the host's choice; 7-30 bytes per BRC-205). */
383
+ export function setBridgeBaseVersion(v: string): void {
384
+ setSnapshot({ baseVersion: v })
385
+ }
386
+
387
+ /**
388
+ * Registers what drops pending `connection` requests (`ConsentStore.withdrawAll`), run on every
389
+ * wallet replacement and session teardown. Returns the unregister function.
390
+ */
391
+ export function registerConsentWithdrawal(fn: () => void): () => void {
392
+ rt.consentWithdrawals.add(fn)
393
+ return () => {
394
+ rt.consentWithdrawals.delete(fn)
395
+ }
396
+ }
397
+
398
+ /**
399
+ * A manager permission prompt was raised for `originator`. When the app is not in the foreground
400
+ * and a live binding of that originator is waiting on it, the transport is asked to bring the user
401
+ * to the sheet (`requestAttention('prompt')`, spec 6.2): the call itself has no deadline and would
402
+ * otherwise wait unseen. The originator is the one the wallet call carried, so only the bindings
403
+ * that can have raised it are told. `onPromptRaised` is called for each of them regardless of the
404
+ * app state.
405
+ */
406
+ export function notifyPromptRaised(
407
+ originator: string,
408
+ isActive: () => boolean = () => AppState.currentState === 'active'
409
+ ): void {
410
+ if (!rt.isLoaded) return
411
+ const active = isActive()
412
+ for (const b of rt.bindings.live()) {
413
+ if (b.originator !== originator) continue
414
+ const transport = rt.transports.get(b.transportId)
415
+ try {
416
+ transport?.onPromptRaised?.(b)
417
+ } catch (e) {
418
+ console.warn('[bridge] onPromptRaised failed', e)
419
+ }
420
+ if (active) continue
421
+ try {
422
+ transport?.requestAttention('prompt', b)
423
+ } catch (e) {
424
+ console.warn('[bridge] requestAttention failed', e)
425
+ }
426
+ }
427
+ }
428
+
429
+ /** Registers the live consent store for the site and policy APIs. Returns the unregister function. */
430
+ export function setActiveConsent(c: ActiveConsent | undefined): () => void {
431
+ const state = rt
432
+ state.consentForward?.()
433
+ state.consentForward = undefined
434
+ state.consent = c
435
+ if (c !== undefined) state.consentForward = c.store.onChange(() => notifyConnectedSites(state))
436
+ // The set of connected sites just changed hands, even if neither store reports a change.
437
+ notifyConnectedSites(state)
438
+ return () => {
439
+ if (state.consent !== c) return
440
+ state.consentForward?.()
441
+ state.consentForward = undefined
442
+ state.consent = undefined
443
+ notifyConnectedSites(state)
444
+ }
445
+ }
446
+
447
+ function notifyConnectedSites(state: RuntimeState): void {
448
+ for (const fn of [...state.connectedSitesListeners]) {
449
+ try {
450
+ fn()
451
+ } catch (e) {
452
+ console.warn('[bridge] connected sites listener failed', e)
453
+ }
454
+ }
455
+ }
456
+
457
+ /**
458
+ * Called when a site is connected or revoked on the active profile, and when the provider swaps the
459
+ * consent store (spec 6.5: the cross-process mirror lists the connected sites). Forwards the active
460
+ * store's `ConsentStore.onChange` and follows a swapped store. Returns the unsubscribe function.
461
+ */
462
+ export function onConnectedSitesChange(fn: () => void): () => void {
463
+ const state = rt
464
+ state.connectedSitesListeners.add(fn)
465
+ return () => {
466
+ state.connectedSitesListeners.delete(fn)
467
+ }
468
+ }
469
+
470
+ /** The sites the user has connected on this profile (spec 6.4). Empty when no wallet is mounted. */
471
+ export async function listConnectedSites(): Promise<ConnectedSite[]> {
472
+ return (await rt.consent?.store.listConnectedSites()) ?? []
473
+ }
474
+
475
+ /**
476
+ * Forgets a connected site and closes its live bindings of that attestation with `revoked`
477
+ * (spec 6.4). Bindings of the same origin under the other attestation are untouched. The record is
478
+ * deleted first, so a binding that reconnects in between is asked again.
479
+ */
480
+ export async function revokeSite(origin: string, attestation: Attestation): Promise<void> {
481
+ const state = rt
482
+ if (state.consent === undefined) {
483
+ throw connectionError('CONFIGURATION_ERROR', 'The wallet bridge is not available', 'not-sent')
484
+ }
485
+ // The provider may unwire the store during the await; the revoke still closes the site's bindings.
486
+ const store = state.consent.store
487
+ await store.revokeSite(origin, attestation)
488
+ if (state !== rt || !state.isLoaded) return
489
+ for (const b of state.bindings.live()) {
490
+ if (b.applicationOrigin !== origin || b.attestation !== attestation) continue
491
+ store.dropRequestsFor(b.epoch)
492
+ state.bindings.close(b.epoch, 'revoked')
493
+ }
494
+ }
495
+
496
+ /** The effective permission policy: defaults, the host's statement, then the user's stored policy. */
497
+ export async function getPermissionPolicy(): Promise<PermissionPolicy> {
498
+ const c = rt.consent
499
+ if (c === undefined) return resolvePermissionPolicy()
500
+ return resolvePermissionPolicy(await loadStoredPolicy(c.profileKey(), c.adminWallet, c.adminOriginator))
501
+ }
502
+
503
+ /** Stores the user's policy for this profile. It applies from the next wallet build (spec 6.5). */
504
+ export async function setPermissionPolicy(policy: PermissionPolicy): Promise<void> {
505
+ const c = rt.consent
506
+ if (c === undefined) {
507
+ throw connectionError('CONFIGURATION_ERROR', 'The wallet bridge is not available', 'not-sent')
508
+ }
509
+ await saveStoredPolicy(c.profileKey(), policy, c.adminWallet, c.adminOriginator)
510
+ }
511
+
512
+ function withdrawConsent(): void {
513
+ for (const fn of [...rt.consentWithdrawals]) {
514
+ try {
515
+ fn()
516
+ } catch (e) {
517
+ console.warn('[bridge] consent withdrawal failed', e)
518
+ }
519
+ }
520
+ }
521
+
522
+ function sameSet<T>(a: T[], b: T[]): boolean {
523
+ return a.length === b.length && a.every(x => b.includes(x))
524
+ }
525
+
526
+ /**
527
+ * The provider's report of the wallet it currently has. A manager identity that differs from the
528
+ * previous build's (after the first build in this process) is a wallet replacement: bump the
529
+ * revision, close the bindings, withdraw the old prompts. Detected here rather than from
530
+ * teardown hooks because `rebuildWallet` and the mid-build rebuild have none.
531
+ */
532
+ export function publish(input: PublishInput): void {
533
+ if (!rt.isLoaded) throw new Error('Bridge runtime published to before initBridgeRuntime() resolved')
534
+ const signing: SigningPolicyPermissionsManager[] = []
535
+ if (input.attestedManager) signing.push(input.attestedManager.signing)
536
+ if (input.unverifiedManager) signing.push(input.unverifiedManager.signing)
537
+
538
+ if (signing.length > 0) {
539
+ const previous = rt.lastSigning
540
+ if (previous !== undefined && !sameSet(previous, signing)) {
541
+ const old = previous.filter(m => !signing.includes(m))
542
+ replaceWallet(old)
543
+ }
544
+ rt.lastSigning = signing
545
+ }
546
+ rt.attested = input.attestedManager
547
+ rt.unverified = input.unverifiedManager
548
+ // The revision bump, if any, is already in the snapshot; this carries the rest of the report.
549
+ setSnapshot({
550
+ network: input.network,
551
+ accountContext: input.accountContext,
552
+ readiness: input.readiness
553
+ })
554
+ }
555
+
556
+ function replaceWallet(oldManagers: SigningPolicyPermissionsManager[]): void {
557
+ const next = String(Number(rt.snapshot.walletRevision) + 1)
558
+ // Close first and synchronously, so nothing is admitted on the old wallet's bindings.
559
+ rt.bindings.closeAll('account-changed')
560
+ try {
561
+ rt.hooks?.withdrawPrompts(oldManagers)
562
+ } catch (e) {
563
+ console.warn('[bridge] withdrawPrompts failed', e)
564
+ }
565
+ withdrawConsent()
566
+ setSnapshot({ walletRevision: next })
567
+ const state = rt
568
+ // A failed write leaves the in-memory revision ahead; the next launch starts from the old one,
569
+ // but its bindings are in memory only and its tombstones persist, so nothing revives.
570
+ state.storage.setItem(REVISION_KEY, next).catch(e => console.warn('[bridge] could not persist wallet revision', e))
571
+ }
572
+
573
+ /* ------------------------------ internals for dispatch --------------------- */
574
+
575
+ export function getBindingRegistry(): BindingRegistry {
576
+ return rt.bindings
577
+ }
578
+
579
+ export function getPublishedManagers(): { attested?: BridgeManager; unverified?: BridgeManager } {
580
+ return { attested: rt.attested, unverified: rt.unverified }
581
+ }
582
+
583
+ /**
584
+ * A request with no provider mounted, or before the runtime finished loading, cannot be served.
585
+ * Throws the `CONFIGURATION_ERROR` the dispatcher returns.
586
+ */
587
+ export function assertBridgeHost(): void {
588
+ if (!isBridgeHostAttached()) {
589
+ throw connectionError('CONFIGURATION_ERROR', 'The wallet bridge is not available', 'not-sent')
590
+ }
591
+ }
592
+
593
+ /* ------------------------------ account context ---------------------------- */
594
+
595
+ function serialized<T>(fn: () => Promise<T>): Promise<T> {
596
+ const run = rt.secretQueue.then(fn, fn)
597
+ rt.secretQueue = run.catch(() => undefined)
598
+ return run
599
+ }
600
+
601
+ function randomHex32(): string {
602
+ const bytes = new Uint8Array(32)
603
+ globalThis.crypto.getRandomValues(bytes)
604
+ return Utils.toHex(Array.from(bytes))
605
+ }
606
+
607
+ function getInstallSecret(): Promise<string> {
608
+ return serialized(async () => {
609
+ const existing = await SecureStore.getItemAsync(SECRET_KEY, secureOptions)
610
+ if (existing && /^[0-9a-f]{64}$/.test(existing)) return existing
611
+ const fresh = randomHex32()
612
+ await SecureStore.setItemAsync(SECRET_KEY, fresh, secureOptions)
613
+ return fresh
614
+ })
615
+ }
616
+
617
+ /** Rotates the account context: run at logout and Delete Wallet. */
618
+ export function deleteInstallSecret(): Promise<void> {
619
+ return serialized(() => SecureStore.deleteItemAsync(SECRET_KEY, secureOptions)).catch(e => {
620
+ console.warn('[bridge] could not delete the install secret', e)
621
+ })
622
+ }
623
+
624
+ /**
625
+ * `HMAC-SHA256(installSecret, "bsv-bridge-account-context-v1" || identityKeyHex || network)`,
626
+ * hex. Opaque and local to the app process (6.7).
627
+ */
628
+ export async function computeAccountContext(identityKeyHex: string, network: string): Promise<string> {
629
+ const secret = await getInstallSecret()
630
+ const message = Utils.toArray(CONTEXT_DOMAIN + identityKeyHex + network, 'utf8')
631
+ return Utils.toHex(Hash.sha256hmac(Utils.toArray(secret, 'hex'), message))
632
+ }
633
+
634
+ /* ----------------------------------- tests --------------------------------- */
635
+
636
+ /** Drops all runtime state and the registered teardown; optionally swaps the storage. Tests only. */
637
+ export function resetBridgeRuntimeForTests(storage?: KeyValue): void {
638
+ unregisterTeardown?.()
639
+ unregisterTeardown = undefined
640
+ setUnattestedTransportPresent(false)
641
+ rt = createState(storage ?? (AsyncStorage as unknown as KeyValue))
642
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Whether any registered bridge transport can deliver `unattested` calls (spec 6.5).
3
+ *
4
+ * The wallet build creates the unverified permissions manager only when this is true, and
5
+ * rebuilds its managers when it turns true. Kept in its own dependency-free module so the
6
+ * runtime (which sets it) and WalletContext (which reads it) need not import each other.
7
+ */
8
+
9
+ let present = false
10
+ const listeners = new Set<(present: boolean) => void>()
11
+
12
+ export function setUnattestedTransportPresent(v: boolean): void {
13
+ if (present === v) return
14
+ present = v
15
+ for (const fn of [...listeners]) {
16
+ try {
17
+ fn(v)
18
+ } catch {
19
+ // A listener must not stop the others.
20
+ }
21
+ }
22
+ }
23
+
24
+ export function hasUnattestedTransport(): boolean {
25
+ return present
26
+ }
27
+
28
+ /** Returns the unsubscribe function. */
29
+ export function onUnattestedTransportChange(fn: (present: boolean) => void): () => void {
30
+ listeners.add(fn)
31
+ return () => {
32
+ listeners.delete(fn)
33
+ }
34
+ }