@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,621 @@
1
+ /**
2
+ * The dispatch pipeline (spec 6.6): one BRC-185 request in, one `Outcome` out.
3
+ *
4
+ * Order, as in the spec: transport bounds, binding, method, probes, arguments, wallet state and
5
+ * consent, readiness again, a synchronous re-check, the call, the result. Steps 6 and 7 may park a
6
+ * request for as long as it takes (BRC-219 sets no timeout on a pending prompt); a parked request
7
+ * wakes on two signals, a snapshot change and the close of its own binding, so a profile switch
8
+ * settles it instead of letting it proceed onto the new wallet.
9
+ *
10
+ * `Outcome.walletError` carries `delivery`, which the plan's type omitted but spec 6.11 assigns:
11
+ * `not-sent` for a refusal before the call, and for a call that failed on a read-only method
12
+ * (nothing can have changed); `unknown` for a call that failed on a mutating method.
13
+ *
14
+ * The `ConsentStore` needs the admin-scoped wallet, so it is not created here: `BrowserBridgeProvider`
15
+ * creates it per wallet, hands it to `createDispatcher`, then `installDispatcher`.
16
+ */
17
+ import { WERR_INVALID_PARAMETER, normalizeBRC100WalletByteFields, stringifyBRC100 } from '@bsv/sdk'
18
+ import { snapshotWalletResultRequest, validateWalletArgs, validateWalletResult } from '@bsv/sdk'
19
+ import type { WalletInterface } from '@bsv/sdk'
20
+ import { WalletArgTooLarge, capWalletArgs, tierLimits } from '../services/capWalletArgs'
21
+ import { checkWalletArgs, type WalletArgLimits } from '../services/walletArgLimits'
22
+ import type { Binding } from './bindings'
23
+ import type { ConsentStore, GroupPermissions } from './consent'
24
+ import { findTokenModuleVariant, isValidVersionString } from './policy'
25
+ import { encodeWalletError, type WireError } from './protocol/errorCodec'
26
+ import { connectionError, isConnectionError, type ConnectionError, type Delivery } from './protocol/connectionError'
27
+ import {
28
+ MAX_BRIDGE_REQUEST_BYTES,
29
+ MAX_IN_FLIGHT_BYTES,
30
+ MAX_IN_FLIGHT_PER_BINDING,
31
+ MAX_IN_FLIGHT_TOTAL
32
+ } from './protocol/limits'
33
+ import { BRIDGE_METHODS, isBridgeMethod, type WalletMethodName } from './protocol/methods'
34
+ import { assertCanonicalOriginator } from './protocol/origin'
35
+ import type { CloseEvent } from './bindings'
36
+ import {
37
+ assertBridgeHost,
38
+ getBindingRegistry,
39
+ getBridgeSnapshot,
40
+ getPublishedManagers,
41
+ getTransport,
42
+ onBindingClosed,
43
+ onSnapshotChange,
44
+ type AttentionReason
45
+ } from './runtime'
46
+
47
+ export interface DispatchRequest {
48
+ epoch: string
49
+ instanceId: string
50
+ continuityKey: string
51
+ origin: string
52
+ accountContext?: string
53
+ method: string
54
+ args: unknown
55
+ sizeBytes: number
56
+ /**
57
+ * Awaited once, after consent and before the final readiness wait and the synchronous re-check.
58
+ * The durable inbox claims its record here (spec 6.8): the claim is the at-most-once point, and
59
+ * the re-check then runs after it. A rejection with a `ConnectionError` settles the request with
60
+ * it; the wallet is not called.
61
+ */
62
+ beforeCall?: () => Promise<void>
63
+ }
64
+
65
+ export type Outcome =
66
+ | { ok: true; result: unknown }
67
+ | { ok: false; walletError: WireError; delivery: Delivery }
68
+ | { ok: false; connectionError: ConnectionError }
69
+
70
+ export interface DispatcherDeps {
71
+ consent: ConsentStore
72
+ /** Defaults to the device tier's limits, the same ones `capWalletArgs` applies. */
73
+ walletArgLimits?: WalletArgLimits
74
+ /** Nudges the backup log after a mutating call. Defaults to `TaskBackupPush.noteChanged`. */
75
+ noteChanged?: () => void
76
+ /**
77
+ * The manifest group to show on the Connect sheet, from the manager that will check it. Awaited
78
+ * under a short timeout before the sheet is raised; a failure, a timeout or an empty manifest
79
+ * all resolve to null, which gives the plain sheet.
80
+ */
81
+ previewGroup?: (binding: Binding) => Promise<GroupPermissions | null>
82
+ }
83
+
84
+ /** How long the Connect sheet waits for the manifest preview before showing without it. */
85
+ export const PREVIEW_GROUP_TIMEOUT_MS = 2000
86
+
87
+ export interface Dispatcher {
88
+ dispatch(input: { transport: string | { id: string }; request: DispatchRequest }): Promise<Outcome>
89
+ }
90
+
91
+ /** A settled outcome reached mid-pipeline. */
92
+ class Early {
93
+ constructor(readonly outcome: Outcome) {}
94
+ }
95
+
96
+ const refuse = (e: ConnectionError): Early => new Early({ ok: false, connectionError: e })
97
+ const walletRefusal = (wire: WireError): Early => new Early({ ok: false, walletError: wire, delivery: 'not-sent' })
98
+
99
+ function permissionDenied(message: string): Early {
100
+ const error = Object.assign(new Error(message), { code: 'ERR_PERMISSION_DENIED' })
101
+ return walletRefusal(encodeWalletError(error))
102
+ }
103
+
104
+ /** A wallet error that must reach the page as code 6, whatever the validator threw. */
105
+ function invalidArgument(e: unknown): Early {
106
+ const wire = encodeWalletError(e)
107
+ return walletRefusal(wire.code === 6 ? wire : encodeWalletError(new WERR_INVALID_PARAMETER('request', 'valid')))
108
+ }
109
+
110
+ const MAX_SCAN_DEPTH = 64
111
+
112
+ /**
113
+ * True when the arguments hold a typed array or an ArrayBuffer, or nest deeper than a JSON request
114
+ * could. Byte fields on this boundary are `number[]`. A deep cycle can only come from an
115
+ * in-process caller, and is refused the same way.
116
+ */
117
+ function hasBinaryOrDeep(v: unknown, depth = 0): boolean {
118
+ if (v === null || typeof v !== 'object') return false
119
+ if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) return true
120
+ if (depth > MAX_SCAN_DEPTH) return true
121
+ if (Array.isArray(v)) {
122
+ for (let i = 0; i < v.length; i++) {
123
+ const item = v[i]
124
+ if (item !== null && typeof item === 'object' && hasBinaryOrDeep(item, depth + 1)) return true
125
+ }
126
+ return false
127
+ }
128
+ for (const value of Object.values(v)) if (hasBinaryOrDeep(value, depth + 1)) return true
129
+ return false
130
+ }
131
+
132
+ function closedOutcome(e: CloseEvent): ConnectionError {
133
+ if (e.reason === 'lost') {
134
+ return connectionError('CONNECTION_CLOSED', 'This connection is closed', 'not-sent', {
135
+ epoch: e.epoch,
136
+ cause: 'lost'
137
+ })
138
+ }
139
+ if (e.reason === 'disconnected') {
140
+ return connectionError('DISCONNECTED', 'This connection was closed', 'not-sent', { epoch: e.epoch })
141
+ }
142
+ return connectionError('PROVIDER_CHANGED', 'This connection was closed', 'not-sent', {
143
+ epoch: e.epoch,
144
+ cause: e.reason
145
+ })
146
+ }
147
+
148
+ function readTxid(result: unknown): string | undefined {
149
+ const txid = (result as { txid?: unknown } | null | undefined)?.txid
150
+ return typeof txid === 'string' && /^[0-9a-f]{64}$/i.test(txid) ? txid : undefined
151
+ }
152
+
153
+ function defaultNoteChanged(): void {
154
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
155
+ const { TaskBackupPush } = require('../monitor/TaskBackupPush') as typeof import('../monitor/TaskBackupPush')
156
+ TaskBackupPush.noteChanged()
157
+ }
158
+
159
+ export function createDispatcher(deps: DispatcherDeps): Dispatcher {
160
+ const inFlightByEpoch = new Map<string, number>()
161
+ let inFlightTotal = 0
162
+ let inFlightBytes = 0
163
+
164
+ function admit(epoch: string, size: number): (() => void) | ConnectionError {
165
+ const per = inFlightByEpoch.get(epoch) ?? 0
166
+ if (per >= MAX_IN_FLIGHT_PER_BINDING || inFlightTotal >= MAX_IN_FLIGHT_TOTAL) {
167
+ return connectionError('RESOURCE_LIMIT', 'Too many requests in flight', 'not-sent', { epoch })
168
+ }
169
+ if (inFlightBytes + size > MAX_IN_FLIGHT_BYTES) {
170
+ return connectionError('RESOURCE_LIMIT', 'Too many request bytes in flight', 'not-sent', { epoch })
171
+ }
172
+ inFlightByEpoch.set(epoch, per + 1)
173
+ inFlightTotal += 1
174
+ inFlightBytes += size
175
+ let released = false
176
+ return () => {
177
+ if (released) return
178
+ released = true
179
+ const n = (inFlightByEpoch.get(epoch) ?? 1) - 1
180
+ if (n <= 0) inFlightByEpoch.delete(epoch)
181
+ else inFlightByEpoch.set(epoch, n)
182
+ inFlightTotal -= 1
183
+ inFlightBytes -= size
184
+ }
185
+ }
186
+
187
+ async function run(transportId: string, req: DispatchRequest): Promise<Outcome> {
188
+ const argLimits = deps.walletArgLimits ?? tierLimits()
189
+ const noteChanged = deps.noteChanged ?? defaultNoteChanged
190
+
191
+ // Without a mounted, loaded host nothing below is safe to touch (the registry throws).
192
+ try {
193
+ assertBridgeHost()
194
+ } catch (e) {
195
+ if (isConnectionError(e)) throw refuse(e)
196
+ throw e
197
+ }
198
+ const transport = getTransport(transportId)
199
+ if (!transport) {
200
+ throw refuse(
201
+ connectionError('CONFIGURATION_ERROR', 'Transport is not registered', 'not-sent', { epoch: req.epoch })
202
+ )
203
+ }
204
+
205
+ // 1. Transport bounds, re-checked here. Typed arrays are refused under the same code: the
206
+ // spec lists them with the boundary rules, and a JSON transport can never produce one.
207
+ if (typeof req.sizeBytes !== 'number' || !Number.isFinite(req.sizeBytes) || req.sizeBytes < 0) {
208
+ throw refuse(connectionError('PROTOCOL_ERROR', 'Request size missing', 'not-sent', { epoch: req.epoch }))
209
+ }
210
+ if (req.sizeBytes > MAX_BRIDGE_REQUEST_BYTES) {
211
+ throw refuse(connectionError('RESOURCE_LIMIT', 'Request too large', 'not-sent', { epoch: req.epoch }))
212
+ }
213
+ let binary: boolean
214
+ try {
215
+ binary = hasBinaryOrDeep(req.args)
216
+ } catch (e) {
217
+ // A hostile in-process object (a throwing getter) is an invalid argument, not a crash.
218
+ throw invalidArgument(e)
219
+ }
220
+ if (binary) {
221
+ throw refuse(
222
+ connectionError('RESOURCE_LIMIT', 'Byte fields must be number arrays', 'not-sent', { epoch: req.epoch })
223
+ )
224
+ }
225
+
226
+ // 2. Binding.
227
+ const resolved = getBindingRegistry().resolve(transportId, {
228
+ epoch: req.epoch,
229
+ instanceId: req.instanceId,
230
+ continuityKey: req.continuityKey,
231
+ origin: req.origin,
232
+ accountContext: req.accountContext
233
+ })
234
+ if (isConnectionError(resolved)) throw refuse(resolved)
235
+ const binding: Binding = resolved
236
+
237
+ // 3. Method.
238
+ if (!isBridgeMethod(req.method)) {
239
+ throw refuse(connectionError('PROTOCOL_ERROR', 'Unknown method', 'not-sent', { epoch: binding.epoch }))
240
+ }
241
+ const method: WalletMethodName = req.method
242
+ const info = BRIDGE_METHODS[method]
243
+
244
+ // 4. Probes: no gate, no wallet call, no wait. They hold no resource, so the in-flight limits
245
+ // (which exist to bound parked work) do not apply to them.
246
+ if (info.probe) {
247
+ const snap = getBridgeSnapshot()
248
+ if (method === 'isAuthenticated') {
249
+ throw new Early({ ok: true, result: { authenticated: snap.readiness === 'ready' } })
250
+ }
251
+ if (!isValidVersionString(snap.baseVersion)) {
252
+ throw refuse(
253
+ connectionError('CONFIGURATION_ERROR', 'The wallet version string is invalid', 'not-sent', {
254
+ epoch: binding.epoch
255
+ })
256
+ )
257
+ }
258
+ throw new Early({ ok: true, result: { version: snap.baseVersion } })
259
+ }
260
+
261
+ const release = admit(binding.epoch, req.sizeBytes)
262
+ if (typeof release !== 'function') throw refuse(release)
263
+
264
+ // Everything from here can park, so it watches this binding's close.
265
+ let closed: CloseEvent | undefined
266
+ const waiters = new Set<() => void>()
267
+ let consentRequested = false
268
+ const unsubscribeClose = onBindingClosed(e => {
269
+ if (e.epoch !== binding.epoch) return
270
+ closed = e
271
+ if (consentRequested) deps.consent.dropRequestsFor(e.epoch)
272
+ for (const w of [...waiters]) w()
273
+ })
274
+
275
+ /** Resolves with `p`, or rejects with the close outcome if the binding closes first. */
276
+ function untilClosed<T>(p: Promise<T>): Promise<T> {
277
+ if (closed) return Promise.reject(refuse(closedOutcome(closed)))
278
+ return new Promise<T>((resolve, reject) => {
279
+ const onClose = () => reject(refuse(closedOutcome(closed as CloseEvent)))
280
+ waiters.add(onClose)
281
+ p.then(
282
+ v => {
283
+ waiters.delete(onClose)
284
+ resolve(v)
285
+ },
286
+ e => {
287
+ waiters.delete(onClose)
288
+ reject(e)
289
+ }
290
+ )
291
+ })
292
+ }
293
+
294
+ function notify(reason: AttentionReason) {
295
+ try {
296
+ transport!.requestAttention(reason, binding)
297
+ } catch (e) {
298
+ console.warn('[bridge] requestAttention failed', e)
299
+ }
300
+ }
301
+
302
+ /** Parks until the runtime is `ready`; `none` fails at once. */
303
+ async function ensureReady(): Promise<void> {
304
+ let notified = false
305
+ for (;;) {
306
+ if (closed) throw refuse(closedOutcome(closed))
307
+ const readiness = getBridgeSnapshot().readiness
308
+ if (readiness === 'ready') return
309
+ if (readiness === 'none') {
310
+ throw refuse(
311
+ connectionError('CONFIGURATION_ERROR', 'No wallet is available', 'not-sent', { epoch: binding.epoch })
312
+ )
313
+ }
314
+ if (!notified) {
315
+ notified = true
316
+ notify('wallet-not-ready')
317
+ }
318
+ let off = () => {}
319
+ const changed = new Promise<void>(res => {
320
+ off = onSnapshotChange(() => res())
321
+ })
322
+ try {
323
+ await untilClosed(changed)
324
+ } finally {
325
+ off()
326
+ }
327
+ }
328
+ }
329
+
330
+ let started = false
331
+ try {
332
+ // 5. Arguments.
333
+ let args: unknown = req.args ?? {}
334
+ try {
335
+ args = normalizeBRC100WalletByteFields(args)
336
+ } catch (e) {
337
+ throw invalidArgument(e)
338
+ }
339
+ const refusal = checkWalletArgs(method, args, argLimits)
340
+ if (refusal) throw invalidArgument(new WalletArgTooLarge(refusal.field, refusal.message))
341
+ try {
342
+ validateWalletArgs(method as Parameters<typeof validateWalletArgs>[0], args)
343
+ } catch (e) {
344
+ throw invalidArgument(e)
345
+ }
346
+ if (binding.attestation === 'unattested' && findTokenModuleVariant(args) !== undefined) {
347
+ throw permissionDenied('Token modules are not available to unverified origins')
348
+ }
349
+ let requestSnapshot: unknown
350
+ try {
351
+ requestSnapshot = snapshotWalletResultRequest(method as Parameters<typeof snapshotWalletResultRequest>[0], args)
352
+ } catch (e) {
353
+ throw invalidArgument(e)
354
+ }
355
+
356
+ // 6. Wallet state, then consent. The store is authenticated by the admin wallet, which
357
+ // exists only when `ready`.
358
+ await ensureReady()
359
+ if (!binding.consented) {
360
+ const record = await untilClosed(deps.consent.lookup(binding.applicationOrigin, binding.attestation))
361
+ // The connect-time token is checked once, here, and forgotten whatever the result. A
362
+ // missing record and a wrong token look the same to the page: not connected, then the
363
+ // sheet (whose "connected before" line is the spec's only disclosure).
364
+ const presented = getBindingRegistry().takeReconnectToken(binding.epoch)
365
+ if (record !== undefined) {
366
+ if (binding.attestation === 'browser' || deps.consent.checkReconnect(record, presented)) {
367
+ getBindingRegistry().markConsented(binding.epoch, record.originator)
368
+ }
369
+ }
370
+ if (!binding.consented) {
371
+ if ((args as { seekPermission?: unknown }).seekPermission === false) {
372
+ throw permissionDenied('Permission denied: this site is not connected')
373
+ }
374
+ let groupPermissions: GroupPermissions | null = null
375
+ if (deps.previewGroup !== undefined) {
376
+ const preview = deps.previewGroup
377
+ let timer: ReturnType<typeof setTimeout> | undefined
378
+ groupPermissions = await untilClosed(
379
+ Promise.race([
380
+ Promise.resolve()
381
+ .then(() => preview(binding))
382
+ .catch(() => null),
383
+ new Promise<null>(res => {
384
+ timer = setTimeout(() => res(null), PREVIEW_GROUP_TIMEOUT_MS)
385
+ })
386
+ ]).finally(() => clearTimeout(timer))
387
+ )
388
+ }
389
+ const asked = deps.consent.requestConsent({
390
+ origin: binding.applicationOrigin,
391
+ attestation: binding.attestation,
392
+ transportId,
393
+ bindingEpoch: binding.epoch,
394
+ walletRevision: Number(getBridgeSnapshot().walletRevision),
395
+ connectedBefore: record !== undefined,
396
+ groupPermissions
397
+ })
398
+ if ('refused' in asked) {
399
+ throw refuse(
400
+ connectionError(
401
+ 'RESOURCE_LIMIT',
402
+ asked.refused === 'backoff' ? 'This site was just declined' : 'A connection request is already open',
403
+ 'not-sent',
404
+ { epoch: binding.epoch }
405
+ )
406
+ )
407
+ }
408
+ consentRequested = true
409
+ notify('consent')
410
+ const answer = await untilClosed(asked.promise)
411
+ const approved =
412
+ answer === 'approved'
413
+ ? await untilClosed(deps.consent.lookup(binding.applicationOrigin, binding.attestation))
414
+ : undefined
415
+ if (approved === undefined) {
416
+ throw refuse(
417
+ connectionError('USER_CANCELLED', 'The connection was declined', 'not-sent', { epoch: binding.epoch })
418
+ )
419
+ }
420
+ getBindingRegistry().markConsented(binding.epoch, approved.originator)
421
+ }
422
+ }
423
+
424
+ if (req.beforeCall) {
425
+ try {
426
+ await untilClosed(req.beforeCall())
427
+ } catch (e) {
428
+ if (e instanceof Early) throw e
429
+ if (isConnectionError(e)) throw refuse({ ...e, epoch: e.epoch ?? binding.epoch })
430
+ throw e
431
+ }
432
+ }
433
+
434
+ // 7 and 8. Readiness again, then the synchronous re-check and the call with no await between.
435
+ let call: Promise<unknown>
436
+ for (;;) {
437
+ await ensureReady()
438
+ const snap = getBridgeSnapshot()
439
+ const published = getPublishedManagers()
440
+ const manager = binding.attestation === 'unattested' ? published.unverified : published.attested
441
+ if (snap.readiness !== 'ready') continue
442
+ let current =
443
+ binding.state === 'live' &&
444
+ String(binding.walletRevision) === snap.walletRevision &&
445
+ binding.accountContext === snap.accountContext &&
446
+ manager !== undefined
447
+ if (current) {
448
+ try {
449
+ assertCanonicalOriginator(binding.originator)
450
+ } catch {
451
+ current = false
452
+ }
453
+ }
454
+ if (!current || manager === undefined) {
455
+ throw refuse(
456
+ connectionError('PROVIDER_CHANGED', 'The wallet changed since this page connected', 'not-sent', {
457
+ epoch: binding.epoch,
458
+ cause: 'account-changed'
459
+ })
460
+ )
461
+ }
462
+ // 9. Call, on the guarded stack read just now, never cached across builds.
463
+ const wallet = capWalletArgs(manager.wallet as WalletInterface, argLimits)
464
+ started = true
465
+ try {
466
+ call = Promise.resolve(
467
+ (wallet as unknown as Record<string, (a: unknown, o?: string) => unknown>)[method](args, binding.originator)
468
+ )
469
+ } catch (e) {
470
+ call = Promise.reject(e)
471
+ }
472
+ break
473
+ }
474
+
475
+ // 10. After the call. A mutating call nudges backup on every outcome, errors included.
476
+ if (info.mutating) {
477
+ const note = () => {
478
+ try {
479
+ noteChanged()
480
+ } catch (e) {
481
+ console.warn('[bridge] noteChanged failed', e)
482
+ }
483
+ }
484
+ call.then(note, note)
485
+ }
486
+ let result: unknown
487
+ try {
488
+ result = await new Promise<unknown>((resolve, reject) => {
489
+ if (closed) {
490
+ reject(new Early(closedWhileRunning(closed)))
491
+ return
492
+ }
493
+ const onClose = () => reject(new Early(closedWhileRunning(closed as CloseEvent)))
494
+ waiters.add(onClose)
495
+ call.then(
496
+ v => {
497
+ waiters.delete(onClose)
498
+ resolve(v)
499
+ },
500
+ e => {
501
+ waiters.delete(onClose)
502
+ reject(e)
503
+ }
504
+ )
505
+ })
506
+ } catch (e) {
507
+ if (e instanceof Early) throw e
508
+ if (binding.state === 'closed' && closed) throw new Early(closedWhileRunning(closed))
509
+ throw new Early({
510
+ ok: false,
511
+ walletError: encodeWalletError(e),
512
+ delivery: info.mutating ? 'unknown' : 'not-sent'
513
+ })
514
+ }
515
+
516
+ return finishResult(result)
517
+
518
+ function finishResult(raw: unknown): Outcome {
519
+ if (method === 'getVersion') {
520
+ const v = (raw as { version?: unknown } | null)?.version
521
+ if (!isValidVersionString(v)) return invalidResult(raw)
522
+ return { ok: true, result: { version: v } }
523
+ }
524
+ try {
525
+ if (stringifyBRC100(raw).length > MAX_BRIDGE_REQUEST_BYTES) {
526
+ return {
527
+ ok: false,
528
+ connectionError: connectionError('RESOURCE_LIMIT', 'Response too large', 'unknown', {
529
+ epoch: binding.epoch
530
+ })
531
+ }
532
+ }
533
+ const validated = validateWalletResult(
534
+ method as Parameters<typeof validateWalletResult>[0],
535
+ raw,
536
+ requestSnapshot
537
+ )
538
+ return { ok: true, result: validated }
539
+ } catch {
540
+ return invalidResult(raw)
541
+ }
542
+ }
543
+
544
+ function invalidResult(raw: unknown): Outcome {
545
+ if (info.mutating) {
546
+ return {
547
+ ok: false,
548
+ connectionError: connectionError('PROTOCOL_ERROR', 'The wallet returned an invalid result', 'unknown', {
549
+ epoch: binding.epoch,
550
+ cause: 'invalid-result',
551
+ txid: readTxid(raw)
552
+ })
553
+ }
554
+ }
555
+ return {
556
+ ok: false,
557
+ walletError: encodeWalletError(new Error('The wallet returned an invalid result')),
558
+ delivery: 'not-sent'
559
+ }
560
+ }
561
+ } catch (e) {
562
+ if (e instanceof Early) throw e
563
+ console.warn('[bridge] dispatch failed', e)
564
+ throw refuse(
565
+ connectionError('CONFIGURATION_ERROR', 'The wallet bridge failed', started ? 'unknown' : 'not-sent', {
566
+ epoch: binding.epoch
567
+ })
568
+ )
569
+ } finally {
570
+ unsubscribeClose()
571
+ release()
572
+ }
573
+ }
574
+
575
+ function closedWhileRunning(e: CloseEvent): Outcome {
576
+ return {
577
+ ok: false,
578
+ connectionError: connectionError('CONNECTION_CLOSED', 'The connection closed during the call', 'unknown', {
579
+ epoch: e.epoch,
580
+ cause: e.reason
581
+ })
582
+ }
583
+ }
584
+
585
+ return {
586
+ async dispatch({ transport, request }) {
587
+ const transportId = typeof transport === 'string' ? transport : transport.id
588
+ try {
589
+ return await run(transportId, request)
590
+ } catch (e) {
591
+ if (e instanceof Early) return e.outcome
592
+ console.warn('[bridge] dispatch failed', e)
593
+ return {
594
+ ok: false,
595
+ connectionError: connectionError('CONFIGURATION_ERROR', 'The wallet bridge failed', 'not-sent', {
596
+ epoch: request?.epoch
597
+ })
598
+ }
599
+ }
600
+ }
601
+ }
602
+ }
603
+
604
+ let installed: Dispatcher | undefined
605
+
606
+ /** The host's dispatcher, set once the consent store exists. Transports call `dispatch`. */
607
+ export function installDispatcher(d: Dispatcher | undefined): void {
608
+ installed = d
609
+ }
610
+
611
+ export function dispatch(input: { transport: string | { id: string }; request: DispatchRequest }): Promise<Outcome> {
612
+ if (!installed) {
613
+ return Promise.resolve({
614
+ ok: false,
615
+ connectionError: connectionError('CONFIGURATION_ERROR', 'The wallet bridge is not available', 'not-sent', {
616
+ epoch: input.request?.epoch
617
+ })
618
+ })
619
+ }
620
+ return installed.dispatch(input)
621
+ }