@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
package/core/index.ts CHANGED
@@ -132,6 +132,8 @@ export * from './directpay/deviceStore'
132
132
  export * from './directpay/receive'
133
133
  export * from './directpay/DirectPayManager'
134
134
  export * from './directpay/DirectPayProvider'
135
+ // The browser bridge's public API (BRC-185 core): see './bridge/index'.
136
+ export * from './bridge'
135
137
  export * from './peerpay/outbox'
136
138
  export * from './peerpay/control'
137
139
  export * from './peerpay/handleResendRequests'
@@ -249,6 +251,19 @@ export { processOfflineActions } from './storage/methods/processOfflineActions'
249
251
  export { colorHeldTxids, txHasColorOutput } from './mandala/colorGuard'
250
252
  export * from './storage/skipQueuedAncestors'
251
253
  export { prepareSqliteImageForDeserialize } from './storage/dbImage'
254
+ export {
255
+ encryptDbImage,
256
+ decryptDbImage,
257
+ isEncryptedDbImage,
258
+ EncryptedDbError,
259
+ ENCRYPTED_DB_EXTENSION,
260
+ DB_EXPORT_PROTOCOL,
261
+ type DbExportWallet,
262
+ type EncryptedDbErrorCode,
263
+ type EncryptedDbOptions,
264
+ type ByteSource,
265
+ type ByteSink
266
+ } from './storage/encryptedDbImage'
252
267
 
253
268
  // Local secrets storage
254
269
  export {
@@ -18,9 +18,11 @@
18
18
  * ledger to persistent storage.
19
19
  */
20
20
 
21
+ import { isUnattestedOriginator } from '../bridge/unverifiedOriginator'
22
+
21
23
  const DAY_MS = 24 * 60 * 60 * 1000
22
24
 
23
- export type AutoApproveReason = 'over-threshold' | 'cooldown' | 'daily-cap' | null
25
+ export type AutoApproveReason = 'over-threshold' | 'cooldown' | 'daily-cap' | 'unattested' | null
24
26
 
25
27
  export interface AutoApproveDecision {
26
28
  approve: boolean
@@ -70,6 +72,9 @@ export function createAutoApprovePolicy(deps: AutoApprovePolicyDeps): AutoApprov
70
72
 
71
73
  return {
72
74
  shouldAutoApprove({ originator, satoshis }) {
75
+ // An unverified origin may be a local app forging a remembered site: spending always asks.
76
+ if (isUnattestedOriginator(originator)) return { approve: false, reason: 'unattested' }
77
+
73
78
  const threshold = deps.threshold()
74
79
  if (!(threshold > 0) || satoshis > threshold) {
75
80
  return { approve: false, reason: 'over-threshold' }
@@ -89,6 +94,7 @@ export function createAutoApprovePolicy(deps: AutoApprovePolicyDeps): AutoApprov
89
94
  },
90
95
 
91
96
  record({ originator, satoshis, at }) {
97
+ if (isUnattestedOriginator(originator)) return
92
98
  lastApproveAtByOriginator.set(originator, at)
93
99
  ledger.push({ originator, satoshis, at })
94
100
  pruneLedger(at)
@@ -50,7 +50,7 @@ export class WalletArgTooLarge extends Error {
50
50
  * caller that supplies its own limits never touches it at all, and a failure to
51
51
  * read the tier falls back to 'mid' rather than leaving the surface uncapped.
52
52
  */
53
- function tierLimits(): WalletArgLimits {
53
+ export function tierLimits(): WalletArgLimits {
54
54
  try {
55
55
  // eslint-disable-next-line @typescript-eslint/no-require-imports
56
56
  const { getDeviceTier } = require('../deviceTier') as typeof import('../deviceTier')
@@ -67,6 +67,7 @@ const SIZED = new Set<keyof WalletInterface>([
67
67
  'createAction',
68
68
  'signAction',
69
69
  'internalizeAction',
70
+ 'acquireCertificate',
70
71
  'encrypt',
71
72
  'decrypt',
72
73
  'createHmac',
@@ -0,0 +1,132 @@
1
+ import type { SigningPolicyPermissionsManager } from './signingPermissionPolicy'
2
+
3
+ /** A token module's prompt function (BTMS `promptHandler`, Mandala `requestTokenAccess`). */
4
+ export type TokenPromptHandler = (originator: string, message: string) => Promise<boolean>
5
+
6
+ /**
7
+ * Ties a token-module prompt function to the build that created it. Once the
8
+ * build's manager is retired the wrapper resolves `false` without enqueueing,
9
+ * so a module call that was already inside `onRequest` (mid-lookup) when the
10
+ * wallet was replaced ends with its usual denial instead of raising a sheet
11
+ * for a wallet that is gone. The flag is set in the same synchronous step as
12
+ * `manager.retire()`. A check in the module's `onRequest` wrapper would not be
13
+ * enough: a call already inside it has passed that check.
14
+ */
15
+ export function guardTokenPromptHandlers(handlers: { btms: TokenPromptHandler; mandala: TokenPromptHandler }): {
16
+ btms: TokenPromptHandler
17
+ mandala: TokenPromptHandler
18
+ /** Hand to `manager.onRetire`. */
19
+ retire: () => void
20
+ } {
21
+ let retired = false
22
+ const guarded = (handler: TokenPromptHandler): TokenPromptHandler => {
23
+ return (originator, message) => (retired ? Promise.resolve(false) : handler(originator, message))
24
+ }
25
+ return {
26
+ btms: guarded(handlers.btms),
27
+ mandala: guarded(handlers.mandala),
28
+ retire: () => {
29
+ retired = true
30
+ }
31
+ }
32
+ }
33
+
34
+ /** The places a withdrawal empties. */
35
+ export interface PromptSinks {
36
+ /** Queues whose items are answered through a manager (protocol, basket, certificate, spending, group). */
37
+ managerQueues: Array<{ clear: () => void }>
38
+ /** Queues whose items hold a promise (BTMS, Mandala); each is resolved `false`. */
39
+ tokenQueues: Array<{ clear: (onEach: (item: { resolve: (approved: boolean) => void }) => void) => void }>
40
+ /** Anything else holding a question for the user (pending connection requests). */
41
+ others: Iterable<() => void>
42
+ }
43
+
44
+ /**
45
+ * Withdraws every prompt that belonged to wallets that have gone. The old
46
+ * managers are retired FIRST, synchronously, so a call still parked inside one
47
+ * (on a manifest fetch, the grouped lock, a token lookup) cannot raise a prompt
48
+ * after the sweep; then every request they still hold is denied and every queue
49
+ * is emptied, which also closes the modals and gives focus back.
50
+ */
51
+ export function withdrawPrompts(oldManagers: SigningPolicyPermissionsManager[], sinks: PromptSinks): void {
52
+ for (const manager of oldManagers) manager.retire()
53
+ for (const manager of oldManagers) manager.denyAllActiveRequests()
54
+ for (const queue of sinks.managerQueues) queue.clear()
55
+ for (const queue of sinks.tokenQueues) queue.clear(item => item.resolve(false))
56
+ for (const other of sinks.others) {
57
+ try {
58
+ other()
59
+ } catch (error) {
60
+ console.warn('[permissions] withdrawing a prompt failed', error)
61
+ }
62
+ }
63
+ }
64
+
65
+ export interface SpendingPromptArgs {
66
+ requestID?: string
67
+ originator: string
68
+ reason?: string
69
+ renewal?: boolean
70
+ spending?: { satoshis: number; lineItems?: any[] }
71
+ }
72
+
73
+ export interface SpendingPromptDeps<Item> {
74
+ /** Re-reads the persisted auto-approve threshold (an AsyncStorage read). */
75
+ loadThreshold: () => Promise<void>
76
+ /** The auto-approve decision for this spend. */
77
+ decide: (originator: string, satoshis: number) => { approve: boolean; reason?: string | null }
78
+ /** Records an auto-approved spend in the ledger. */
79
+ recordAutoApproved: (originator: string, satoshis: number) => void
80
+ enqueue: (item: Item) => void
81
+ /** Only for a request that arrives without the manager it was raised on. */
82
+ currentManager: () => SigningPolicyPermissionsManager | undefined
83
+ }
84
+
85
+ /**
86
+ * The wallet's reaction to a spending-authorization request: auto-grant a small
87
+ * one, otherwise queue it for the sheet. `manager` is the one the request was
88
+ * raised on (the callback is bound per manager). The threshold read is async,
89
+ * so a withdrawal can land inside it; after it, and before the ledger record,
90
+ * the auto-grant or the enqueue, the manager must still hold the request, or
91
+ * the request is gone and nothing more happens. The auto-grant also targets
92
+ * that same manager: a replacement manager restarts its `spend:…:request:N`
93
+ * counter, so the current one must never be asked to grant an old ID.
94
+ */
95
+ export async function handleSpendingPrompt<Item>(
96
+ args: SpendingPromptArgs,
97
+ manager: SigningPolicyPermissionsManager | undefined,
98
+ deps: SpendingPromptDeps<Item>
99
+ ): Promise<void> {
100
+ const { requestID, originator, reason, renewal, spending } = args
101
+ if (!requestID || !spending) return
102
+
103
+ await deps.loadThreshold()
104
+ if (manager && !manager.hasActiveRequest(requestID)) return
105
+
106
+ const decision = deps.decide(originator, spending.satoshis)
107
+ if (decision.approve) {
108
+ deps.recordAutoApproved(originator, spending.satoshis)
109
+ if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
110
+ const target = manager ?? deps.currentManager()
111
+ target?.grantPermission({ requestID, ephemeral: true, amount: spending.satoshis }).catch(() => {})
112
+ return
113
+ }
114
+ if (__DEV__) {
115
+ console.log(
116
+ `[spend-auth] not eligible (${decision.reason}) → manual modal requestID=${requestID} sats=${spending.satoshis}`
117
+ )
118
+ }
119
+
120
+ deps.enqueue({
121
+ requestID,
122
+ originator,
123
+ description: reason,
124
+ transactionAmount: 0,
125
+ totalPastSpending: 0,
126
+ amountPreviouslyAuthorized: 0,
127
+ authorizationAmount: spending.satoshis,
128
+ renewal,
129
+ lineItems: spending.lineItems || [],
130
+ manager
131
+ } as Item)
132
+ }
@@ -1,5 +1,8 @@
1
1
  import { Hash, Utils } from '@bsv/sdk'
2
- import { WalletPermissionsManager } from '@bsv/wallet-toolbox-mobile'
2
+ import { WalletPermissionsManager, type GroupedPermissions } from '@bsv/wallet-toolbox-mobile'
3
+
4
+ /** A site's manifest group request (BRC-73), as the Connect sheet shows it and `mintGroupedPermissions` mints it. */
5
+ export type GroupPermissions = GroupedPermissions
3
6
 
4
7
  /**
5
8
  * Protocols a connected app may sign under without a protocol prompt, even
@@ -92,8 +95,88 @@ interface ManagerInternals {
92
95
  firePermissionRequestEvent(request: ProtocolRequest, key: string): Promise<void>
93
96
  underlying: { verifySignature: WalletPermissionsManager['verifySignature'] }
94
97
  fetchManifestPermissions(originator: string): Promise<ManifestPermissions>
98
+ callEvent(eventName: string, param: unknown): Promise<void>
99
+ denyActiveRequest(requestID: string): void
100
+ filterAlreadyGrantedPermissions(originator: string, group: GroupPermissions): Promise<GroupPermissions>
101
+ buildOriginatorLookupValues(displayOriginator: string | undefined, originator: string): unknown
102
+ persistPermissionGrant(toCreate: MintItem[], toRenew: MintItem[]): Promise<void>
103
+ }
104
+
105
+ /** One permission token to create or renew, as `persistPermissionGrant` takes it. */
106
+ interface MintItem {
107
+ request: Record<string, unknown>
108
+ expiry: number
109
+ amount?: number
110
+ oldToken?: unknown
95
111
  }
96
112
 
113
+ const str = (v: unknown): string => (typeof v === 'string' ? v : '')
114
+ const isObject = (v: unknown): v is Record<string, any> => v !== null && typeof v === 'object' && !Array.isArray(v)
115
+
116
+ /**
117
+ * The manifest group as a well-formed GroupPermissions, or null when it lists nothing. A site writes
118
+ * the manifest, so every entry is checked: one that does not have the shape the manager reads is
119
+ * left out, and what remains is both what the Connect sheet shows and what Connect mints.
120
+ */
121
+ function sanitizeGroup(raw: unknown): GroupPermissions | null {
122
+ if (!isObject(raw)) return null
123
+ const group: GroupPermissions = {}
124
+ if (typeof raw.description === 'string') group.description = raw.description
125
+ const spending = raw.spendingAuthorization
126
+ if (isObject(spending) && Number.isSafeInteger(spending.amount) && spending.amount > 0) {
127
+ group.spendingAuthorization = { amount: spending.amount, description: str(spending.description) }
128
+ }
129
+ const list = (v: unknown): any[] => (Array.isArray(v) ? v.filter(isObject) : [])
130
+ group.protocolPermissions = list(raw.protocolPermissions)
131
+ .filter(
132
+ p =>
133
+ Array.isArray(p.protocolID) &&
134
+ p.protocolID.length === 2 &&
135
+ [0, 1, 2].includes(p.protocolID[0]) &&
136
+ typeof p.protocolID[1] === 'string' &&
137
+ (p.counterparty === undefined || typeof p.counterparty === 'string')
138
+ )
139
+ .map(p => ({
140
+ protocolID: [p.protocolID[0], p.protocolID[1]] as [0 | 1 | 2, string],
141
+ ...(p.counterparty !== undefined ? { counterparty: p.counterparty as string } : {}),
142
+ description: str(p.description)
143
+ }))
144
+ group.basketAccess = list(raw.basketAccess)
145
+ .filter(b => typeof b.basket === 'string' && b.basket.length > 0)
146
+ .map(b => ({ basket: b.basket as string, description: str(b.description) }))
147
+ group.certificateAccess = list(raw.certificateAccess)
148
+ .filter(
149
+ c =>
150
+ typeof c.type === 'string' &&
151
+ typeof c.verifierPublicKey === 'string' &&
152
+ Array.isArray(c.fields) &&
153
+ c.fields.every((f: unknown) => typeof f === 'string')
154
+ )
155
+ .map(c => ({
156
+ type: c.type as string,
157
+ fields: [...c.fields] as string[],
158
+ verifierPublicKey: c.verifierPublicKey as string,
159
+ description: str(c.description)
160
+ }))
161
+ const empty =
162
+ group.spendingAuthorization === undefined &&
163
+ !group.protocolPermissions.length &&
164
+ !group.basketAccess.length &&
165
+ !group.certificateAccess.length
166
+ return empty ? null : group
167
+ }
168
+
169
+ /** The events that put a question to the user (all carry a `requestID`). A
170
+ * retired manager denies these instead of raising them. */
171
+ const PROMPT_EVENTS = new Set([
172
+ 'onProtocolPermissionRequested',
173
+ 'onBasketAccessRequested',
174
+ 'onCertificateAccessRequested',
175
+ 'onSpendingAuthorizationRequested',
176
+ 'onGroupedPermissionRequested',
177
+ 'onCounterpartyPermissionRequested'
178
+ ])
179
+
97
180
  /** The parts of a site's manifest.json permissions the manager reads. */
98
181
  interface ManifestPermissions {
99
182
  groupPermissions: { protocolPermissions?: Array<{ protocolID?: unknown }> } | null
@@ -134,7 +217,10 @@ function withoutAskEveryTime(manifest: ManifestPermissions): ManifestPermissions
134
217
  * cover is ever read back for them; a site's manifest never puts them in a
135
218
  * grouped request; and one origin's createSignature calls under them run
136
219
  * one at a time, so a burst of calls cannot ride on one approval;
137
- * - a non-privileged verifySignature is never prompted.
220
+ * - a non-privileged verifySignature is never prompted;
221
+ * - once retired (its wallet was replaced), it raises no prompt: every prompt
222
+ * event is denied on the spot, so a call still parked inside it ends instead
223
+ * of surfacing a sheet for a wallet that is gone.
138
224
  * Every other check runs unchanged.
139
225
  */
140
226
  export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
@@ -142,6 +228,8 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
142
228
  /** Key ID of the ask-every-time createSignature call each (normalized)
143
229
  * origin has in flight. The per-origin queue keeps it to one at a time. */
144
230
  private readonly keyIDInFlight = new Map<string, string>()
231
+ private retired = false
232
+ private readonly retireHooks: Array<() => void> = []
145
233
 
146
234
  constructor(...args: ConstructorParameters<typeof WalletPermissionsManager>) {
147
235
  super(...args)
@@ -177,6 +265,22 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
177
265
  }
178
266
  return await firePermissionRequestEvent(request, key)
179
267
  }
268
+ // Deny, never throw: a throw out of callEvent would leave the entry its
269
+ // caller registered unsettled (its waiter hangs, and a grouped one holds
270
+ // the per-originator lock). Denying settles the waiter and removes it.
271
+ const callEvent = internals.callEvent.bind(this)
272
+ internals.callEvent = async (eventName, param) => {
273
+ const requestID = (param as { requestID?: unknown } | null | undefined)?.requestID
274
+ if (this.retired && PROMPT_EVENTS.has(eventName) && typeof requestID === 'string') {
275
+ try {
276
+ internals.denyActiveRequest.call(this, requestID)
277
+ } catch {
278
+ // Already settled.
279
+ }
280
+ return
281
+ }
282
+ await callEvent(eventName, param)
283
+ }
180
284
  const fetchManifestPermissions = internals.fetchManifestPermissions.bind(this)
181
285
  internals.fetchManifestPermissions = async originator =>
182
286
  withoutAskEveryTime(await fetchManifestPermissions(originator))
@@ -186,6 +290,130 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
186
290
  return this as unknown as ManagerInternals
187
291
  }
188
292
 
293
+ /**
294
+ * One-way: from here on this manager raises no prompt. Call it only on a
295
+ * manager that has been replaced, never on the one just published. `onRetire`
296
+ * hooks run in this same synchronous step.
297
+ */
298
+ retire(): void {
299
+ if (this.retired) return
300
+ this.retired = true
301
+ for (const hook of this.retireHooks.splice(0)) {
302
+ try {
303
+ hook()
304
+ } catch {
305
+ // A hook must not stop the others.
306
+ }
307
+ }
308
+ }
309
+
310
+ isRetired(): boolean {
311
+ return this.retired
312
+ }
313
+
314
+ /** Runs `hook` when this manager is retired (immediately if it already is). */
315
+ onRetire(hook: () => void): void {
316
+ if (this.retired) hook()
317
+ else this.retireHooks.push(hook)
318
+ }
319
+
320
+ /**
321
+ * The group this origin's manifest asks for, as the later group check will read it: the same
322
+ * `fetchManifestPermissions` and its 5-minute cache, with ask-every-time protocols already
323
+ * filtered (and, on the unverified manager, spending and token modules). Null when there is no
324
+ * manifest, it lists nothing, or the fetch fails. Raises no prompt.
325
+ */
326
+ async peekGroupPermissions(originator: string): Promise<GroupPermissions | null> {
327
+ try {
328
+ const { normalized } = this.internals.prepareOriginator(originator)
329
+ const { groupPermissions } = await this.internals.fetchManifestPermissions(normalized)
330
+ return sanitizeGroup(groupPermissions)
331
+ } catch {
332
+ return null
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Mints a permission token for every item of `group` that does not already hold one, the way
338
+ * `grantGroupedPermission` does for a granted item, but with no active request to answer. An
339
+ * expired token is renewed. Ask-every-time protocols are never minted. Throws if the mint fails;
340
+ * the caller decides what that means.
341
+ */
342
+ async mintGroupedPermissions(originator: string, group: GroupPermissions): Promise<void> {
343
+ const i = this.internals
344
+ const { normalized } = i.prepareOriginator(originator)
345
+ const wanted: GroupPermissions = {
346
+ ...group,
347
+ protocolPermissions: (group.protocolPermissions ?? []).filter(p => !isAskEveryTimeProtocol(p.protocolID))
348
+ }
349
+ const todo = await i.filterAlreadyGrantedPermissions(normalized, wanted)
350
+ const lookup = i.buildOriginatorLookupValues(originator, normalized)
351
+ const toCreate: MintItem[] = []
352
+ const toRenew: MintItem[] = []
353
+ if (todo.spendingAuthorization != null) {
354
+ toCreate.push({
355
+ request: {
356
+ type: 'spending',
357
+ originator: normalized,
358
+ spending: { satoshis: todo.spendingAuthorization.amount },
359
+ reason: todo.spendingAuthorization.description
360
+ },
361
+ expiry: 0,
362
+ amount: todo.spendingAuthorization.amount
363
+ })
364
+ }
365
+ for (const p of todo.protocolPermissions ?? []) {
366
+ const counterparty = (p.protocolID?.[0] ?? 0) === 1 ? '' : p.counterparty || 'self'
367
+ const request = {
368
+ type: 'protocol',
369
+ originator: normalized,
370
+ privileged: false,
371
+ protocolID: p.protocolID,
372
+ counterparty,
373
+ reason: p.description
374
+ }
375
+ const token = await i.findProtocolToken(normalized, false, p.protocolID, counterparty, true, lookup)
376
+ if (token == null) toCreate.push({ request, expiry: 0 })
377
+ else toRenew.push({ oldToken: token, request, expiry: 0 })
378
+ }
379
+ for (const b of todo.basketAccess ?? []) {
380
+ toCreate.push({
381
+ request: { type: 'basket', originator: normalized, basket: b.basket, reason: b.description },
382
+ expiry: 0
383
+ })
384
+ }
385
+ for (const c of todo.certificateAccess ?? []) {
386
+ toCreate.push({
387
+ request: {
388
+ type: 'certificate',
389
+ originator: normalized,
390
+ privileged: false,
391
+ certificate: { verifier: c.verifierPublicKey, certType: c.type, fields: c.fields },
392
+ reason: c.description
393
+ },
394
+ expiry: 0
395
+ })
396
+ }
397
+ if (toCreate.length === 0 && toRenew.length === 0) return
398
+ await i.persistPermissionGrant(toCreate, toRenew)
399
+ }
400
+
401
+ /** Whether a prompt with this ID is still waiting for an answer. */
402
+ hasActiveRequest(requestID: string): boolean {
403
+ return this.internals.activeRequests.has(requestID)
404
+ }
405
+
406
+ /** Denies every request still waiting for an answer. Never throws. */
407
+ denyAllActiveRequests(): void {
408
+ for (const requestID of [...this.internals.activeRequests.keys()]) {
409
+ try {
410
+ this.internals.denyActiveRequest(requestID)
411
+ } catch {
412
+ // Already settled.
413
+ }
414
+ }
415
+ }
416
+
189
417
  override async ensureProtocolPermission(args: EnsureProtocolPermissionArgs): Promise<boolean> {
190
418
  if (isPromptFreeSigning(args)) {
191
419
  // Still refuse a missing or malformed originator, as the full check
@@ -193,6 +193,11 @@ const CONNECTION_AUTHORITY_PROTOCOL_NAMES = new Set(['connection authority'])
193
193
  * RPC method, authenticating nothing. */
194
194
  const PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES = new Set(['pending abort authority'])
195
195
 
196
+ /** Browser bridge: the `bridge site authority` namespace tags site-consent records and the
197
+ * stored permission policy (core/bridge/permissionPolicy.ts). Reserved for the same reason as
198
+ * `connection authority`: a connected origin must not be able to mint or verify the tag. */
199
+ const BRIDGE_SITE_AUTHORITY_PROTOCOL_NAMES = new Set(['bridge site authority'])
200
+
196
201
  function matchesProtocolNamespace(args: unknown, names: Set<string>): boolean {
197
202
  if (args === null || typeof args !== 'object' || Array.isArray(args)) return false
198
203
  const protocolID = (args as { protocolID?: unknown }).protocolID
@@ -211,6 +216,10 @@ function requestsConnectionAuthorityProtocol(args: unknown): boolean {
211
216
  return matchesProtocolNamespace(args, CONNECTION_AUTHORITY_PROTOCOL_NAMES)
212
217
  }
213
218
 
219
+ function requestsBridgeSiteAuthorityProtocol(args: unknown): boolean {
220
+ return matchesProtocolNamespace(args, BRIDGE_SITE_AUTHORITY_PROTOCOL_NAMES)
221
+ }
222
+
214
223
  function requestsPendingAbortAuthorityProtocol(args: unknown): boolean {
215
224
  return matchesProtocolNamespace(args, PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES)
216
225
  }
@@ -703,6 +712,7 @@ export function guardVaultAccess<T extends WalletInterface>(
703
712
  requestsVaultProtocol(args) ||
704
713
  requestsConnectionAuthorityProtocol(args) ||
705
714
  requestsPendingAbortAuthorityProtocol(args) ||
715
+ requestsBridgeSiteAuthorityProtocol(args) ||
706
716
  requestsAddressRailKey(args))
707
717
  ) {
708
718
  return deny(String(method), originator)
@@ -101,7 +101,7 @@ export interface ArgRefusal {
101
101
  }
102
102
 
103
103
  /** Calls that can carry transaction bytes. Everything else passes untouched. */
104
- const SIZED_CALLS = new Set(['createAction', 'signAction', 'internalizeAction'])
104
+ const SIZED_CALLS = new Set(['createAction', 'signAction', 'internalizeAction', 'acquireCertificate'])
105
105
 
106
106
  /**
107
107
  * XR-026: these carry only small byte-array fields (a hash, a short
@@ -132,7 +132,10 @@ const refuse = (field: string, actual: number, limit: number, why?: string): Arg
132
132
  /** Bytes represented by a hex string, or 0 for anything that is not one. */
133
133
  const hexBytes = (v: unknown): number => (typeof v === 'string' ? Math.floor(v.length / 2) : 0)
134
134
 
135
- const arrayBytes = (v: unknown): number => (Array.isArray(v) ? v.length : 0)
135
+ // Typed arrays and ArrayBuffers are byte arrays too. An in-process caller can pass one, and
136
+ // counting it as zero would let a multi-megabyte inputBEEF past the cap.
137
+ const arrayBytes = (v: unknown): number =>
138
+ Array.isArray(v) ? v.length : ArrayBuffer.isView(v) || v instanceof ArrayBuffer ? v.byteLength : 0
136
139
 
137
140
  const asRecord = (v: unknown): Record<string, unknown> | null =>
138
141
  v != null && typeof v === 'object' ? (v as Record<string, unknown>) : null
@@ -176,6 +179,18 @@ export function checkWalletArgs(call: string, args: unknown, limits: WalletArgLi
176
179
  try {
177
180
  let total = 0
178
181
 
182
+ // ── acquireCertificate ──
183
+ // Carries only strings. Bound the sum of every field value, keyring value and URL by the
184
+ // aggregate, so a page cannot park megabytes in a certificate request.
185
+ if (call === 'acquireCertificate') {
186
+ const sum = (v: unknown): number => {
187
+ if (typeof v === 'string') return v.length
188
+ const r = asRecord(v)
189
+ return r ? Object.values(r).reduce<number>((n, x) => n + (typeof x === 'string' ? x.length : 0), 0) : 0
190
+ }
191
+ total += sum(a.fields) + sum(a.keyringForSubject) + sum(a.certifierUrl) + sum(a.privilegedReason)
192
+ }
193
+
179
194
  // ── internalizeAction ──
180
195
  if (call === 'internalizeAction') {
181
196
  const tx = arrayBytes(a.tx)