@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,459 @@
1
+ /**
2
+ * Binding registry (spec 6.7): the live pairing between one page (an epoch) and the wallet,
3
+ * the install-wide tombstone ring that stops a closed epoch from ever binding again, the
4
+ * admission horizon for implicit (queue) epochs, and the synchronous close fan-out.
5
+ *
6
+ * Transport-free and clock-injected. Bindings live in memory only; the tombstone ring, its
7
+ * `evictedThrough` watermark and the `closeSeq` counter persist through `tombstoneStorage`.
8
+ * Closes are synchronous: `onClosed` runs before `close` returns, so no request on a replacement
9
+ * binding is admitted ahead of the fan-out. Persistence is a serialised write queue behind that;
10
+ * the in-memory ring is authoritative once `load()` has resolved, and `flush()` awaits the queue.
11
+ *
12
+ * The ContinuityStore comparison for an explicit connect (a mismatch is `PROVIDER_CHANGED`) is the
13
+ * transport's step before `connectExplicit`; this module only compares what each request repeats.
14
+ */
15
+ import type { KeyValue } from './consent'
16
+ import { connectionError, isConnectionError, type ConnectionError } from './protocol/connectionError'
17
+ import type { InternalCloseReason } from './protocol/envelopes'
18
+ import { MAX_BINDINGS_PER_ORIGIN, MAX_BINDINGS_TOTAL, TOMBSTONE_RING_SIZE, TOMBSTONE_TTL_MS } from './protocol/limits'
19
+ import { canonicalizeBridgeOrigin, OriginRefused, type Attestation } from './protocol/origin'
20
+
21
+ /** The wallet revision is a persisted counter; the queue stores it as a string. Compared as text. */
22
+ export type WalletRevision = string | number
23
+
24
+ export interface Binding {
25
+ epoch: string
26
+ transportId: string
27
+ applicationOrigin: string
28
+ /** Browser: the hostname. Unattested: set when consent resolves (6.3). */
29
+ originator?: string
30
+ attestation: Attestation
31
+ instanceId: string
32
+ continuityKey: string
33
+ accountContext: string
34
+ walletRevision: WalletRevision
35
+ boundAt: number
36
+ createdAt: number
37
+ state: 'live' | 'closed'
38
+ closeReason?: InternalCloseReason
39
+ /** Present and true on every unattested binding, absent on `browser` bindings. Fixed at connect. */
40
+ launchProofVerified?: true
41
+ /** True once the reconnect token matched or the user approved (6.4). */
42
+ consented: boolean
43
+ }
44
+
45
+ export interface CloseEvent {
46
+ closeSeq: number
47
+ epoch: string
48
+ reason: InternalCloseReason
49
+ /** False for a page-initiated disconnect: tombstone and outbox event, but no notice to that page. */
50
+ notifyPage: boolean
51
+ transportId: string
52
+ instanceId: string
53
+ applicationOrigin: string
54
+ }
55
+
56
+ export interface BindingRegistryDeps {
57
+ tombstoneStorage: KeyValue
58
+ now: () => number
59
+ onClosed: (e: CloseEvent) => void
60
+ /**
61
+ * The registered transport, which is where trust comes from (spec 6.2): its attestation and
62
+ * binding mode. When given, a binding on an unknown transport, or one whose attestation or mode
63
+ * differs from the registration, is refused. Absent in unit tests that exercise the registry alone.
64
+ */
65
+ transportInfo?: (id: string) => { attestation: Attestation; bindingMode: 'implicit' | 'explicit' } | undefined
66
+ /** Host policy for `http://localhost:<port>` origins (development builds only). */
67
+ allowLocalhostHttp?: () => boolean
68
+ }
69
+
70
+ export interface ExplicitConnectInput {
71
+ epoch: string
72
+ transportId: string
73
+ applicationOrigin: string
74
+ originator?: string
75
+ attestation: Attestation
76
+ instanceId: string
77
+ continuityKey: string
78
+ accountContext: string
79
+ walletRevision: WalletRevision
80
+ launchProofVerified?: boolean
81
+ /**
82
+ * Unattested only: the reconnect token the page presented at connect (6.4, 6.7). Held in memory
83
+ * beside the binding, never on it, so no snapshot, log line or error can carry it. The
84
+ * dispatcher takes it once, at the binding's first interactive request.
85
+ */
86
+ reconnectToken?: string
87
+ }
88
+
89
+ /** An inbox record (6.8) plus what the registered transport contributes: its id and attestation. */
90
+ export interface ImplicitRecord {
91
+ epoch: string
92
+ transportId: string
93
+ attestation: Attestation
94
+ origin: string
95
+ instanceId: string
96
+ continuityKey: string
97
+ accountContext: string
98
+ walletRevision: WalletRevision
99
+ boundAt: number
100
+ originator?: string
101
+ }
102
+
103
+ export interface ResolveRequest {
104
+ epoch: string
105
+ instanceId: string
106
+ continuityKey: string
107
+ origin: string
108
+ accountContext?: string
109
+ }
110
+
111
+ export interface BindingRegistry {
112
+ /** Reads the persisted ring. Must resolve before any other call; a storage failure rejects. */
113
+ load(): Promise<void>
114
+ /** Resolves once every queued ring write has reached storage. */
115
+ flush(): Promise<void>
116
+ connectExplicit(input: ExplicitConnectInput): Binding
117
+ admitImplicit(
118
+ record: ImplicitRecord,
119
+ current: { walletRevision: WalletRevision; accountContext: string }
120
+ ): Binding | ConnectionError
121
+ resolve(transportId: string, request: ResolveRequest): Binding | ConnectionError
122
+ /** Records the originator minted at consent and marks the binding consented. */
123
+ markConsented(epoch: string, originator: string): void
124
+ /** Returns the connect-time reconnect token once and forgets it. Undefined when none was presented. */
125
+ takeReconnectToken(epoch: string): string | undefined
126
+ close(epoch: string, reason: InternalCloseReason): void
127
+ closeAll(reason: InternalCloseReason): void
128
+ live(): Binding[]
129
+ /** The monotonic close counter, restored from the persisted ring by `load()`. */
130
+ closeSeq(): number
131
+ }
132
+
133
+ interface Tombstone {
134
+ reason: InternalCloseReason
135
+ closedAt: number
136
+ }
137
+
138
+ const RING_KEY = 'bsv-bridge-binding-tombstones-v1'
139
+
140
+ export function createBindingRegistry(deps: BindingRegistryDeps): BindingRegistry {
141
+ const liveByEpoch = new Map<string, Binding>()
142
+ // Off the Binding object on purpose (see ExplicitConnectInput.reconnectToken).
143
+ const reconnectTokens = new Map<string, string>()
144
+ // Map keeps insertion order, which is close order: the first entry is the oldest.
145
+ const ring = new Map<string, Tombstone>()
146
+ let evictedThrough = 0
147
+ let closeSeq = 0
148
+ let loaded = false
149
+ let writes: Promise<void> = Promise.resolve()
150
+
151
+ const sameRev = (a: WalletRevision, b: WalletRevision) => String(a) === String(b)
152
+
153
+ function assertLoaded() {
154
+ // Fail closed: without the ring an old epoch could be re-admitted.
155
+ if (!loaded) throw new Error('Binding registry used before load()')
156
+ }
157
+
158
+ function persist() {
159
+ const body = JSON.stringify({
160
+ v: 1,
161
+ evictedThrough,
162
+ closeSeq,
163
+ entries: [...ring].map(([epoch, t]) => [epoch, t.reason, t.closedAt])
164
+ })
165
+ writes = writes.then(
166
+ () => deps.tombstoneStorage.setItem(RING_KEY, body),
167
+ () => deps.tombstoneStorage.setItem(RING_KEY, body)
168
+ )
169
+ // A failed write must not become an unhandled rejection; flush() surfaces it.
170
+ writes.catch(() => undefined)
171
+ }
172
+
173
+ function prune(now: number) {
174
+ for (const [epoch, t] of ring) {
175
+ if (now - t.closedAt <= TOMBSTONE_TTL_MS) break
176
+ ring.delete(epoch)
177
+ }
178
+ }
179
+
180
+ function tombstone(epoch: string, reason: InternalCloseReason) {
181
+ const now = deps.now()
182
+ ring.set(epoch, { reason, closedAt: now })
183
+ while (ring.size > TOMBSTONE_RING_SIZE) {
184
+ const [oldest, t] = ring.entries().next().value as [string, Tombstone]
185
+ ring.delete(oldest)
186
+ if (t.closedAt > evictedThrough) evictedThrough = t.closedAt
187
+ }
188
+ prune(now)
189
+ }
190
+
191
+ /** The one close path: tombstone, increment closeSeq, persist, then fan out synchronously. */
192
+ function recordClose(
193
+ who: Pick<Binding, 'epoch' | 'transportId' | 'instanceId' | 'applicationOrigin'>,
194
+ reason: InternalCloseReason
195
+ ) {
196
+ tombstone(who.epoch, reason)
197
+ closeSeq += 1
198
+ persist()
199
+ deps.onClosed({
200
+ closeSeq,
201
+ epoch: who.epoch,
202
+ reason,
203
+ notifyPage: reason !== 'disconnected',
204
+ transportId: who.transportId,
205
+ instanceId: who.instanceId,
206
+ applicationOrigin: who.applicationOrigin
207
+ })
208
+ }
209
+
210
+ function tombstoneError(epoch: string, t: Tombstone): ConnectionError {
211
+ return connectionError('PROVIDER_CHANGED', 'This connection was closed', 'not-sent', {
212
+ epoch,
213
+ ...(t.reason === 'disconnected' ? {} : { cause: t.reason })
214
+ })
215
+ }
216
+
217
+ function limitError(epoch: string, message: string): ConnectionError {
218
+ return connectionError('RESOURCE_LIMIT', message, 'not-sent', { epoch })
219
+ }
220
+
221
+ /** Returns an error when a new live binding for `origin` would exceed a limit. */
222
+ function checkLimits(epoch: string, origin: string): ConnectionError | undefined {
223
+ if (liveByEpoch.size >= MAX_BINDINGS_TOTAL) return limitError(epoch, 'Too many open connections')
224
+ let perOrigin = 0
225
+ for (const b of liveByEpoch.values()) if (b.applicationOrigin === origin) perOrigin++
226
+ if (perOrigin >= MAX_BINDINGS_PER_ORIGIN) return limitError(epoch, 'Too many open connections for this site')
227
+ return undefined
228
+ }
229
+
230
+ /**
231
+ * The core's own check of the trust inputs it is handed (spec 6.3): the origin must be canonical
232
+ * for its attestation, and the attestation and binding mode must be the registered transport's.
233
+ * Returns the canonical originator for a `browser` binding.
234
+ */
235
+ function validateTrust(
236
+ epoch: string,
237
+ transportId: string,
238
+ origin: string,
239
+ attestation: Attestation,
240
+ mode: 'implicit' | 'explicit'
241
+ ): { originator: string | undefined } | ConnectionError {
242
+ if (deps.transportInfo) {
243
+ const info = deps.transportInfo(transportId)
244
+ if (!info) return connectionError('CONFIGURATION_ERROR', 'Transport is not registered', 'not-sent', { epoch })
245
+ if (info.attestation !== attestation || info.bindingMode !== mode) {
246
+ return connectionError('PROTOCOL_ERROR', 'Attestation does not match the transport', 'not-sent', { epoch })
247
+ }
248
+ }
249
+ try {
250
+ const canon = canonicalizeBridgeOrigin({
251
+ origin,
252
+ attestation,
253
+ allowLocalhostHttp: deps.allowLocalhostHttp?.() === true
254
+ })
255
+ return { originator: canon.originator }
256
+ } catch (e) {
257
+ if (e instanceof OriginRefused) {
258
+ return connectionError('PROTOCOL_ERROR', 'Origin refused', 'not-sent', { epoch })
259
+ }
260
+ throw e
261
+ }
262
+ }
263
+
264
+ function create(
265
+ base: Omit<Binding, 'createdAt' | 'state' | 'consented' | 'launchProofVerified'>,
266
+ launchProofVerified: boolean | undefined
267
+ ): Binding {
268
+ const b: Binding = { ...base, createdAt: deps.now(), state: 'live', consented: false }
269
+ if (b.attestation === 'unattested' && launchProofVerified === true) b.launchProofVerified = true
270
+ liveByEpoch.set(b.epoch, b)
271
+ return b
272
+ }
273
+
274
+ return {
275
+ async load() {
276
+ const raw = await deps.tombstoneStorage.getItem(RING_KEY)
277
+ ring.clear()
278
+ evictedThrough = 0
279
+ closeSeq = 0
280
+ if (raw !== null) {
281
+ const p = JSON.parse(raw)
282
+ if (p && p.v === 1 && Array.isArray(p.entries)) {
283
+ evictedThrough = Number(p.evictedThrough) || 0
284
+ closeSeq = Number(p.closeSeq) || 0
285
+ for (const e of p.entries) {
286
+ if (Array.isArray(e) && typeof e[0] === 'string' && typeof e[2] === 'number') {
287
+ ring.set(e[0], { reason: e[1], closedAt: e[2] })
288
+ }
289
+ }
290
+ }
291
+ }
292
+ prune(deps.now())
293
+ loaded = true
294
+ },
295
+
296
+ flush: () => writes,
297
+
298
+ connectExplicit(input) {
299
+ assertLoaded()
300
+ if (input.attestation === 'unattested' && input.launchProofVerified !== true) {
301
+ // No binding and no limit slot: the check runs before either.
302
+ throw connectionError(
303
+ 'CONFIGURATION_ERROR',
304
+ 'An unattested connection needs a verified launch proof',
305
+ 'not-sent',
306
+ { epoch: input.epoch }
307
+ )
308
+ }
309
+ const trust = validateTrust(
310
+ input.epoch,
311
+ input.transportId,
312
+ input.applicationOrigin,
313
+ input.attestation,
314
+ 'explicit'
315
+ )
316
+ if (isConnectionError(trust)) throw trust
317
+ const dead = ring.get(input.epoch)
318
+ if (dead) throw tombstoneError(input.epoch, dead)
319
+ if (liveByEpoch.has(input.epoch)) {
320
+ throw connectionError('PROTOCOL_ERROR', 'Connection epoch already in use', 'not-sent', { epoch: input.epoch })
321
+ }
322
+ const over = checkLimits(input.epoch, input.applicationOrigin)
323
+ if (over) throw over
324
+ const created = create(
325
+ {
326
+ epoch: input.epoch,
327
+ transportId: input.transportId,
328
+ applicationOrigin: input.applicationOrigin,
329
+ originator: trust.originator ?? input.originator,
330
+ attestation: input.attestation,
331
+ instanceId: input.instanceId,
332
+ continuityKey: input.continuityKey,
333
+ accountContext: input.accountContext,
334
+ walletRevision: input.walletRevision,
335
+ boundAt: deps.now()
336
+ },
337
+ input.launchProofVerified
338
+ )
339
+ if (input.attestation === 'unattested' && typeof input.reconnectToken === 'string' && input.reconnectToken) {
340
+ reconnectTokens.set(input.epoch, input.reconnectToken)
341
+ }
342
+ return created
343
+ },
344
+
345
+ admitImplicit(record, current) {
346
+ assertLoaded()
347
+ const trust = validateTrust(record.epoch, record.transportId, record.origin, record.attestation, 'implicit')
348
+ if (isConnectionError(trust)) return trust
349
+ const who = {
350
+ epoch: record.epoch,
351
+ transportId: record.transportId,
352
+ instanceId: record.instanceId,
353
+ applicationOrigin: record.origin
354
+ }
355
+ const existing = liveByEpoch.get(record.epoch)
356
+ if (existing) {
357
+ return this.resolve(record.transportId, {
358
+ epoch: record.epoch,
359
+ instanceId: record.instanceId,
360
+ continuityKey: record.continuityKey,
361
+ origin: record.origin
362
+ })
363
+ }
364
+ const dead = ring.get(record.epoch)
365
+ if (dead) return tombstoneError(record.epoch, dead)
366
+
367
+ const now = deps.now()
368
+ // Admission horizon: with no tombstone to consult, an old epoch must not be re-admitted.
369
+ if (now - record.boundAt > TOMBSTONE_TTL_MS || record.boundAt <= evictedThrough) {
370
+ recordClose(who, 'lost')
371
+ return connectionError('CONNECTION_CLOSED', 'This connection is too old; reconnect', 'not-sent', {
372
+ epoch: record.epoch,
373
+ cause: 'lost'
374
+ })
375
+ }
376
+ if (!sameRev(record.walletRevision, current.walletRevision) || record.accountContext !== current.accountContext) {
377
+ recordClose(who, 'account-changed')
378
+ return connectionError('PROVIDER_CHANGED', 'The wallet changed since this page connected', 'not-sent', {
379
+ epoch: record.epoch,
380
+ cause: 'account-changed'
381
+ })
382
+ }
383
+ const over = checkLimits(record.epoch, record.origin)
384
+ if (over) return over
385
+ return create(
386
+ {
387
+ epoch: record.epoch,
388
+ transportId: record.transportId,
389
+ applicationOrigin: record.origin,
390
+ originator: trust.originator ?? record.originator,
391
+ attestation: record.attestation,
392
+ instanceId: record.instanceId,
393
+ continuityKey: record.continuityKey,
394
+ accountContext: record.accountContext,
395
+ walletRevision: record.walletRevision,
396
+ boundAt: record.boundAt
397
+ },
398
+ undefined
399
+ )
400
+ },
401
+
402
+ resolve(transportId, request) {
403
+ assertLoaded()
404
+ const b = liveByEpoch.get(request.epoch)
405
+ if (!b) {
406
+ const dead = ring.get(request.epoch)
407
+ if (dead) return tombstoneError(request.epoch, dead)
408
+ return connectionError('PROVIDER_CHANGED', 'Unknown connection', 'not-sent', { epoch: request.epoch })
409
+ }
410
+ if (
411
+ b.transportId !== transportId ||
412
+ b.instanceId !== request.instanceId ||
413
+ b.continuityKey !== request.continuityKey ||
414
+ b.applicationOrigin !== request.origin
415
+ ) {
416
+ return connectionError('PROVIDER_CHANGED', 'Connection does not match', 'not-sent', { epoch: request.epoch })
417
+ }
418
+ if (request.accountContext !== undefined && request.accountContext !== b.accountContext) {
419
+ return connectionError('PROVIDER_CHANGED', 'The wallet changed since this page connected', 'not-sent', {
420
+ epoch: request.epoch,
421
+ cause: 'account-changed'
422
+ })
423
+ }
424
+ return b
425
+ },
426
+
427
+ markConsented(epoch, originator) {
428
+ const b = liveByEpoch.get(epoch)
429
+ if (!b) return
430
+ b.originator = originator
431
+ b.consented = true
432
+ },
433
+
434
+ takeReconnectToken(epoch) {
435
+ const token = reconnectTokens.get(epoch)
436
+ reconnectTokens.delete(epoch)
437
+ return token
438
+ },
439
+
440
+ close(epoch, reason) {
441
+ assertLoaded()
442
+ reconnectTokens.delete(epoch)
443
+ const b = liveByEpoch.get(epoch)
444
+ if (!b) return
445
+ b.state = 'closed'
446
+ b.closeReason = reason
447
+ liveByEpoch.delete(epoch)
448
+ recordClose(b, reason)
449
+ },
450
+
451
+ closeAll(reason) {
452
+ for (const epoch of [...liveByEpoch.keys()]) this.close(epoch, reason)
453
+ },
454
+
455
+ live: () => [...liveByEpoch.values()],
456
+
457
+ closeSeq: () => closeSeq
458
+ }
459
+ }
@@ -0,0 +1,222 @@
1
+ /**
2
+ * The generated conformance report (spec 8, 9): what the bridge core carries, what it refuses and
3
+ * where it knowingly differs from BRC-185 / BRC-219. Pure data built from the same tables the
4
+ * dispatcher uses, so the list of methods and the limits cannot drift from the code. The wording of
5
+ * refusals and deviations is spec 6.11 and 9; the snapshot test makes any change to it deliberate.
6
+ */
7
+ import { BRIDGE_METHODS, type WalletMethodName } from './protocol/methods'
8
+ import {
9
+ DECLINE_BACKOFF_MS,
10
+ INBOX_MAX_VALIDITY_MS,
11
+ MAX_BINDINGS_PER_ORIGIN,
12
+ MAX_BINDINGS_TOTAL,
13
+ MAX_BRIDGE_REQUEST_BYTES,
14
+ MAX_IN_FLIGHT_BYTES,
15
+ MAX_IN_FLIGHT_PER_BINDING,
16
+ MAX_IN_FLIGHT_TOTAL
17
+ } from './protocol/limits'
18
+
19
+ /** Bumped when the report's shape changes. */
20
+ export const CONFORMANCE_REPORT_VERSION = 1
21
+
22
+ export interface MethodConformance {
23
+ name: WalletMethodName
24
+ /** `probe`: answered by the bridge with no consent, wallet call or wait. `wallet`: forwarded to the permissions manager. */
25
+ handling: 'probe' | 'wallet'
26
+ mutating: boolean
27
+ /** Ids from `deviations` that touch this method. */
28
+ deviations: string[]
29
+ }
30
+
31
+ export interface Refusal {
32
+ id: string
33
+ when: string
34
+ outcome: string
35
+ delivery: 'not-sent' | 'unknown'
36
+ }
37
+
38
+ export interface Deviation {
39
+ id: string
40
+ summary: string
41
+ }
42
+
43
+ export interface ConformanceReport {
44
+ reportVersion: number
45
+ protocol: 'BRC-185'
46
+ spec: { document: string; revision: number }
47
+ methods: MethodConformance[]
48
+ limits: Record<string, number>
49
+ refusals: Refusal[]
50
+ deviations: Deviation[]
51
+ }
52
+
53
+ export const BRIDGE_REFUSALS: readonly Refusal[] = [
54
+ {
55
+ id: 'no-provider-or-wallet',
56
+ when: 'No provider mounted; no wallet exists; unattested connect without launch proof',
57
+ outcome: 'ConnectionError CONFIGURATION_ERROR',
58
+ delivery: 'not-sent'
59
+ },
60
+ {
61
+ id: 'protocol-violation',
62
+ when: 'Origin refused; attestation mismatch; originator frame mismatch; unknown method on an epoch transport; asserted (non-web) context',
63
+ outcome: 'ConnectionError PROTOCOL_ERROR',
64
+ delivery: 'not-sent'
65
+ },
66
+ {
67
+ id: 'provider-changed',
68
+ when: 'Unknown, retired or mismatched binding; account or wallet changed before the call',
69
+ outcome: 'ConnectionError PROVIDER_CHANGED (cause account-changed when known)',
70
+ delivery: 'not-sent'
71
+ },
72
+ {
73
+ id: 'user-declined',
74
+ when: 'User declined site consent',
75
+ outcome: 'ConnectionError USER_CANCELLED',
76
+ delivery: 'not-sent'
77
+ },
78
+ {
79
+ id: 'resource-limit',
80
+ when: 'Request over size or concurrency; the transport sheet slot is held; inside the decline backoff',
81
+ outcome: 'ConnectionError RESOURCE_LIMIT',
82
+ delivery: 'not-sent'
83
+ },
84
+ {
85
+ id: 'response-too-large',
86
+ when: 'Response over the limit',
87
+ outcome: 'ConnectionError RESOURCE_LIMIT',
88
+ delivery: 'unknown'
89
+ },
90
+ {
91
+ id: 'inbox-expired',
92
+ when: 'Inbox record expired before acceptance; implicit epoch outside the admission horizon',
93
+ outcome: 'ConnectionError CONNECTION_CLOSED',
94
+ delivery: 'not-sent'
95
+ },
96
+ {
97
+ id: 'not-connected-no-seek',
98
+ when: 'seekPermission false from a site that is not connected',
99
+ outcome: 'Wallet error 1, permission denied',
100
+ delivery: 'not-sent'
101
+ },
102
+ {
103
+ id: 'unverified-token-module',
104
+ when: 'A token-module name (any case variant) from an unverified origin',
105
+ outcome: 'Wallet error 1, permission denied',
106
+ delivery: 'not-sent'
107
+ },
108
+ {
109
+ id: 'typed-arrays',
110
+ when: 'Typed arrays or ArrayBuffers in arguments; byte fields must be number arrays',
111
+ outcome: 'ConnectionError RESOURCE_LIMIT',
112
+ delivery: 'not-sent'
113
+ },
114
+ {
115
+ id: 'invalid-arguments',
116
+ when: 'Arguments fail BRC-100 validation or the wallet argument caps',
117
+ outcome: 'Wallet error 6',
118
+ delivery: 'not-sent'
119
+ },
120
+ {
121
+ id: 'closed-in-flight',
122
+ when: 'Claimed, then crash; in flight, then binding closed or teardown',
123
+ outcome: 'ConnectionError CONNECTION_CLOSED',
124
+ delivery: 'unknown'
125
+ },
126
+ {
127
+ id: 'invalid-result',
128
+ when: 'Mutating call whose result failed validation',
129
+ outcome: 'ConnectionError PROTOCOL_ERROR (cause invalid-result)',
130
+ delivery: 'unknown'
131
+ }
132
+ ]
133
+
134
+ export const BRIDGE_DEVIATIONS: readonly Deviation[] = [
135
+ {
136
+ id: 'wait-for-authentication-sheet',
137
+ summary:
138
+ 'waitForAuthentication can raise the grouped-permission sheet for a connected origin, which conflicts with BRC-219 "probes must not prompt"; only after the user has connected the site. Where the manifest group was previewed at connect (merged Connect sheet), Connect mints it and this call no longer prompts; it prompts only for a manifest that has since gained items or when minting failed.'
139
+ },
140
+ {
141
+ id: 'list-actions-deadline',
142
+ summary:
143
+ 'External listActions is subject to the vault guard\'s 30 s deadline and shared 16-slot queue (pre-existing); conflicts with BRC-219 "no deadline" for that method only.'
144
+ },
145
+ {
146
+ id: 'sdk-http-json-clients',
147
+ summary: 'SDK 2.8 HTTP JSON clients keep the message only for codes 5, 6 and 7 and reject isAuthenticated false.'
148
+ },
149
+ {
150
+ id: 'unverified-namespace',
151
+ summary:
152
+ 'Unattested originators are rewritten into the .<grantTag>.unverified.invalid namespace: wallet-side BRC-116 policy, loopback only, never a future BRC-185 section 8 mobile profile.'
153
+ },
154
+ { id: 'request-cap', summary: 'Request and response caps are 5 MiB, not 64 MiB.' },
155
+ {
156
+ id: 'unsupported-contexts',
157
+ summary: 'Non-web asserted contexts and legacy epoch-less routes are not supported in project 1.'
158
+ },
159
+ {
160
+ id: 'approved-forging-app',
161
+ summary:
162
+ 'A user who approves a forging local app gets a fresh grant set plus everything the effective unverified policy leaves prompt-free; the reconnect token only stops silent reconnects, and the launch proof does not authenticate the website.'
163
+ },
164
+ {
165
+ id: 'sheet-slot',
166
+ summary:
167
+ 'An unanswered connection sheet holds its transport single slot until answered or its bindings close; a second new site on that transport gets RESOURCE_LIMIT. There is no deadline.'
168
+ },
169
+ {
170
+ id: 'basket-contents-shared',
171
+ summary:
172
+ 'Basket contents are not isolated between a site verified and unverified identities, or between connected sites, once basket access is granted.'
173
+ },
174
+ {
175
+ id: 'manifest-fetch-hermes',
176
+ summary:
177
+ 'The SDK private-address DNS check runs only on Node; on Hermes an unverified site claimed hostname resolving to a private address is fetched, bounded by TLS, the fixed URL and port and the special-use host list.'
178
+ },
179
+ {
180
+ id: 'token-module-routing-case',
181
+ summary:
182
+ 'Token-module routing is exact-case for attested callers (pre-existing); unverified bindings are covered by the dispatcher pre-scan.'
183
+ },
184
+ {
185
+ id: 'sheet-modal-flag',
186
+ summary:
187
+ 'executeGrant and handleDeny close the kind modal flag unconditionally, which can strand a queued request of the same kind (pre-existing).'
188
+ }
189
+ ]
190
+
191
+ const METHOD_DEVIATIONS: Partial<Record<WalletMethodName, string[]>> = {
192
+ waitForAuthentication: ['wait-for-authentication-sheet'],
193
+ listActions: ['list-actions-deadline'],
194
+ isAuthenticated: ['sdk-http-json-clients']
195
+ }
196
+
197
+ export function buildConformanceReport(): ConformanceReport {
198
+ const methods = (Object.keys(BRIDGE_METHODS) as WalletMethodName[]).sort().map(name => ({
199
+ name,
200
+ handling: BRIDGE_METHODS[name].probe ? ('probe' as const) : ('wallet' as const),
201
+ mutating: BRIDGE_METHODS[name].mutating,
202
+ deviations: METHOD_DEVIATIONS[name] ?? []
203
+ }))
204
+ return {
205
+ reportVersion: CONFORMANCE_REPORT_VERSION,
206
+ protocol: 'BRC-185',
207
+ spec: { document: '2026-10-27-browser-bridge-core-design', revision: 5 },
208
+ methods,
209
+ limits: {
210
+ maxRequestBytes: MAX_BRIDGE_REQUEST_BYTES,
211
+ maxInFlightPerBinding: MAX_IN_FLIGHT_PER_BINDING,
212
+ maxInFlightTotal: MAX_IN_FLIGHT_TOTAL,
213
+ maxInFlightBytes: MAX_IN_FLIGHT_BYTES,
214
+ maxBindingsPerOrigin: MAX_BINDINGS_PER_ORIGIN,
215
+ maxBindingsTotal: MAX_BINDINGS_TOTAL,
216
+ inboxMaxValidityMs: INBOX_MAX_VALIDITY_MS,
217
+ declineBackoffMs: DECLINE_BACKOFF_MS
218
+ },
219
+ refusals: BRIDGE_REFUSALS.map(r => ({ ...r })),
220
+ deviations: BRIDGE_DEVIATIONS.map(d => ({ ...d }))
221
+ }
222
+ }