@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,569 @@
1
+ /**
2
+ * Durable inbox (spec 6.8): the queue contract for transports where the app is not running when
3
+ * the page asks (iOS), and the processor that drives records through it.
4
+ *
5
+ * Lifecycle: `pending -> accepted -> claimed -> done`. The store is a dumb, sealed, atomic
6
+ * adapter (project 2 supplies an App Group one; `memoryInboxStore.ts` is the reference and runs
7
+ * the same contract suite). The processor owns the policy: size checks before reads, the
8
+ * `notAfter` clamp, acceptance in `createdAt` order, binding admission, and crash recovery.
9
+ *
10
+ * The claim is the at-most-once point. It is awaited, so it cannot be fused with the dispatcher's
11
+ * synchronous re-check; instead the dispatcher awaits `beforeCall` (the claim) and runs its
12
+ * re-check after it, immediately before the wallet call (6.6 step 8).
13
+ */
14
+ import { Hash, Utils } from '@bsv/sdk'
15
+ import type { BindingRegistry, CloseEvent } from './bindings'
16
+ import type { Dispatcher, Outcome } from './dispatcher'
17
+ import { connectionError, isConnectionError, type ConnectionError } from './protocol/connectionError'
18
+ import { isUuidV4, type InboxCloseEvent, type InboxRecord, type InboxResult } from './protocol/envelopes'
19
+ import { parseStrictJson } from './protocol/json'
20
+ import {
21
+ INBOX_CLOCK_SKEW_MS,
22
+ INBOX_MAX_VALIDITY_MS,
23
+ MAX_BRIDGE_REQUEST_BYTES,
24
+ MAX_IN_FLIGHT_BYTES,
25
+ MAX_IN_FLIGHT_TOTAL
26
+ } from './protocol/limits'
27
+ import type { Attestation } from './protocol/origin'
28
+ import type { BridgeSnapshot } from './runtime'
29
+
30
+ export type InboxState = 'pending' | 'accepted' | 'claimed' | 'done'
31
+
32
+ export interface InboxStat {
33
+ /** Size in bytes of the record as staged (plaintext). Stays known after the payload is deleted. */
34
+ size: number
35
+ state: InboxState
36
+ /** Boot id stamped by `claim`. */
37
+ claimBootId?: string
38
+ }
39
+
40
+ export type ClaimOutcome = 'claimed' | 'digest-mismatch' | 'not-accepted'
41
+
42
+ export type ResultRead =
43
+ /** No result has been written yet. */
44
+ | { kind: 'none' }
45
+ | { kind: 'result'; bytes: Uint8Array }
46
+ /** Acknowledged or past the retention window: the payload is gone, the id tombstone remains. */
47
+ | { kind: 'purged' }
48
+
49
+ /**
50
+ * The store adapter contract. Every method may be asynchronous; each is atomic. Records are
51
+ * immutable and ids are create-exclusive across every state, tombstones included.
52
+ */
53
+ export interface InboxStore {
54
+ /** Stages a record as `pending`. False when the id already exists in any state. */
55
+ create(id: string, bytes: Uint8Array): Promise<boolean>
56
+ /** Undefined for an unknown id. Never reads the payload. */
57
+ stat(id: string): Promise<InboxStat | undefined>
58
+ /** The immutable bytes, without changing state. Undefined once the arguments are deleted. */
59
+ read(id: string): Promise<Uint8Array | undefined>
60
+ /** `pending -> accepted`. False when the record is not pending. */
61
+ accept(id: string): Promise<boolean>
62
+ /** `accepted -> pending`: crash recovery for a record that was never dispatched. */
63
+ release(id: string): Promise<boolean>
64
+ /** Atomic `accepted -> claimed` for exactly one caller, and only if the bytes still hash to `digest`. */
65
+ claim(id: string, digest: string): Promise<ClaimOutcome>
66
+ /** Writes the result once, moves to `done` and deletes the arguments. False if one exists. */
67
+ writeResult(id: string, bytes: Uint8Array): Promise<boolean>
68
+ readResult(id: string): Promise<ResultRead>
69
+ /** Deletes the payload and result, never the id tombstone. */
70
+ ack(id: string): Promise<void>
71
+ writeEvent(e: InboxCloseEvent): Promise<void>
72
+ /**
73
+ * Close events with `closeSeq > seq`, sorted. `gap` is true when events the reader never saw were
74
+ * trimmed (`seq < evictedThrough`): it must then close every epoch it holds.
75
+ */
76
+ readEventsAfter(seq: number): Promise<{ events: InboxCloseEvent[]; gap: boolean }>
77
+ bootId(): string
78
+ /** Pending ids are oldest first by the record createdAt, stable for equal timestamps. */
79
+ list(state: InboxState): Promise<string[]>
80
+ }
81
+
82
+ /** Hex SHA-256 of the staged bytes: what `claim` compares. */
83
+ export function inboxDigest(bytes: Uint8Array): string {
84
+ return Utils.toHex(Hash.sha256(Array.from(bytes)))
85
+ }
86
+
87
+ const encodeJson = (v: unknown): Uint8Array => Uint8Array.from(Utils.toArray(JSON.stringify(v), 'utf8'))
88
+
89
+ export function encodeInboxResult(r: InboxResult): Uint8Array {
90
+ return encodeJson(r)
91
+ }
92
+
93
+ export function decodeInboxResult(bytes: Uint8Array): InboxResult | undefined {
94
+ try {
95
+ const v = parseStrictJson(Utils.toUTF8(Array.from(bytes))) as InboxResult
96
+ return v && v.v === 1 && typeof v.id === 'string' && typeof v.ok === 'boolean' ? v : undefined
97
+ } catch {
98
+ return undefined
99
+ }
100
+ }
101
+
102
+ /**
103
+ * What a reader (the extension) sees for an id: the stored result, or for a purged or
104
+ * acknowledged one `CONNECTION_CLOSED`, `unknown` (the call may have run and the answer is gone).
105
+ * Undefined while no result exists yet.
106
+ */
107
+ export async function resolveInboxResult(store: InboxStore, id: string): Promise<InboxResult | undefined> {
108
+ const r = await store.readResult(id)
109
+ if (r.kind === 'none') return undefined
110
+ if (r.kind === 'purged') {
111
+ return {
112
+ v: 1,
113
+ id,
114
+ ok: false,
115
+ error: connectionError('CONNECTION_CLOSED', 'The result is no longer available', 'unknown')
116
+ }
117
+ }
118
+ return decodeInboxResult(r.bytes)
119
+ }
120
+
121
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
122
+ const isStr = (v: unknown): v is string => typeof v === 'string'
123
+ const isTime = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v >= 0
124
+
125
+ /** Structural check of a staged record; the key must equal the id it was staged under. */
126
+ export function parseInboxRecord(bytes: Uint8Array, expectedId: string): InboxRecord | undefined {
127
+ let v: unknown
128
+ try {
129
+ v = parseStrictJson(Utils.toUTF8(Array.from(bytes)))
130
+ } catch {
131
+ return undefined
132
+ }
133
+ if (!isObj(v) || v.v !== 1 || !isUuidV4(v.id) || v.id !== expectedId) return undefined
134
+ if (v.kind !== 'invoke' && v.kind !== 'disconnect') return undefined
135
+ if (!isStr(v.epoch) || !isStr(v.instanceId) || !isStr(v.continuityKey) || !isStr(v.origin)) return undefined
136
+ if (!isStr(v.accountContext) || !isStr(v.walletRevision)) return undefined
137
+ if (!isTime(v.boundAt) || !isTime(v.createdAt) || !isTime(v.notAfter)) return undefined
138
+ if (v.kind === 'invoke' && !isStr(v.method)) return undefined
139
+ return v as unknown as InboxRecord
140
+ }
141
+
142
+ export interface InboxProcessorDeps {
143
+ store: InboxStore
144
+ dispatch: Dispatcher['dispatch']
145
+ now: () => number
146
+ bindings: Pick<BindingRegistry, 'admitImplicit' | 'resolve' | 'close'>
147
+ /** The registered transport this inbox belongs to; trust comes from it, not from the record (6.2). */
148
+ transport: { id: string; attestation: Attestation }
149
+ /** The runtime's current revision and context. Defaults to `getBridgeSnapshot`. */
150
+ snapshot?: () => Pick<BridgeSnapshot, 'walletRevision' | 'accountContext'> &
151
+ Partial<Pick<BridgeSnapshot, 'readiness'>>
152
+ /** Subscribes to snapshot changes (the wait for readiness). Defaults to the runtime's. */
153
+ onSnapshotChange?: (fn: () => void) => () => void
154
+ /** Subscribes to binding closes (the events outbox). Defaults to the runtime's `onBindingClosed`. */
155
+ onClosed?: (fn: (e: CloseEvent) => void) => () => void
156
+ /**
157
+ * The registered transport for an id: trust comes from the registration, never from what the
158
+ * caller of `createInboxProcessor` says (6.2). Defaults to the runtime's `getTransport`.
159
+ */
160
+ registeredTransport?: (id: string) => { attestation: Attestation } | undefined
161
+ }
162
+
163
+ export interface InboxProcessor {
164
+ /**
165
+ * Recovers after a restart (once), expires stale pending records, then accepts every pending
166
+ * record in `createdAt` order within the byte/count budget, starting independent work concurrently. Resolves when
167
+ * everything it started has settled; a record parked behind a sheet keeps it open, so callers
168
+ * that must not wait run `sweepExpired` on their timer instead.
169
+ */
170
+ processPending(): Promise<void>
171
+ /** Answers `CONNECTION_CLOSED`, `not-sent` for pending records past `notAfter`. Needs no readiness. */
172
+ sweepExpired(): Promise<void>
173
+ /** Crash recovery (6.8). Idempotent; `processPending` runs it first. */
174
+ recover(): Promise<void>
175
+ /** Resolves when every close event raised so far is durable in the store. Never rejects. */
176
+ flushEvents(): Promise<void>
177
+ /** Stops writing close events. The processor is meant to live as long as its transport. */
178
+ dispose(): void
179
+ }
180
+
181
+ function errorResult(id: string, error: ConnectionError): Uint8Array {
182
+ return encodeInboxResult({ v: 1, id, ok: false, error })
183
+ }
184
+
185
+ function outcomeResult(id: string, o: Outcome): Uint8Array {
186
+ if (o.ok) return encodeInboxResult({ v: 1, id, ok: true, result: o.result })
187
+ if ('walletError' in o) return encodeInboxResult({ v: 1, id, ok: false, error: o.walletError })
188
+ return errorResult(id, o.connectionError)
189
+ }
190
+
191
+ export function createInboxProcessor(deps: InboxProcessorDeps): InboxProcessor {
192
+ const { store, now, transport } = deps
193
+ const snapshot =
194
+ deps.snapshot ??
195
+ (() => {
196
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
197
+ return (require('./runtime') as typeof import('./runtime')).getBridgeSnapshot()
198
+ })
199
+ const registered =
200
+ deps.registeredTransport ??
201
+ ((id: string) => {
202
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
203
+ return (require('./runtime') as typeof import('./runtime')).getTransport(id)
204
+ })
205
+ const subscribeSnapshot =
206
+ deps.onSnapshotChange ??
207
+ ((fn: () => void) => {
208
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
209
+ return (require('./runtime') as typeof import('./runtime')).onSnapshotChange(fn)
210
+ })
211
+ const subscribeClosed =
212
+ deps.onClosed ??
213
+ ((fn: (e: CloseEvent) => void) => {
214
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
215
+ return (require('./runtime') as typeof import('./runtime')).onBindingClosed(fn)
216
+ })
217
+ let recovered: Promise<void> | undefined
218
+ let draining: Promise<void> | undefined
219
+ let wakeDrain: (() => void) | undefined
220
+ let drainRequested = false
221
+ let disposed = false
222
+ const resultRetries = new Set<() => void>()
223
+ const finishing = new Map<string, Promise<void>>()
224
+ let executionTurn: Promise<void> = Promise.resolve()
225
+
226
+ async function reserveExecution(): Promise<() => void> {
227
+ const previous = executionTurn
228
+ let release!: () => void
229
+ executionTurn = new Promise<void>(resolve => { release = resolve })
230
+ await previous
231
+ return release
232
+ }
233
+
234
+ // Every close of one of this transport's bindings goes to the events outbox, in close order
235
+ // (6.7). The writes are chained, and `handle` waits for the chain before it admits anything, so
236
+ // a replacement binding never gets ahead of the event for the one it replaces.
237
+ let eventWrites: Promise<void> = Promise.resolve()
238
+ const unsubscribeClosed = subscribeClosed(e => {
239
+ if (e.transportId !== transport.id) return
240
+ const event: InboxCloseEvent = {
241
+ v: 1,
242
+ closeSeq: e.closeSeq,
243
+ instanceId: e.instanceId,
244
+ epoch: e.epoch,
245
+ reason: e.reason === 'disconnected' ? 'lost' : e.reason,
246
+ ...(e.notifyPage ? {} : { notifyPage: false as const })
247
+ }
248
+ eventWrites = eventWrites
249
+ .then(() => store.writeEvent(event))
250
+ .catch(err => console.warn('[bridge] inbox close event write failed', err))
251
+ })
252
+
253
+ /**
254
+ * Parks until the runtime is `ready` (spec 6.8): while it is `building` or `blocked` the
255
+ * snapshot's account context is empty, and admitting against it would tombstone every epoch
256
+ * bound earlier as `account-changed`. Undefined when there is no wallet at all.
257
+ */
258
+ async function readySnapshot() {
259
+ for (;;) {
260
+ const snap = snapshot()
261
+ if (snap.readiness === undefined || snap.readiness === 'ready') return snap
262
+ if (snap.readiness === 'none') return undefined
263
+ await new Promise<void>(resolve => {
264
+ const off = subscribeSnapshot(() => {
265
+ off()
266
+ resolve()
267
+ })
268
+ })
269
+ }
270
+ }
271
+
272
+ function finish(id: string, bytes: Uint8Array): Promise<void> {
273
+ const existing = finishing.get(id)
274
+ if (existing) return existing
275
+ const task = (async () => {
276
+ let oversized = false
277
+ while (!disposed) {
278
+ try {
279
+ await store.writeResult(id, bytes)
280
+ return
281
+ } catch (e) {
282
+ const code = isObj(e) ? e.code : undefined
283
+ if (code === 'ERR_RESULT_TOO_LARGE' && !oversized) {
284
+ oversized = true
285
+ bytes = errorResult(id, connectionError('RESOURCE_LIMIT', 'Response too large', 'unknown'))
286
+ continue
287
+ }
288
+ if (code !== 'ERR_RESOURCE_LIMIT') {
289
+ console.warn('[bridge] inbox result write failed', e)
290
+ return
291
+ }
292
+ // Keep the exact outcome and its drain slot until storage is reclaimed. Native
293
+ // Wallet execution stays serialized through finish, retaining at most one 5 MiB
294
+ // response plus small probe/admission errors. JS objects add representation overhead.
295
+ // Duplicate expiry sweeps share this task; no claimed call is dispatched again.
296
+ await new Promise<void>(resolve => {
297
+ const done = () => {
298
+ clearTimeout(timer)
299
+ resultRetries.delete(done)
300
+ resolve()
301
+ }
302
+ const timer = setTimeout(done, 1000)
303
+ resultRetries.add(done)
304
+ if (disposed) done()
305
+ })
306
+ }
307
+ }
308
+ })().finally(() => finishing.delete(id))
309
+ finishing.set(id, task)
310
+ return task
311
+ }
312
+
313
+ async function recoverOnce() {
314
+ const boot = store.bootId()
315
+ for (const id of await store.list('claimed')) {
316
+ const st = await store.stat(id)
317
+ if (!st || st.state !== 'claimed' || st.claimBootId === boot) continue
318
+ // Claimed by a process that died: the call may have run, so it is never re-dispatched.
319
+ await finish(
320
+ id,
321
+ errorResult(id, connectionError('CONNECTION_CLOSED', 'The wallet restarted during the call', 'unknown'))
322
+ )
323
+ }
324
+ // Accepted only: the app took responsibility but nothing was dispatched.
325
+ for (const id of await store.list('accepted')) await store.release(id)
326
+ }
327
+
328
+ /** Reads a pending record after the size check; refuses it with a result when it cannot be used. */
329
+ async function load(id: string): Promise<{ record: InboxRecord; bytes: Uint8Array; size: number } | undefined> {
330
+ const st = await store.stat(id)
331
+ if (!st || st.state !== 'pending') return undefined
332
+ if (st.size > MAX_BRIDGE_REQUEST_BYTES) {
333
+ await finish(id, errorResult(id, connectionError('RESOURCE_LIMIT', 'Request too large', 'not-sent')))
334
+ return undefined
335
+ }
336
+ const bytes = await store.read(id)
337
+ if (!bytes) return undefined
338
+ const record = parseInboxRecord(bytes, id)
339
+ if (!record) {
340
+ await finish(id, errorResult(id, connectionError('PROTOCOL_ERROR', 'Malformed inbox record', 'not-sent')))
341
+ return undefined
342
+ }
343
+ return { record, bytes, size: st.size }
344
+ }
345
+
346
+ const effectiveNotAfter = (r: InboxRecord) => Math.min(r.notAfter, r.createdAt + INBOX_MAX_VALIDITY_MS)
347
+
348
+ /** Stage-time checks that apply to a pending record. True when it may be accepted. */
349
+ async function admissible(record: InboxRecord): Promise<boolean> {
350
+ const t = now()
351
+ if (record.createdAt > t + INBOX_CLOCK_SKEW_MS) {
352
+ await finish(
353
+ record.id,
354
+ errorResult(
355
+ record.id,
356
+ connectionError('PROTOCOL_ERROR', 'Record is dated in the future', 'not-sent', { epoch: record.epoch })
357
+ )
358
+ )
359
+ return false
360
+ }
361
+ if (t > effectiveNotAfter(record)) {
362
+ await finish(
363
+ record.id,
364
+ errorResult(
365
+ record.id,
366
+ connectionError('CONNECTION_CLOSED', 'The request expired before it was handled', 'not-sent', {
367
+ epoch: record.epoch
368
+ })
369
+ )
370
+ )
371
+ return false
372
+ }
373
+ return true
374
+ }
375
+
376
+ async function handle(id: string, record: InboxRecord, bytes: Uint8Array, size: number) {
377
+ let snap = await readySnapshot()
378
+ // Closes that happened while this record waited are in the outbox before it is admitted.
379
+ await eventWrites
380
+ if (snap !== undefined) snap = await readySnapshot()
381
+ if (disposed) return
382
+ if (snap === undefined) {
383
+ await finish(
384
+ id,
385
+ errorResult(
386
+ id,
387
+ connectionError('CONFIGURATION_ERROR', 'No wallet is available', 'not-sent', { epoch: record.epoch })
388
+ )
389
+ )
390
+ return
391
+ }
392
+ const reg = registered(transport.id)
393
+ if (reg !== undefined && reg.attestation !== transport.attestation) {
394
+ await finish(
395
+ id,
396
+ errorResult(
397
+ id,
398
+ connectionError('PROTOCOL_ERROR', 'Attestation does not match the transport', 'not-sent', {
399
+ epoch: record.epoch
400
+ })
401
+ )
402
+ )
403
+ return
404
+ }
405
+ const admitted = deps.bindings.admitImplicit(
406
+ {
407
+ epoch: record.epoch,
408
+ transportId: transport.id,
409
+ attestation: reg?.attestation ?? transport.attestation,
410
+ origin: record.origin,
411
+ instanceId: record.instanceId,
412
+ continuityKey: record.continuityKey,
413
+ accountContext: record.accountContext,
414
+ walletRevision: record.walletRevision,
415
+ boundAt: record.boundAt
416
+ },
417
+ { walletRevision: snap.walletRevision, accountContext: snap.accountContext }
418
+ )
419
+ if (isConnectionError(admitted)) {
420
+ await finish(id, errorResult(id, admitted))
421
+ return
422
+ }
423
+ if (record.kind === 'disconnect') {
424
+ const claim = await store.claim(id, inboxDigest(bytes))
425
+ if (claim !== 'claimed') return
426
+ deps.bindings.close(record.epoch, 'disconnected')
427
+ await finish(id, encodeInboxResult({ v: 1, id, ok: true, result: {} }))
428
+ return
429
+ }
430
+ let claimed = false
431
+ let dispatchSettled = false
432
+ let releaseExecution = () => {}
433
+ try {
434
+ const outcome = await deps
435
+ .dispatch({
436
+ transport: transport.id,
437
+ request: {
438
+ epoch: record.epoch,
439
+ instanceId: record.instanceId,
440
+ continuityKey: record.continuityKey,
441
+ origin: record.origin,
442
+ accountContext: record.accountContext,
443
+ method: record.method as string,
444
+ args: record.args,
445
+ sizeBytes: size,
446
+ beforeCall: async () => {
447
+ // Approval/readiness waits remain concurrent; only execution and result persistence
448
+ // serialize. A dispatcher may stop waiting on this promise when its binding closes.
449
+ const release = await reserveExecution()
450
+ if (disposed || dispatchSettled) {
451
+ release()
452
+ throw connectionError('CONNECTION_CLOSED', 'The bridge stopped waiting', 'not-sent')
453
+ }
454
+ releaseExecution = release
455
+ const c = await store.claim(id, inboxDigest(bytes))
456
+ if (c === 'claimed') {
457
+ claimed = true
458
+ return
459
+ }
460
+ throw connectionError(
461
+ 'PROTOCOL_ERROR',
462
+ c === 'digest-mismatch' ? 'The record changed after it was read' : 'The record is no longer waiting',
463
+ 'not-sent',
464
+ { epoch: record.epoch }
465
+ )
466
+ }
467
+ }
468
+ })
469
+ .catch(
470
+ (e): Outcome => ({
471
+ ok: false,
472
+ connectionError: connectionError(
473
+ 'CONFIGURATION_ERROR',
474
+ 'The wallet bridge failed',
475
+ claimed ? 'unknown' : 'not-sent',
476
+ {
477
+ epoch: record.epoch
478
+ }
479
+ )
480
+ })
481
+ )
482
+ dispatchSettled = true
483
+ await finish(id, outcomeResult(id, outcome))
484
+ } finally {
485
+ dispatchSettled = true
486
+ releaseExecution()
487
+ }
488
+ }
489
+
490
+ async function sweepExpired() {
491
+ for (const id of await store.list('pending')) {
492
+ const loaded = await load(id)
493
+ if (!loaded) continue
494
+ await admissible(loaded.record)
495
+ }
496
+ }
497
+
498
+ return {
499
+ recover() {
500
+ recovered ??= recoverOnce().catch(e => {
501
+ recovered = undefined
502
+ throw e
503
+ })
504
+ return recovered
505
+ },
506
+
507
+ sweepExpired,
508
+
509
+ flushEvents: () => eventWrites,
510
+
511
+ dispose() {
512
+ disposed = true
513
+ for (const done of resultRetries) done()
514
+ unsubscribeClosed()
515
+ },
516
+
517
+ processPending() {
518
+ if (disposed) return Promise.resolve()
519
+ // One budget across nudges; new arrivals can still join while an earlier approval waits.
520
+ if (draining) {
521
+ drainRequested = true
522
+ wakeDrain?.()
523
+ return draining
524
+ }
525
+ draining = (async () => {
526
+ try {
527
+ await this.recover()
528
+ const running = new Set<Promise<void>>()
529
+ let loadedBytes = 0
530
+ for (;;) {
531
+ drainRequested = false
532
+ const nudged = new Promise<void>(resolve => { wakeDrain = resolve })
533
+ for (const id of await store.list('pending')) {
534
+ if (disposed) break
535
+ const stat = await store.stat(id)
536
+ if (!stat || stat.state !== 'pending') continue
537
+ const size = Math.max(0, stat.size)
538
+ while (running.size > 0 && (running.size >= MAX_IN_FLIGHT_TOTAL || loadedBytes + size > MAX_IN_FLIGHT_BYTES)) {
539
+ await Promise.race(running)
540
+ }
541
+ const loaded = await load(id)
542
+ if (!loaded || !(await admissible(loaded.record)) || disposed || !(await store.accept(id))) continue
543
+ loadedBytes += loaded.size
544
+ const task = handle(id, loaded.record, loaded.bytes, loaded.size)
545
+ .catch(e => {
546
+ console.warn('[bridge] inbox record failed', e)
547
+ })
548
+ .finally(() => {
549
+ loadedBytes -= loaded.size
550
+ running.delete(task)
551
+ })
552
+ running.add(task)
553
+ }
554
+ if (running.size === 0) {
555
+ if (drainRequested) continue
556
+ break
557
+ }
558
+ await Promise.race([nudged, ...running])
559
+ }
560
+ } finally {
561
+ draining = undefined
562
+ wakeDrain = undefined
563
+ drainRequested = false
564
+ }
565
+ })()
566
+ return draining
567
+ }
568
+ }
569
+ }
@@ -0,0 +1,48 @@
1
+ /** Public API of the browser bridge core (spec 6.9). Transports and hosts import from here. */
2
+ export { BrowserBridgeProvider } from './BrowserBridgeProvider'
3
+ export {
4
+ DEFAULT_BASE_VERSION,
5
+ getBindingRegistry,
6
+ getBridgeSnapshot,
7
+ getPermissionPolicy,
8
+ getTransport,
9
+ initBridgeRuntime,
10
+ isBridgeHostAttached,
11
+ onBindingClosed,
12
+ listConnectedSites,
13
+ notifyPromptRaised,
14
+ onConnectedSitesChange,
15
+ onSnapshotChange,
16
+ registerTransport,
17
+ revokeSite,
18
+ setPermissionPolicy,
19
+ type AttentionReason,
20
+ type BridgeReadiness,
21
+ type BridgeSnapshot,
22
+ type TransportHandle,
23
+ type TransportRegistration
24
+ } from './runtime'
25
+ export type { Binding, CloseEvent } from './bindings'
26
+ export type { ConnectionError } from './protocol/connectionError'
27
+ export { setConsentSheetSource, type ConsentSheetSource } from './consentSheetSource'
28
+
29
+ // The inbox transport API (spec 6.15 item 1): what a cross-process transport (project 2) drives.
30
+ export { createInboxProcessor, inboxDigest, resolveInboxResult, type InboxProcessor, type InboxStore } from './inbox'
31
+ export { createMemoryInboxStore } from './memoryInboxStore'
32
+ export { dispatch, type Dispatcher, type Outcome } from './dispatcher'
33
+ // The session teardown registry lives with the wallet context; transports reset their state from it.
34
+ export { registerSessionTeardown, type TeardownReason } from '../context/sessionTeardown'
35
+
36
+ // The pure protocol modules the Safari extension bundles. No app imports (bundleSafe.test.ts).
37
+ export * from './protocol/constants'
38
+ export * from './protocol/limits'
39
+ export * from './protocol/base64url'
40
+ export * from './protocol/json'
41
+ export * from './protocol/methods'
42
+ export * from './protocol/connectionError'
43
+ export * from './protocol/envelopes'
44
+ export * from './protocol/descriptor'
45
+ export * from './protocol/origin'
46
+
47
+ // The pure loopback HTTP semantics for the Android kit (spec: Android design 6.2, 6.6).
48
+ export * as loopback from './loopback'
@@ -0,0 +1,57 @@
1
+ /** CORS and base headers for loopback responses (spec 6.6.1). Never credentials, wildcard or null. */
2
+
3
+ export type CorsKind = 'public' | 'binding'
4
+
5
+ /** On every response, errors included. `Content-Length` and `Connection: close` are added by the writer. */
6
+ export const BASE_HEADERS: readonly [string, string][] = Object.freeze([
7
+ ['Cache-Control', 'no-store'],
8
+ ['Vary', 'Origin'],
9
+ ['X-Content-Type-Options', 'nosniff']
10
+ ] as [string, string][])
11
+
12
+ const ALLOWED_REQUEST_HEADERS = [
13
+ 'Content-Type',
14
+ 'BRC-185-Epoch',
15
+ 'BRC-185-Instance',
16
+ 'BRC-185-Key',
17
+ 'BRC-185-Android-Binding'
18
+ ]
19
+
20
+ function assertOrigin(origin: string): void {
21
+ if (typeof origin !== 'string' || origin === '' || origin === '*' || origin === 'null') {
22
+ throw new Error('CORS origin must be a concrete origin')
23
+ }
24
+ }
25
+
26
+ /**
27
+ * `public`: discovery, connect, preflight (exposes the describe/connect ack). `binding`: RPC and DELETE for the live
28
+ * binding's origin (exposes the reconnect token). Callers send no CORS headers at all for any other origin.
29
+ */
30
+ export function corsHeaders(opts: { origin: string; kind: CorsKind }): [string, string][] {
31
+ assertOrigin(opts.origin)
32
+ return [
33
+ ['Access-Control-Allow-Origin', opts.origin],
34
+ ['Access-Control-Expose-Headers', opts.kind === 'public' ? 'BRC-185-Android-Ack' : 'BRC-185-Reconnect-Token']
35
+ ]
36
+ }
37
+
38
+ export function preflightHeaders(req: {
39
+ origin: string
40
+ requestHeaders?: string
41
+ privateNetwork?: boolean
42
+ }): [string, string][] {
43
+ assertOrigin(req.origin)
44
+ const asked = (req.requestHeaders ?? '')
45
+ .split(',')
46
+ .map(s => s.trim().toLowerCase())
47
+ .filter(s => s !== '')
48
+ const allow = ALLOWED_REQUEST_HEADERS.filter(h => asked.includes(h.toLowerCase()))
49
+ const out: [string, string][] = [
50
+ ['Access-Control-Allow-Origin', req.origin],
51
+ ['Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS']
52
+ ]
53
+ if (allow.length > 0) out.push(['Access-Control-Allow-Headers', allow.join(', ')])
54
+ if (req.privateNetwork === true) out.push(['Access-Control-Allow-Private-Network', 'true'])
55
+ for (const h of BASE_HEADERS) out.push([h[0], h[1]])
56
+ return out
57
+ }
@@ -0,0 +1,11 @@
1
+ /** The descriptor endpoints a loopback wallet advertises (spec 6.2.1). Same list on every response. */
2
+ import type { DescriptorEndpoint } from '../protocol/descriptor'
3
+ import type { LoopbackBound } from './hostCheck'
4
+
5
+ export function loopbackEndpoints(b: LoopbackBound): DescriptorEndpoint[] {
6
+ const out: DescriptorEndpoint[] = []
7
+ if (b.ipv4) out.push({ id: 'json-ipv4', type: 'http-json', address: `http://127.0.0.1:${b.port}` })
8
+ if (b.ipv6) out.push({ id: 'json-ipv6', type: 'http-json', address: `http://[::1]:${b.port}` })
9
+ if (b.ipv4 && b.ipv6) out.push({ id: 'json-localhost', type: 'http-json', address: `http://localhost:${b.port}` })
10
+ return out
11
+ }