@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,464 @@
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 { INBOX_CLOCK_SKEW_MS, INBOX_MAX_VALIDITY_MS, MAX_BRIDGE_REQUEST_BYTES } from './protocol/limits'
21
+ import type { Attestation } from './protocol/origin'
22
+ import type { BridgeSnapshot } from './runtime'
23
+
24
+ export type InboxState = 'pending' | 'accepted' | 'claimed' | 'done'
25
+
26
+ export interface InboxStat {
27
+ /** Size in bytes of the record as staged (plaintext). Stays known after the payload is deleted. */
28
+ size: number
29
+ state: InboxState
30
+ /** Boot id stamped by `claim`. */
31
+ claimBootId?: string
32
+ }
33
+
34
+ export type ClaimOutcome = 'claimed' | 'digest-mismatch' | 'not-accepted'
35
+
36
+ export type ResultRead =
37
+ /** No result has been written yet. */
38
+ | { kind: 'none' }
39
+ | { kind: 'result'; bytes: Uint8Array }
40
+ /** Acknowledged or past the retention window: the payload is gone, the id tombstone remains. */
41
+ | { kind: 'purged' }
42
+
43
+ /**
44
+ * The store adapter contract. Every method may be asynchronous; each is atomic. Records are
45
+ * immutable and ids are create-exclusive across every state, tombstones included.
46
+ */
47
+ export interface InboxStore {
48
+ /** Stages a record as `pending`. False when the id already exists in any state. */
49
+ create(id: string, bytes: Uint8Array): Promise<boolean>
50
+ /** Undefined for an unknown id. Never reads the payload. */
51
+ stat(id: string): Promise<InboxStat | undefined>
52
+ /** The immutable bytes, without changing state. Undefined once the arguments are deleted. */
53
+ read(id: string): Promise<Uint8Array | undefined>
54
+ /** `pending -> accepted`. False when the record is not pending. */
55
+ accept(id: string): Promise<boolean>
56
+ /** `accepted -> pending`: crash recovery for a record that was never dispatched. */
57
+ release(id: string): Promise<boolean>
58
+ /** Atomic `accepted -> claimed` for exactly one caller, and only if the bytes still hash to `digest`. */
59
+ claim(id: string, digest: string): Promise<ClaimOutcome>
60
+ /** Writes the result once, moves to `done` and deletes the arguments. False if one exists. */
61
+ writeResult(id: string, bytes: Uint8Array): Promise<boolean>
62
+ readResult(id: string): Promise<ResultRead>
63
+ /** Deletes the payload and result, never the id tombstone. */
64
+ ack(id: string): Promise<void>
65
+ writeEvent(e: InboxCloseEvent): Promise<void>
66
+ /**
67
+ * Close events with `closeSeq > seq`, sorted. `gap` is true when events the reader never saw were
68
+ * trimmed (`seq < evictedThrough`): it must then close every epoch it holds.
69
+ */
70
+ readEventsAfter(seq: number): Promise<{ events: InboxCloseEvent[]; gap: boolean }>
71
+ bootId(): string
72
+ list(state: InboxState): Promise<string[]>
73
+ }
74
+
75
+ /** Hex SHA-256 of the staged bytes: what `claim` compares. */
76
+ export function inboxDigest(bytes: Uint8Array): string {
77
+ return Utils.toHex(Hash.sha256(Array.from(bytes)))
78
+ }
79
+
80
+ const encodeJson = (v: unknown): Uint8Array => Uint8Array.from(Utils.toArray(JSON.stringify(v), 'utf8'))
81
+
82
+ export function encodeInboxResult(r: InboxResult): Uint8Array {
83
+ return encodeJson(r)
84
+ }
85
+
86
+ export function decodeInboxResult(bytes: Uint8Array): InboxResult | undefined {
87
+ try {
88
+ const v = parseStrictJson(Utils.toUTF8(Array.from(bytes))) as InboxResult
89
+ return v && v.v === 1 && typeof v.id === 'string' && typeof v.ok === 'boolean' ? v : undefined
90
+ } catch {
91
+ return undefined
92
+ }
93
+ }
94
+
95
+ /**
96
+ * What a reader (the extension) sees for an id: the stored result, or for a purged or
97
+ * acknowledged one `CONNECTION_CLOSED`, `unknown` (the call may have run and the answer is gone).
98
+ * Undefined while no result exists yet.
99
+ */
100
+ export async function resolveInboxResult(store: InboxStore, id: string): Promise<InboxResult | undefined> {
101
+ const r = await store.readResult(id)
102
+ if (r.kind === 'none') return undefined
103
+ if (r.kind === 'purged') {
104
+ return {
105
+ v: 1,
106
+ id,
107
+ ok: false,
108
+ error: connectionError('CONNECTION_CLOSED', 'The result is no longer available', 'unknown')
109
+ }
110
+ }
111
+ return decodeInboxResult(r.bytes)
112
+ }
113
+
114
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
115
+ const isStr = (v: unknown): v is string => typeof v === 'string'
116
+ const isTime = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v >= 0
117
+
118
+ /** Structural check of a staged record; the key must equal the id it was staged under. */
119
+ export function parseInboxRecord(bytes: Uint8Array, expectedId: string): InboxRecord | undefined {
120
+ let v: unknown
121
+ try {
122
+ v = parseStrictJson(Utils.toUTF8(Array.from(bytes)))
123
+ } catch {
124
+ return undefined
125
+ }
126
+ if (!isObj(v) || v.v !== 1 || !isUuidV4(v.id) || v.id !== expectedId) return undefined
127
+ if (v.kind !== 'invoke' && v.kind !== 'disconnect') return undefined
128
+ if (!isStr(v.epoch) || !isStr(v.instanceId) || !isStr(v.continuityKey) || !isStr(v.origin)) return undefined
129
+ if (!isStr(v.accountContext) || !isStr(v.walletRevision)) return undefined
130
+ if (!isTime(v.boundAt) || !isTime(v.createdAt) || !isTime(v.notAfter)) return undefined
131
+ if (v.kind === 'invoke' && !isStr(v.method)) return undefined
132
+ return v as unknown as InboxRecord
133
+ }
134
+
135
+ export interface InboxProcessorDeps {
136
+ store: InboxStore
137
+ dispatch: Dispatcher['dispatch']
138
+ now: () => number
139
+ bindings: Pick<BindingRegistry, 'admitImplicit' | 'resolve' | 'close'>
140
+ /** The registered transport this inbox belongs to; trust comes from it, not from the record (6.2). */
141
+ transport: { id: string; attestation: Attestation }
142
+ /** The runtime's current revision and context. Defaults to `getBridgeSnapshot`. */
143
+ snapshot?: () => Pick<BridgeSnapshot, 'walletRevision' | 'accountContext'> &
144
+ Partial<Pick<BridgeSnapshot, 'readiness'>>
145
+ /** Subscribes to snapshot changes (the wait for readiness). Defaults to the runtime's. */
146
+ onSnapshotChange?: (fn: () => void) => () => void
147
+ /** Subscribes to binding closes (the events outbox). Defaults to the runtime's `onBindingClosed`. */
148
+ onClosed?: (fn: (e: CloseEvent) => void) => () => void
149
+ /**
150
+ * The registered transport for an id: trust comes from the registration, never from what the
151
+ * caller of `createInboxProcessor` says (6.2). Defaults to the runtime's `getTransport`.
152
+ */
153
+ registeredTransport?: (id: string) => { attestation: Attestation } | undefined
154
+ }
155
+
156
+ export interface InboxProcessor {
157
+ /**
158
+ * Recovers after a restart (once), expires stale pending records, then accepts every pending
159
+ * record in `createdAt` order and starts it without waiting for the earlier ones. Resolves when
160
+ * everything it started has settled; a record parked behind a sheet keeps it open, so callers
161
+ * that must not wait run `sweepExpired` on their timer instead.
162
+ */
163
+ processPending(): Promise<void>
164
+ /** Answers `CONNECTION_CLOSED`, `not-sent` for pending records past `notAfter`. Needs no readiness. */
165
+ sweepExpired(): Promise<void>
166
+ /** Crash recovery (6.8). Idempotent; `processPending` runs it first. */
167
+ recover(): Promise<void>
168
+ /** Resolves when every close event raised so far is durable in the store. Never rejects. */
169
+ flushEvents(): Promise<void>
170
+ /** Stops writing close events. The processor is meant to live as long as its transport. */
171
+ dispose(): void
172
+ }
173
+
174
+ function errorResult(id: string, error: ConnectionError): Uint8Array {
175
+ return encodeInboxResult({ v: 1, id, ok: false, error })
176
+ }
177
+
178
+ function outcomeResult(id: string, o: Outcome): Uint8Array {
179
+ if (o.ok) return encodeInboxResult({ v: 1, id, ok: true, result: o.result })
180
+ if ('walletError' in o) return encodeInboxResult({ v: 1, id, ok: false, error: o.walletError })
181
+ return errorResult(id, o.connectionError)
182
+ }
183
+
184
+ export function createInboxProcessor(deps: InboxProcessorDeps): InboxProcessor {
185
+ const { store, now, transport } = deps
186
+ const snapshot =
187
+ deps.snapshot ??
188
+ (() => {
189
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
190
+ return (require('./runtime') as typeof import('./runtime')).getBridgeSnapshot()
191
+ })
192
+ const registered =
193
+ deps.registeredTransport ??
194
+ ((id: string) => {
195
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
196
+ return (require('./runtime') as typeof import('./runtime')).getTransport(id)
197
+ })
198
+ const subscribeSnapshot =
199
+ deps.onSnapshotChange ??
200
+ ((fn: () => void) => {
201
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
202
+ return (require('./runtime') as typeof import('./runtime')).onSnapshotChange(fn)
203
+ })
204
+ const subscribeClosed =
205
+ deps.onClosed ??
206
+ ((fn: (e: CloseEvent) => void) => {
207
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
208
+ return (require('./runtime') as typeof import('./runtime')).onBindingClosed(fn)
209
+ })
210
+ let recovered: Promise<void> | undefined
211
+
212
+ // Every close of one of this transport's bindings goes to the events outbox, in close order
213
+ // (6.7). The writes are chained, and `handle` waits for the chain before it admits anything, so
214
+ // a replacement binding never gets ahead of the event for the one it replaces.
215
+ let eventWrites: Promise<void> = Promise.resolve()
216
+ const unsubscribeClosed = subscribeClosed(e => {
217
+ if (e.transportId !== transport.id) return
218
+ const event: InboxCloseEvent = {
219
+ v: 1,
220
+ closeSeq: e.closeSeq,
221
+ instanceId: e.instanceId,
222
+ epoch: e.epoch,
223
+ reason: e.reason === 'disconnected' ? 'lost' : e.reason,
224
+ ...(e.notifyPage ? {} : { notifyPage: false as const })
225
+ }
226
+ eventWrites = eventWrites
227
+ .then(() => store.writeEvent(event))
228
+ .catch(err => console.warn('[bridge] inbox close event write failed', err))
229
+ })
230
+
231
+ /**
232
+ * Parks until the runtime is `ready` (spec 6.8): while it is `building` or `blocked` the
233
+ * snapshot's account context is empty, and admitting against it would tombstone every epoch
234
+ * bound earlier as `account-changed`. Undefined when there is no wallet at all.
235
+ */
236
+ async function readySnapshot() {
237
+ for (;;) {
238
+ const snap = snapshot()
239
+ if (snap.readiness === undefined || snap.readiness === 'ready') return snap
240
+ if (snap.readiness === 'none') return undefined
241
+ await new Promise<void>(resolve => {
242
+ const off = subscribeSnapshot(() => {
243
+ off()
244
+ resolve()
245
+ })
246
+ })
247
+ }
248
+ }
249
+
250
+ async function finish(id: string, bytes: Uint8Array) {
251
+ try {
252
+ await store.writeResult(id, bytes)
253
+ } catch (e) {
254
+ console.warn('[bridge] inbox result write failed', e)
255
+ }
256
+ }
257
+
258
+ async function recoverOnce() {
259
+ const boot = store.bootId()
260
+ for (const id of await store.list('claimed')) {
261
+ const st = await store.stat(id)
262
+ if (!st || st.state !== 'claimed' || st.claimBootId === boot) continue
263
+ // Claimed by a process that died: the call may have run, so it is never re-dispatched.
264
+ await finish(
265
+ id,
266
+ errorResult(id, connectionError('CONNECTION_CLOSED', 'The wallet restarted during the call', 'unknown'))
267
+ )
268
+ }
269
+ // Accepted only: the app took responsibility but nothing was dispatched.
270
+ for (const id of await store.list('accepted')) await store.release(id)
271
+ }
272
+
273
+ /** Reads a pending record after the size check; refuses it with a result when it cannot be used. */
274
+ async function load(id: string): Promise<{ record: InboxRecord; bytes: Uint8Array; size: number } | undefined> {
275
+ const st = await store.stat(id)
276
+ if (!st || st.state !== 'pending') return undefined
277
+ if (st.size > MAX_BRIDGE_REQUEST_BYTES) {
278
+ await finish(id, errorResult(id, connectionError('RESOURCE_LIMIT', 'Request too large', 'not-sent')))
279
+ return undefined
280
+ }
281
+ const bytes = await store.read(id)
282
+ if (!bytes) return undefined
283
+ const record = parseInboxRecord(bytes, id)
284
+ if (!record) {
285
+ await finish(id, errorResult(id, connectionError('PROTOCOL_ERROR', 'Malformed inbox record', 'not-sent')))
286
+ return undefined
287
+ }
288
+ return { record, bytes, size: st.size }
289
+ }
290
+
291
+ const effectiveNotAfter = (r: InboxRecord) => Math.min(r.notAfter, r.createdAt + INBOX_MAX_VALIDITY_MS)
292
+
293
+ /** Stage-time checks that apply to a pending record. True when it may be accepted. */
294
+ async function admissible(record: InboxRecord): Promise<boolean> {
295
+ const t = now()
296
+ if (record.createdAt > t + INBOX_CLOCK_SKEW_MS) {
297
+ await finish(
298
+ record.id,
299
+ errorResult(
300
+ record.id,
301
+ connectionError('PROTOCOL_ERROR', 'Record is dated in the future', 'not-sent', { epoch: record.epoch })
302
+ )
303
+ )
304
+ return false
305
+ }
306
+ if (t > effectiveNotAfter(record)) {
307
+ await finish(
308
+ record.id,
309
+ errorResult(
310
+ record.id,
311
+ connectionError('CONNECTION_CLOSED', 'The request expired before it was handled', 'not-sent', {
312
+ epoch: record.epoch
313
+ })
314
+ )
315
+ )
316
+ return false
317
+ }
318
+ return true
319
+ }
320
+
321
+ async function handle(id: string, record: InboxRecord, bytes: Uint8Array, size: number) {
322
+ let snap = await readySnapshot()
323
+ // Closes that happened while this record waited are in the outbox before it is admitted.
324
+ await eventWrites
325
+ if (snap !== undefined) snap = await readySnapshot()
326
+ if (snap === undefined) {
327
+ await finish(
328
+ id,
329
+ errorResult(
330
+ id,
331
+ connectionError('CONFIGURATION_ERROR', 'No wallet is available', 'not-sent', { epoch: record.epoch })
332
+ )
333
+ )
334
+ return
335
+ }
336
+ const reg = registered(transport.id)
337
+ if (reg !== undefined && reg.attestation !== transport.attestation) {
338
+ await finish(
339
+ id,
340
+ errorResult(
341
+ id,
342
+ connectionError('PROTOCOL_ERROR', 'Attestation does not match the transport', 'not-sent', {
343
+ epoch: record.epoch
344
+ })
345
+ )
346
+ )
347
+ return
348
+ }
349
+ const admitted = deps.bindings.admitImplicit(
350
+ {
351
+ epoch: record.epoch,
352
+ transportId: transport.id,
353
+ attestation: reg?.attestation ?? transport.attestation,
354
+ origin: record.origin,
355
+ instanceId: record.instanceId,
356
+ continuityKey: record.continuityKey,
357
+ accountContext: record.accountContext,
358
+ walletRevision: record.walletRevision,
359
+ boundAt: record.boundAt
360
+ },
361
+ { walletRevision: snap.walletRevision, accountContext: snap.accountContext }
362
+ )
363
+ if (isConnectionError(admitted)) {
364
+ await finish(id, errorResult(id, admitted))
365
+ return
366
+ }
367
+ if (record.kind === 'disconnect') {
368
+ const claim = await store.claim(id, inboxDigest(bytes))
369
+ if (claim !== 'claimed') return
370
+ deps.bindings.close(record.epoch, 'disconnected')
371
+ await finish(id, encodeInboxResult({ v: 1, id, ok: true, result: {} }))
372
+ return
373
+ }
374
+ let claimed = false
375
+ const outcome = await deps
376
+ .dispatch({
377
+ transport: transport.id,
378
+ request: {
379
+ epoch: record.epoch,
380
+ instanceId: record.instanceId,
381
+ continuityKey: record.continuityKey,
382
+ origin: record.origin,
383
+ accountContext: record.accountContext,
384
+ method: record.method as string,
385
+ args: record.args,
386
+ sizeBytes: size,
387
+ beforeCall: async () => {
388
+ const c = await store.claim(id, inboxDigest(bytes))
389
+ if (c === 'claimed') {
390
+ claimed = true
391
+ return
392
+ }
393
+ throw connectionError(
394
+ 'PROTOCOL_ERROR',
395
+ c === 'digest-mismatch' ? 'The record changed after it was read' : 'The record is no longer waiting',
396
+ 'not-sent',
397
+ { epoch: record.epoch }
398
+ )
399
+ }
400
+ }
401
+ })
402
+ .catch(
403
+ (e): Outcome => ({
404
+ ok: false,
405
+ connectionError: connectionError(
406
+ 'CONFIGURATION_ERROR',
407
+ 'The wallet bridge failed',
408
+ claimed ? 'unknown' : 'not-sent',
409
+ {
410
+ epoch: record.epoch
411
+ }
412
+ )
413
+ })
414
+ )
415
+ await finish(id, outcomeResult(id, outcome))
416
+ }
417
+
418
+ async function sweepExpired() {
419
+ for (const id of await store.list('pending')) {
420
+ const loaded = await load(id)
421
+ if (!loaded) continue
422
+ await admissible(loaded.record)
423
+ }
424
+ }
425
+
426
+ return {
427
+ recover() {
428
+ recovered ??= recoverOnce().catch(e => {
429
+ recovered = undefined
430
+ throw e
431
+ })
432
+ return recovered
433
+ },
434
+
435
+ sweepExpired,
436
+
437
+ flushEvents: () => eventWrites,
438
+
439
+ dispose() {
440
+ unsubscribeClosed()
441
+ },
442
+
443
+ async processPending() {
444
+ await this.recover()
445
+ const ready: Array<{ id: string; record: InboxRecord; bytes: Uint8Array; size: number }> = []
446
+ for (const id of await store.list('pending')) {
447
+ const loaded = await load(id)
448
+ if (loaded && (await admissible(loaded.record))) ready.push({ id, ...loaded })
449
+ }
450
+ // Stable: records with equal timestamps keep the store's order.
451
+ ready.sort((a, b) => a.record.createdAt - b.record.createdAt)
452
+ const running: Promise<void>[] = []
453
+ for (const item of ready) {
454
+ if (!(await store.accept(item.id))) continue
455
+ running.push(
456
+ handle(item.id, item.record, item.bytes, item.size).catch(e => {
457
+ console.warn('[bridge] inbox record failed', e)
458
+ })
459
+ )
460
+ }
461
+ await Promise.all(running)
462
+ }
463
+ }
464
+ }
@@ -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
+ }
@@ -0,0 +1,25 @@
1
+ /** Loopback Host check (spec 6.2, DNS rebinding defence). Pure: shared in behaviour with the Kotlin HostCheck. */
2
+
3
+ export interface LoopbackBound {
4
+ port: number
5
+ ipv4: boolean
6
+ ipv6: boolean
7
+ }
8
+
9
+ /**
10
+ * The exact `Host` header values accepted for a bound port: `127.0.0.1:p`, `[::1]:p` when IPv6 is bound, and
11
+ * `localhost:p` only when both families are bound (BRC-185 forbids reaching another wallet through `localhost`).
12
+ */
13
+ export function allowedHosts(b: LoopbackBound): string[] {
14
+ const out: string[] = []
15
+ if (b.ipv4) out.push(`127.0.0.1:${b.port}`)
16
+ if (b.ipv6) out.push(`[::1]:${b.port}`)
17
+ if (b.ipv4 && b.ipv6) out.push(`localhost:${b.port}`)
18
+ return out
19
+ }
20
+
21
+ /** Exact, case-sensitive comparison: no normalisation, no trailing dot, no default-port elision. */
22
+ export function isAllowedHost(value: string | undefined | null, bound: LoopbackBound): boolean {
23
+ if (typeof value !== 'string') return false
24
+ return allowedHosts(bound).includes(value)
25
+ }
@@ -0,0 +1,7 @@
1
+ export * from './hostCheck'
2
+ export * from './endpoints'
3
+ export * from './status'
4
+ export * from './cors'
5
+ export * from './launchProof'
6
+ export * from './routerTypes'
7
+ export * from './router'