@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,494 @@
1
+ /**
2
+ * Site consent (spec 6.4): which websites the user has connected, per profile and per
3
+ * attestation, the reconnect token that lets a remembered unverified site return silently, and
4
+ * the clean slate every new approval starts from.
5
+ *
6
+ * Stateful but transport-free: the dispatcher parks requests and calls `requestConsent`, the
7
+ * PermissionSheet reads `listPending` and answers by `requestId`. The store knows nothing about
8
+ * bindings beyond the opaque epoch strings it is handed.
9
+ *
10
+ * Records are HMAC-tagged by the admin-scoped wallet under the reserved `bridge site authority`
11
+ * namespace (the XR-027 / `connectionAuthority.ts` pattern), so a raw storage edit cannot plant
12
+ * a connected site. A record whose tag fails to verify is simply not connected.
13
+ */
14
+ import { Hash, type WalletInterface } from '@bsv/sdk'
15
+ import { b64uDecode, b64uEncode } from './protocol/base64url'
16
+ import { DECLINE_BACKOFF_MS, RECONNECT_TOKEN_BYTES } from './protocol/limits'
17
+ import type { Attestation } from './protocol/origin'
18
+ import { BRIDGE_SITE_AUTHORITY_PROTOCOL_ID } from './permissionPolicy'
19
+ import type { GroupPermissions } from '../services/signingPermissionPolicy'
20
+ import { mintGrantTag, unverifiedOriginator } from './unverifiedOriginator'
21
+
22
+ export type { GroupPermissions }
23
+
24
+ export type HmacCapableWallet = Pick<WalletInterface, 'createHmac' | 'verifyHmac'>
25
+
26
+ /** The subset of AsyncStorage the store needs. */
27
+ export interface KeyValue {
28
+ getItem(key: string): Promise<string | null>
29
+ setItem(key: string, value: string): Promise<void>
30
+ removeItem(key: string): Promise<void>
31
+ getAllKeys(): Promise<readonly string[]>
32
+ }
33
+
34
+ export interface SiteRecord {
35
+ applicationOrigin: string
36
+ originator: string
37
+ attestation: Attestation
38
+ transport: string
39
+ approvedAt: number
40
+ /** Unattested only: `g` + 10 base32 characters, minted at every approval. */
41
+ grantTag?: string
42
+ /** Unattested only: base64url SHA-256 of the reconnect token. The token itself is never stored. */
43
+ reconnectHash?: string
44
+ tag: string
45
+ }
46
+
47
+ export interface ConsentRequestInput {
48
+ origin: string
49
+ attestation: Attestation
50
+ transportId: string
51
+ bindingEpoch: string
52
+ walletRevision: number
53
+ /** The origin was approved before on this device, so the sheet says "Approving starts fresh". */
54
+ connectedBefore: boolean
55
+ /** The manifest group previewed for this origin, if any. Connect mints exactly this. */
56
+ groupPermissions?: GroupPermissions | null
57
+ }
58
+
59
+ /** What the sheet needs to show a pending `connection` request. */
60
+ export interface PendingConsent {
61
+ requestId: string
62
+ origin: string
63
+ attestation: Attestation
64
+ transportId: string
65
+ connectedBefore: boolean
66
+ walletRevision: number
67
+ profileKey: string
68
+ groupPermissions?: GroupPermissions | null
69
+ }
70
+
71
+ export interface ConsentAnswerContext {
72
+ walletRevision: number
73
+ profileKey: string
74
+ }
75
+
76
+ export interface ConsentStoreDeps {
77
+ storage: KeyValue
78
+ adminWallet: HmacCapableWallet
79
+ adminOriginator: string
80
+ profileKey: () => string
81
+ now: () => number
82
+ randomBytes: (n: number) => Uint8Array
83
+ /**
84
+ * Mints the previewed group as permission tokens under the site's originator, after the consent
85
+ * record is written. A failure is swallowed: the connection stands and the later group check
86
+ * falls back to the group sheet.
87
+ */
88
+ mint?: (originator: string, group: GroupPermissions) => Promise<void>
89
+ }
90
+
91
+ export interface ConnectedSite {
92
+ applicationOrigin: string
93
+ originator: string
94
+ attestation: Attestation
95
+ transport: string
96
+ approvedAt: number
97
+ }
98
+
99
+ export type ConsentOutcome = 'approved' | 'declined'
100
+
101
+ export interface ConsentStore {
102
+ lookup(origin: string, attestation: Attestation): Promise<SiteRecord | undefined>
103
+ /** Constant-time. Verified records need no token; an unattested record needs the matching one. */
104
+ checkReconnect(record: SiteRecord, token?: string): boolean
105
+ requestConsent(
106
+ input: ConsentRequestInput
107
+ ): { requestId: string; promise: Promise<ConsentOutcome> } | { refused: 'slot-held' | 'backoff' }
108
+ answerConsent(
109
+ requestId: string,
110
+ approve: boolean,
111
+ ctx: ConsentAnswerContext
112
+ ): Promise<{ record: SiteRecord; reconnectToken?: string; epochs: string[] } | undefined>
113
+ dropRequestsFor(epoch: string): void
114
+ withdrawAll(): void
115
+ listPending(): PendingConsent[]
116
+ listConnectedSites(): Promise<ConnectedSite[]>
117
+ /** Deletes the record only; closing the origin's live bindings with `revoked` is the caller's job. */
118
+ revokeSite(origin: string, attestation: Attestation): Promise<void>
119
+ onChange(fn: () => void): () => void
120
+ }
121
+
122
+ const STORE_PREFIX = 'bsv-bridge-sites'
123
+ const storeKey = (profileKey: string) => `${STORE_PREFIX}:${profileKey}`
124
+ const TAG_DOMAIN = 'bsv-wallet-bridge-site-record-v1'
125
+ const ORIGIN_RE = /^https?:\/\/([^/:]+)(?::\d+)?$/
126
+
127
+ /** Removes every profile's connected-sites key, including a bare profile 0 key. Run at logout and Delete Wallet. */
128
+ export async function sweepConsentStorage(storage: Pick<KeyValue, 'getAllKeys' | 'removeItem'>): Promise<void> {
129
+ const keys = await storage.getAllKeys()
130
+ for (const k of keys) {
131
+ if (k === STORE_PREFIX || k.startsWith(`${STORE_PREFIX}:`)) await storage.removeItem(k)
132
+ }
133
+ }
134
+
135
+ type Unsigned = Omit<SiteRecord, 'tag'>
136
+
137
+ function recordMessage(profileKey: string, r: Unsigned): number[] {
138
+ // A JSON array has one unambiguous encoding, so no field can bleed into its neighbour.
139
+ return Array.from(
140
+ new TextEncoder().encode(
141
+ JSON.stringify([
142
+ TAG_DOMAIN,
143
+ profileKey,
144
+ r.applicationOrigin,
145
+ r.originator,
146
+ r.attestation,
147
+ r.transport,
148
+ r.approvedAt,
149
+ r.grantTag ?? '',
150
+ r.reconnectHash ?? ''
151
+ ])
152
+ )
153
+ )
154
+ }
155
+
156
+ const recordKeyId = (origin: string, attestation: Attestation) => `site:${attestation}:${origin}`
157
+
158
+ function isRecordShape(v: unknown): v is SiteRecord {
159
+ if (v === null || typeof v !== 'object') return false
160
+ const r = v as Record<string, unknown>
161
+ return (
162
+ typeof r.applicationOrigin === 'string' &&
163
+ typeof r.originator === 'string' &&
164
+ (r.attestation === 'browser' || r.attestation === 'unattested') &&
165
+ typeof r.transport === 'string' &&
166
+ typeof r.approvedAt === 'number' &&
167
+ (r.grantTag === undefined || typeof r.grantTag === 'string') &&
168
+ (r.reconnectHash === undefined || typeof r.reconnectHash === 'string') &&
169
+ typeof r.tag === 'string'
170
+ )
171
+ }
172
+
173
+ function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {
174
+ if (a.length !== b.length) return false
175
+ let diff = 0
176
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]
177
+ return diff === 0
178
+ }
179
+
180
+ interface Pending extends PendingConsent {
181
+ epochs: Set<string>
182
+ settle: (o: ConsentOutcome) => void
183
+ promise: Promise<ConsentOutcome>
184
+ answering: boolean
185
+ }
186
+
187
+ export function createConsentStore(deps: ConsentStoreDeps): ConsentStore {
188
+ const { storage, adminWallet, adminOriginator } = deps
189
+ const pending = new Map<string, Pending>()
190
+ const slotByTransport = new Map<string, string>()
191
+ const declinedAt = new Map<string, number>()
192
+ const listeners = new Set<() => void>()
193
+ let nextId = 0
194
+ // Store writes read-modify-write one key; serializing them keeps two approvals from clobbering each other.
195
+ let writeChain: Promise<unknown> = Promise.resolve()
196
+ const serial = <T>(fn: () => Promise<T>): Promise<T> => {
197
+ const run = writeChain.then(fn, fn)
198
+ writeChain = run.catch(() => undefined)
199
+ return run
200
+ }
201
+
202
+ const notify = () => {
203
+ for (const fn of [...listeners]) {
204
+ try {
205
+ fn()
206
+ } catch {
207
+ // A listener must not stop the others.
208
+ }
209
+ }
210
+ }
211
+ const siteKey = (origin: string, attestation: Attestation) => `${attestation}|${origin}`
212
+
213
+ async function readRecords(profileKey: string): Promise<SiteRecord[]> {
214
+ try {
215
+ const raw = await storage.getItem(storeKey(profileKey))
216
+ if (raw === null) return []
217
+ const parsed = JSON.parse(raw) as { records?: unknown }
218
+ return Array.isArray(parsed?.records) ? parsed.records.filter(isRecordShape) : []
219
+ } catch {
220
+ return []
221
+ }
222
+ }
223
+
224
+ async function tagFor(profileKey: string, r: Unsigned): Promise<string> {
225
+ const { hmac } = await adminWallet.createHmac(
226
+ {
227
+ protocolID: BRIDGE_SITE_AUTHORITY_PROTOCOL_ID,
228
+ keyID: recordKeyId(r.applicationOrigin, r.attestation),
229
+ counterparty: 'self',
230
+ data: recordMessage(profileKey, r)
231
+ },
232
+ adminOriginator
233
+ )
234
+ return b64uEncode(Uint8Array.from(hmac))
235
+ }
236
+
237
+ async function isAuthentic(profileKey: string, r: SiteRecord): Promise<boolean> {
238
+ try {
239
+ const { valid } = await adminWallet.verifyHmac(
240
+ {
241
+ protocolID: BRIDGE_SITE_AUTHORITY_PROTOCOL_ID,
242
+ keyID: recordKeyId(r.applicationOrigin, r.attestation),
243
+ counterparty: 'self',
244
+ data: recordMessage(profileKey, r),
245
+ hmac: Array.from(b64uDecode(r.tag))
246
+ },
247
+ adminOriginator
248
+ )
249
+ return valid === true
250
+ } catch {
251
+ // verifyHmac rejects on a mismatch; a locked wallet or a malformed tag land here too.
252
+ return false
253
+ }
254
+ }
255
+
256
+ async function lookup(origin: string, attestation: Attestation): Promise<SiteRecord | undefined> {
257
+ const profileKey = deps.profileKey()
258
+ const found = (await readRecords(profileKey)).find(
259
+ r => r.applicationOrigin === origin && r.attestation === attestation
260
+ )
261
+ if (found === undefined) return undefined
262
+ return (await isAuthentic(profileKey, found)) ? found : undefined
263
+ }
264
+
265
+ function checkReconnect(record: SiteRecord, token?: string): boolean {
266
+ if (record.attestation !== 'unattested') return true
267
+ if (typeof token !== 'string' || token.length === 0 || record.reconnectHash === undefined) return false
268
+ try {
269
+ const presented = b64uDecode(token)
270
+ if (presented.length !== RECONNECT_TOKEN_BYTES) return false
271
+ const hash = Uint8Array.from(Hash.sha256(Array.from(presented)))
272
+ return constantTimeEqual(hash, b64uDecode(record.reconnectHash))
273
+ } catch {
274
+ return false
275
+ }
276
+ }
277
+
278
+ function remove(p: Pending): void {
279
+ pending.delete(p.requestId)
280
+ // Joining transports hold a slot on this request too, so clear every one that points at it.
281
+ for (const [transportId, held] of [...slotByTransport]) {
282
+ if (held === p.requestId) slotByTransport.delete(transportId)
283
+ }
284
+ }
285
+
286
+ function requestConsent(input: ConsentRequestInput) {
287
+ const key = siteKey(input.origin, input.attestation)
288
+ // One request per origin and attestation: a second binding joins the sheet already waiting.
289
+ for (const p of pending.values()) {
290
+ if (p.origin === input.origin && p.attestation === input.attestation) {
291
+ const held = slotByTransport.get(input.transportId)
292
+ if (held !== undefined && held !== p.requestId) return { refused: 'slot-held' as const }
293
+ slotByTransport.set(input.transportId, p.requestId)
294
+ p.epochs.add(input.bindingEpoch)
295
+ return { requestId: p.requestId, promise: p.promise }
296
+ }
297
+ }
298
+ const declined = declinedAt.get(key)
299
+ if (declined !== undefined) {
300
+ if (deps.now() - declined < DECLINE_BACKOFF_MS) return { refused: 'backoff' as const }
301
+ declinedAt.delete(key)
302
+ }
303
+ if (slotByTransport.has(input.transportId)) return { refused: 'slot-held' as const }
304
+ const requestId = `c${++nextId}-${b64uEncode(deps.randomBytes(9))}`
305
+ let settle!: (o: ConsentOutcome) => void
306
+ const promise = new Promise<ConsentOutcome>(res => (settle = res))
307
+ const p: Pending = {
308
+ requestId,
309
+ origin: input.origin,
310
+ attestation: input.attestation,
311
+ transportId: input.transportId,
312
+ connectedBefore: input.connectedBefore,
313
+ walletRevision: input.walletRevision,
314
+ profileKey: deps.profileKey(),
315
+ groupPermissions: input.groupPermissions ?? null,
316
+ epochs: new Set([input.bindingEpoch]),
317
+ settle,
318
+ promise,
319
+ answering: false
320
+ }
321
+ pending.set(requestId, p)
322
+ slotByTransport.set(input.transportId, requestId)
323
+ notify()
324
+ return { requestId, promise }
325
+ }
326
+
327
+ async function answerConsent(requestId: string, approve: boolean, ctx: ConsentAnswerContext) {
328
+ const p = pending.get(requestId)
329
+ if (p === undefined || p.answering) return undefined
330
+ if (p.walletRevision !== ctx.walletRevision || p.profileKey !== ctx.profileKey) return undefined
331
+ if (!approve) {
332
+ remove(p)
333
+ declinedAt.set(siteKey(p.origin, p.attestation), deps.now())
334
+ p.settle('declined')
335
+ notify()
336
+ return undefined
337
+ }
338
+ const host = ORIGIN_RE.exec(p.origin)?.[1]
339
+ if (host === undefined) return undefined
340
+ p.answering = true
341
+ const profileKey = p.profileKey
342
+ // The bindings parked behind this request, as of the answer (a closed one has already left).
343
+ const epochs = [...p.epochs]
344
+ let reconnectToken: string | undefined
345
+ try {
346
+ const unsigned: Unsigned = {
347
+ applicationOrigin: p.origin,
348
+ originator: host,
349
+ attestation: p.attestation,
350
+ transport: p.transportId,
351
+ approvedAt: deps.now()
352
+ }
353
+ if (p.attestation === 'unattested') {
354
+ // Clean slate: a fresh grant tag moves the site to a new originator, and a fresh token
355
+ // replaces the hash, so nothing earlier carries over.
356
+ unsigned.grantTag = mintGrantTag()
357
+ unsigned.originator = unverifiedOriginator(host, unsigned.grantTag)
358
+ const token = deps.randomBytes(RECONNECT_TOKEN_BYTES)
359
+ reconnectToken = b64uEncode(token)
360
+ unsigned.reconnectHash = b64uEncode(Uint8Array.from(Hash.sha256(Array.from(token))))
361
+ }
362
+ const recorded = await serial(async () => {
363
+ const existing = await readRecords(profileKey)
364
+ const tag = await tagFor(profileKey, unsigned)
365
+ // No await between this re-check and the write call: a wallet replacement or teardown
366
+ // that happened while the tag was computed already withdrew the request (the revision
367
+ // is fixed for this entry, so withdrawal is how it shows). A profile switch leaves the
368
+ // request pending, so drop it here.
369
+ if (pending.get(requestId) !== p) return undefined
370
+ if (deps.profileKey() !== profileKey) {
371
+ remove(p)
372
+ notify()
373
+ return undefined
374
+ }
375
+ const record: SiteRecord = { ...unsigned, tag }
376
+ const kept = existing.filter(r => !(r.applicationOrigin === p.origin && r.attestation === p.attestation))
377
+ const write = storage.setItem(storeKey(profileKey), JSON.stringify({ records: [...kept, record] }))
378
+ remove(p)
379
+ notify()
380
+ await write
381
+ return { record, reconnectToken, epochs }
382
+ })
383
+ if (recorded === undefined) return undefined
384
+ // After the record is written and before the page is told: the later group check then finds
385
+ // the tokens. Outside the write chain, so a slow mint does not hold up other approvals.
386
+ if (p.groupPermissions != null && deps.mint !== undefined) {
387
+ try {
388
+ await deps.mint(recorded.record.originator, p.groupPermissions)
389
+ } catch (e) {
390
+ console.warn('[bridge] minting the connect group failed', e instanceof Error ? e.message : String(e))
391
+ }
392
+ }
393
+ p.settle('approved')
394
+ return recorded
395
+ } catch {
396
+ // A locked wallet or a failed write: nothing was stored, so the site is not connected.
397
+ if (pending.get(requestId) === p) remove(p)
398
+ p.settle('declined')
399
+ notify()
400
+ return undefined
401
+ } finally {
402
+ p.answering = false
403
+ // No-op after an approval (already settled); every other exit leaves the request declined.
404
+ p.settle('declined')
405
+ }
406
+ }
407
+
408
+ function dropRequestsFor(epoch: string): void {
409
+ let changed = false
410
+ for (const p of [...pending.values()]) {
411
+ if (!p.epochs.delete(epoch) || p.epochs.size > 0) continue
412
+ remove(p)
413
+ p.settle('declined')
414
+ changed = true
415
+ }
416
+ if (changed) notify()
417
+ }
418
+
419
+ function withdrawAll(): void {
420
+ const all = [...pending.values()]
421
+ pending.clear()
422
+ slotByTransport.clear()
423
+ for (const p of all) p.settle('declined')
424
+ if (all.length > 0) notify()
425
+ }
426
+
427
+ const listPending = (): PendingConsent[] =>
428
+ [...pending.values()].map(
429
+ ({
430
+ requestId,
431
+ origin,
432
+ attestation,
433
+ transportId,
434
+ connectedBefore,
435
+ walletRevision,
436
+ profileKey,
437
+ groupPermissions
438
+ }) => ({
439
+ requestId,
440
+ origin,
441
+ attestation,
442
+ transportId,
443
+ connectedBefore,
444
+ walletRevision,
445
+ profileKey,
446
+ groupPermissions
447
+ })
448
+ )
449
+
450
+ async function listConnectedSites(): Promise<ConnectedSite[]> {
451
+ const profileKey = deps.profileKey()
452
+ const out: ConnectedSite[] = []
453
+ for (const r of await readRecords(profileKey)) {
454
+ if (!(await isAuthentic(profileKey, r))) continue
455
+ out.push({
456
+ applicationOrigin: r.applicationOrigin,
457
+ originator: r.originator,
458
+ attestation: r.attestation,
459
+ transport: r.transport,
460
+ approvedAt: r.approvedAt
461
+ })
462
+ }
463
+ return out
464
+ }
465
+
466
+ async function revokeSite(origin: string, attestation: Attestation): Promise<void> {
467
+ const profileKey = deps.profileKey()
468
+ await serial(async () => {
469
+ const records = await readRecords(profileKey)
470
+ const kept = records.filter(r => !(r.applicationOrigin === origin && r.attestation === attestation))
471
+ if (kept.length === records.length) return
472
+ await storage.setItem(storeKey(profileKey), JSON.stringify({ records: kept }))
473
+ notify()
474
+ })
475
+ }
476
+
477
+ return {
478
+ lookup,
479
+ checkReconnect,
480
+ requestConsent,
481
+ answerConsent,
482
+ dropRequestsFor,
483
+ withdrawAll,
484
+ listPending,
485
+ listConnectedSites,
486
+ revokeSite,
487
+ onChange(fn) {
488
+ listeners.add(fn)
489
+ return () => {
490
+ listeners.delete(fn)
491
+ }
492
+ }
493
+ }
494
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The seam between the consent store and the PermissionSheet's `connection` kind (spec 6.4).
3
+ *
4
+ * The store is created by whoever composes the bridge (the dispatcher's `consent` dependency);
5
+ * the sheet only needs to read its pending requests, answer them and know which flags apply. The
6
+ * host registers the store here once. Without a registered source the sheet shows no connection
7
+ * requests, which is also what a wallet with no bridge should do.
8
+ *
9
+ * Approval is answered here, not in the UI, so the reconnect token reaches the transport in the
10
+ * same place whichever surface approved: the token is minted once, handed over once, and never
11
+ * kept (6.4).
12
+ */
13
+ import type { ConsentAnswerContext, ConsentStore, PendingConsent } from './consent'
14
+ import { effectiveUnverified, resolvePermissionPolicy, type PermissionPolicy, type SeekFlags } from './permissionPolicy'
15
+ import type { Attestation } from './protocol/origin'
16
+
17
+ export interface ConsentSheetSource {
18
+ store: Pick<ConsentStore, 'listPending' | 'answerConsent' | 'onChange'>
19
+ /** The current wallet revision and profile: an answer carries them so a stale one is dropped. */
20
+ context(): ConsentAnswerContext
21
+ /** The effective policy (host statement plus the user's stored policy). Defaults to the host's. */
22
+ policy?(): PermissionPolicy
23
+ }
24
+
25
+ let source: ConsentSheetSource | undefined
26
+ let detach: (() => void) | undefined
27
+ let snapshot: PendingConsent[] = []
28
+ const listeners = new Set<() => void>()
29
+
30
+ function refresh(): void {
31
+ snapshot = source === undefined ? [] : source.store.listPending()
32
+ for (const fn of [...listeners]) {
33
+ try {
34
+ fn()
35
+ } catch {
36
+ // A listener must not stop the others.
37
+ }
38
+ }
39
+ }
40
+
41
+ export function setConsentSheetSource(next: ConsentSheetSource | undefined): void {
42
+ detach?.()
43
+ detach = undefined
44
+ source = next
45
+ if (next !== undefined) detach = next.store.onChange(refresh)
46
+ refresh()
47
+ }
48
+
49
+ /** For `useSyncExternalStore`: the snapshot only changes when the pending set does. */
50
+ export function subscribeConsentRequests(fn: () => void): () => void {
51
+ listeners.add(fn)
52
+ return () => {
53
+ listeners.delete(fn)
54
+ }
55
+ }
56
+
57
+ export function getPendingConnections(): PendingConsent[] {
58
+ return snapshot
59
+ }
60
+
61
+ /** The flags the connection sheet describes for a site of this attestation (spec 6.4, 6.5). */
62
+ export function connectionFlags(attestation: Attestation): SeekFlags {
63
+ const policy = source?.policy?.() ?? resolvePermissionPolicy()
64
+ return attestation === 'unattested' ? effectiveUnverified(policy) : policy.verified
65
+ }
66
+
67
+ /**
68
+ * Answers a pending connection request. Approve of an unverified site hands the new reconnect
69
+ * token, through its own transport, to each live binding that was parked behind this request; a
70
+ * transport that cannot take it (it never registered `deliverReconnectToken`) does not get one.
71
+ */
72
+ export async function answerConnection(requestId: string, approve: boolean): Promise<void> {
73
+ const src = source
74
+ if (src === undefined) return
75
+ const pending = src.store.listPending().find(p => p.requestId === requestId)
76
+ if (pending === undefined) return
77
+ const result = await src.store.answerConsent(requestId, approve, src.context())
78
+ if (result?.reconnectToken === undefined) return
79
+ // Loaded on demand: the runtime pulls in the secure-store native module, which the sheet itself
80
+ // (and its tests) must not need just to render a request.
81
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
82
+ const { getBindingRegistry, getTransport } = require('./runtime') as typeof import('./runtime')
83
+ // Only the bindings that were parked behind this request get the token, each through its own
84
+ // transport. A binding of the same origin that never asked (connected already, or another
85
+ // instance that has sent no interactive request) is not handed a credential for the site.
86
+ const waiting = new Set(result.epochs)
87
+ for (const b of getBindingRegistry().live()) {
88
+ if (!waiting.has(b.epoch) || b.applicationOrigin !== pending.origin) continue
89
+ if (b.attestation !== 'unattested') continue
90
+ const transport = getTransport(b.transportId)
91
+ if (transport?.deliverReconnectToken === undefined) continue
92
+ try {
93
+ transport.deliverReconnectToken(b, result.reconnectToken)
94
+ } catch (e) {
95
+ console.warn('[bridge] reconnect token delivery failed', e instanceof Error ? e.message : String(e))
96
+ }
97
+ }
98
+ }