@bsv/expo-wallet-toolbox 0.21.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 (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  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/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -1,11 +1,22 @@
1
- import React, { useContext, useState, useCallback, useMemo, useEffect, useRef } from 'react'
2
- import { View, Text, StyleSheet, TouchableOpacity, ScrollView } from 'react-native'
1
+ import React, { useContext, useState, useCallback, useMemo, useEffect, useRef, useSyncExternalStore } from 'react'
2
+ import { View, Text, StyleSheet, TouchableOpacity, ScrollView, Platform, AppState } from 'react-native'
3
3
  import type { WalletPermissionsManager } from '@bsv/wallet-toolbox-mobile'
4
+ import type { SigningPolicyPermissionsManager } from '../../../core/services/signingPermissionPolicy'
4
5
  import Sheet from './Sheet'
5
6
  import PressableScale from './PressableScale'
6
7
  import { useTranslation } from 'react-i18next'
7
8
  import AmountDisplay from '../wallet/AmountDisplay'
8
9
  import { describeProtocolPrompt } from './protocolPrompt'
10
+ import type { PendingConsent } from '../../../core/bridge/consent'
11
+ import {
12
+ answerConnection,
13
+ connectionFlags,
14
+ getPendingConnections,
15
+ subscribeConsentRequests
16
+ } from '../../../core/bridge/consentSheetSource'
17
+ import { SEEK_FLAG_DISCLOSURE, SEEK_FLAG_KEYS, type SeekFlags } from '../../../core/bridge/permissionPolicy'
18
+ import { hostnameOfUnattested, isUnattestedOriginator } from '../../../core/bridge/unverifiedOriginator'
19
+ import { describeColorRequest, type ColorPromptType } from './colorPrompt'
9
20
  import {
10
21
  spacing,
11
22
  radii,
@@ -23,6 +34,22 @@ import {
23
34
  // ---------------------------------------------------------------------------
24
35
  const DEV_BTMS_PREVIEW = false
25
36
 
37
+ /** How long Authorize stays inert when a connection or unverified prompt reaches the head (spec 6.4). */
38
+ const managerTokens = new WeakMap<object, number>()
39
+ let managerTokenCount = 0
40
+ /** A stable small number per manager object, '-' for a prompt that has none. */
41
+ function managerToken(manager: unknown): string {
42
+ if (manager === null || typeof manager !== 'object') return '-'
43
+ let n = managerTokens.get(manager)
44
+ if (n === undefined) {
45
+ n = ++managerTokenCount
46
+ managerTokens.set(manager, n)
47
+ }
48
+ return String(n)
49
+ }
50
+
51
+ const TAP_PROTECTION_MS = 700
52
+
26
53
  // ---------------------------------------------------------------------------
27
54
  // @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
28
55
  // etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
@@ -44,7 +71,7 @@ function loadIonicons(): IoniconsComponent {
44
71
  // Types
45
72
  // ---------------------------------------------------------------------------
46
73
 
47
- type PermissionKind = 'protocol' | 'basket' | 'certificate' | 'spending' | 'group' | 'btms' | 'mandala'
74
+ type PermissionKind = 'protocol' | 'basket' | 'certificate' | 'spending' | 'group' | 'btms' | 'mandala' | 'connection'
48
75
 
49
76
  interface GroupProtocol {
50
77
  protocolID: [number, string]
@@ -78,6 +105,8 @@ type GrantedGroupPermissions = Parameters<WalletPermissionsManager['grantGrouped
78
105
  export interface ActivePermission {
79
106
  kind: PermissionKind
80
107
  requestID: string
108
+ /** The manager that raised the request: the one the answer goes to. */
109
+ manager?: SigningPolicyPermissionsManager
81
110
  originator: string
82
111
  title: string
83
112
  description: string
@@ -93,56 +122,109 @@ export interface ActivePermission {
93
122
  /** Group-specific sub-permissions. */
94
123
  groupPermissions?: GroupPermissions
95
124
  /**
96
- * XR-040: set when a `mandala_spend`/`mandala_credit` prompt's per-asset
97
- * `lines` could not be trusted to be the WHOLE request (absent, malformed,
98
- * empty, or past `MANDALA_MAX_PROMPT_LINES`) — every asset a single
99
- * approval would release has to be shown, and a request this sheet cannot
100
- * fully enumerate must never be approvable. `handleDeny` is unaffected;
101
- * only the Allow control reads this.
125
+ * XR-040 (carried to the color module): set when a token consent message
126
+ * could not be read in full (`describeColorRequest` returned null) — every
127
+ * asset a single approval would release has to be shown, and a request this
128
+ * sheet cannot fully enumerate must never be approvable. `handleDeny` is
129
+ * unaffected; only the Allow control reads this.
102
130
  */
103
131
  approvalBlocked?: boolean
132
+ /**
133
+ * The prompt came from a website the wallet could not verify (spec 6.5). `originator` then holds
134
+ * the plain hostname, with the `.<grantTag>.unverified.invalid` suffix already stripped.
135
+ */
136
+ unverified?: boolean
137
+ /** Text the website supplied about itself (a manifest). Shown quoted, after the wallet's own words. */
138
+ siteSays?: string
139
+ /** `connection` only: what the sheet tells the user connecting allows (spec 6.4). */
140
+ connection?: {
141
+ transportId: string
142
+ connectedBefore: boolean
143
+ /** i18n keys, in `SEEK_FLAG_KEYS` order. */
144
+ allows: string[]
145
+ asksFirst: string[]
146
+ /** i18n key of the payments line, absent when the payment flag is off and listed under `allows`. */
147
+ payments?: string
148
+ }
149
+ }
150
+
151
+ /** Always-visible copy for each color consent type, completing "<app> …". */
152
+ const COLOR_DESCRIPTIONS: Record<ColorPromptType, string> = {
153
+ color_send: 'wants to send tokens from your wallet',
154
+ color_signature: 'wants to sign with one of your token keys. Only approve if you just asked this app to move tokens',
155
+ color_access: 'wants to see your token holdings',
156
+ color_relinquish: 'wants to remove a token holding from your wallet'
104
157
  }
105
158
 
106
- /** One line of a `mandala_spend`/`mandala_credit` prompt's `lines[]` array,
107
- * as loosely as a JSON.parse of counterparty-adjacent data should be trusted. */
108
- interface MandalaPromptLine {
109
- assetId?: unknown
110
- sendAmount?: unknown
111
- changeAmount?: unknown
112
- creditAmount?: unknown
113
- tokenName?: unknown
114
- /** Pre-formatted, e.g. "25.00 USDX" — see `MandalaSpendLine`/`MandalaCreditLine`. */
115
- display?: unknown
159
+ /** What the sheet needs to render color consent messages. */
160
+ export interface ColorPromptDeps {
161
+ t: (key: string, o?: object) => string
162
+ /** Host-resolved, untrusted display metadata; undefined ⇒ exact base units. */
163
+ assetInfo: (assetId: string) => { ticker: string; decimals: number } | undefined
116
164
  }
117
165
 
166
+ const NO_COLOR_DEPS: ColorPromptDeps = { t: key => key, assetInfo: () => undefined }
167
+
168
+ // ---------------------------------------------------------------------------
169
+ // Helpers
170
+ // ---------------------------------------------------------------------------
171
+
118
172
  /**
119
- * A sane display ceiling for a multi-asset Mandala prompt. Every real prompt
120
- * this app's own `MandalaTokenModule` builds groups by assetId — a handful at
121
- * most — so a `lines` array past this is either a bug or a bad-faith caller,
122
- * either way not something to enumerate as if it were the whole request.
173
+ * The originator a prompt shows. An unverified site reaches the wallet as
174
+ * `<hostname>.<grantTag>.unverified.invalid`; the user sees the hostname and the badge, never the suffix.
123
175
  */
124
- const MANDALA_MAX_PROMPT_LINES = 25
176
+ function presentOriginator(raw: string): { originator: string; unverified: boolean } {
177
+ return isUnattestedOriginator(raw)
178
+ ? { originator: hostnameOfUnattested(raw), unverified: true }
179
+ : { originator: raw, unverified: false }
180
+ }
125
181
 
126
182
  /**
127
- * `promptData.lines`, validated into a bounded array of loosely-typed line
128
- * objects — or `null` for anything this sheet cannot enumerate in full
129
- * (absent, not an array, empty, oversized, or containing a non-object entry).
130
- * `null` is the caller's signal to block approval rather than silently fall
131
- * back to the primary-only view (XR-040).
183
+ * What a site said about itself, kept apart from the wallet's own wording for an unverified site.
184
+ * A verified site's text keeps the old inline treatment.
132
185
  */
133
- function sanitizedMandalaLines(raw: unknown): MandalaPromptLine[] | null {
134
- if (!Array.isArray(raw) || raw.length === 0 || raw.length > MANDALA_MAX_PROMPT_LINES) return null
135
- const lines: MandalaPromptLine[] = []
136
- for (const entry of raw) {
137
- if (!entry || typeof entry !== 'object') return null
138
- lines.push(entry as MandalaPromptLine)
139
- }
140
- return lines
186
+ function siteWords(
187
+ unverified: boolean,
188
+ text: string | undefined,
189
+ own: string
190
+ ): { description: string; siteSays?: string } {
191
+ if (!unverified) return { description: text || own }
192
+ return { description: own, siteSays: text || undefined }
141
193
  }
142
194
 
143
- // ---------------------------------------------------------------------------
144
- // Helpers
145
- // ---------------------------------------------------------------------------
195
+ /** Builds the `connection` prompt from a pending consent request and the flags that apply to it. */
196
+ function deriveConnection(c: PendingConsent, flags: SeekFlags): ActivePermission {
197
+ const unverified = c.attestation === 'unattested'
198
+ const allows: string[] = []
199
+ const asksFirst: string[] = []
200
+ for (const key of SEEK_FLAG_KEYS) {
201
+ // Payments have their own line below; only a payment flag that is off needs listing.
202
+ if (key === 'seekSpendingPermissions' && flags[key]) continue
203
+ ;(flags[key] ? asksFirst : allows).push(SEEK_FLAG_DISCLOSURE[key][flags[key] ? 'on' : 'off'])
204
+ }
205
+ return {
206
+ kind: 'connection',
207
+ requestID: c.requestId,
208
+ originator: c.origin,
209
+ unverified,
210
+ title: 'Connect Website',
211
+ description: 'wants to connect to your wallet',
212
+ details: [],
213
+ // The manifest group previewed before the sheet (spec 6.12); Connect mints exactly this.
214
+ groupPermissions: c.groupPermissions ?? undefined,
215
+ connection: {
216
+ transportId: c.transportId,
217
+ connectedBefore: c.connectedBefore,
218
+ allows,
219
+ asksFirst,
220
+ payments: flags.seekSpendingPermissions
221
+ ? unverified
222
+ ? 'bridge_payments_unverified'
223
+ : 'bridge_payments_verified'
224
+ : undefined
225
+ }
226
+ }
227
+ }
146
228
 
147
229
  /**
148
230
  * Derive the human-friendly "what is being asked" description for each
@@ -157,6 +239,9 @@ export function deriveActive(
157
239
  certificateRequests: any[]
158
240
  spendingRequests: any[]
159
241
  groupRequests?: any[]
242
+ /** Pending site-connection requests, with the flags that describe each one. */
243
+ connectionRequests?: PendingConsent[]
244
+ connectionFlags?: (attestation: PendingConsent['attestation']) => SeekFlags
160
245
  btmsRequests: any[]
161
246
  mandalaRequests: any[]
162
247
  protocolAccessModalOpen: boolean
@@ -164,7 +249,8 @@ export function deriveActive(
164
249
  certificateAccessModalOpen: boolean
165
250
  spendingAuthorizationModalOpen: boolean
166
251
  },
167
- formatSats: (satoshis: number) => { value: string; unit: string }
252
+ formatSats: (satoshis: number) => { value: string; unit: string },
253
+ color: ColorPromptDeps = NO_COLOR_DEPS
168
254
  ): ActivePermission | null {
169
255
  // Dev preview — override ctx with real captured data so the description
170
256
  // logic below is exercised exactly as it would be in production.
@@ -200,26 +286,38 @@ export function deriveActive(
200
286
  ...formatSats(item.satoshis)
201
287
  })
202
288
  )
289
+ const who = presentOriginator(r.originator || 'Unknown app')
203
290
  return {
204
291
  kind: 'spending',
205
292
  requestID: r.requestID,
206
- originator: r.originator || 'Unknown app',
293
+ manager: r.manager,
294
+ originator: who.originator,
295
+ unverified: who.unverified,
207
296
  title: 'Spending Authorization',
208
- description: r.description || 'wants to spend from your wallet',
297
+ ...siteWords(who.unverified, r.description, 'wants to spend from your wallet'),
209
298
  amount: r.authorizationAmount,
210
299
  renewal: r.renewal,
211
300
  details: lineItemDetails
212
301
  }
213
302
  }
214
303
 
304
+ // A website asking to connect. Core-owned, so it is not one of the manager queues above.
305
+ if (ctx.connectionRequests && ctx.connectionRequests.length > 0 && ctx.connectionFlags) {
306
+ const c = ctx.connectionRequests[0]
307
+ return deriveConnection(c, ctx.connectionFlags(c.attestation))
308
+ }
309
+
215
310
  // A site's grouped request (its manifest's metanet.groupPermissions) is the
216
311
  // whole set it will use, asked once when it connects.
217
312
  if (ctx.groupRequests && ctx.groupRequests.length > 0) {
218
313
  const r = ctx.groupRequests[0]
314
+ const who = presentOriginator(r.originator)
219
315
  return {
220
316
  kind: 'group',
221
317
  requestID: r.requestID,
222
- originator: r.originator,
318
+ manager: r.manager,
319
+ originator: who.originator,
320
+ unverified: who.unverified,
223
321
  title: 'Permissions',
224
322
  description: 'wants these permissions',
225
323
  details: [],
@@ -237,12 +335,15 @@ export function deriveActive(
237
335
  if (certType) details.push({ label: 'Certificate type', value: certType })
238
336
  if (verifier) details.push({ label: 'Verifier', value: truncate(verifier, 20) })
239
337
 
338
+ const who = presentOriginator(r.originator || 'Unknown app')
240
339
  return {
241
340
  kind: 'certificate',
242
341
  requestID: r.requestID,
243
- originator: r.originator || 'Unknown app',
342
+ manager: r.manager,
343
+ originator: who.originator,
344
+ unverified: who.unverified,
244
345
  title: r.renewal ? 'Certificate Access Renewal' : 'Certificate Access',
245
- description: r.description || 'wants to access certificate information',
346
+ ...siteWords(who.unverified, r.description, 'wants to access certificate information'),
246
347
  renewal: r.renewal,
247
348
  fields: fieldsArray.length > 0 ? fieldsArray : undefined,
248
349
  details
@@ -259,12 +360,18 @@ export function deriveActive(
259
360
  if (prompt.counterpartyLabel) details.push({ label: 'Shared with', value: prompt.counterpartyLabel })
260
361
  if (prompt.keyIDLabel) details.push({ label: 'Key ID', value: truncate(prompt.keyIDLabel, 40) })
261
362
  if (prompt.askEveryTime) details.push({ label: 'Approval', value: 'This signature only' })
363
+ const who = presentOriginator(r.originator || 'Unknown app')
262
364
  return {
263
365
  kind: 'protocol',
264
366
  requestID: r.requestID,
265
- originator: r.originator || 'Unknown app',
367
+ manager: r.manager,
368
+ originator: who.originator,
369
+ unverified: who.unverified,
266
370
  title: r.renewal ? `${prompt.title} Renewal` : prompt.title,
267
- description: prompt.description ?? (r.description || 'wants to use a cryptographic protocol'),
371
+ // The wallet's own wording for a known protocol; otherwise whatever the site said.
372
+ ...(prompt.description !== undefined
373
+ ? { description: prompt.description, siteSays: who.unverified ? r.description || undefined : undefined }
374
+ : siteWords(who.unverified, r.description, 'wants to use a cryptographic protocol')),
268
375
  renewal: r.renewal,
269
376
  details
270
377
  }
@@ -272,12 +379,15 @@ export function deriveActive(
272
379
 
273
380
  if (ctx.basketAccessModalOpen && ctx.basketRequests.length > 0) {
274
381
  const r = ctx.basketRequests[0]
382
+ const who = presentOriginator(r.originator || 'Unknown app')
275
383
  return {
276
384
  kind: 'basket',
277
385
  requestID: r.requestID,
278
- originator: r.originator || 'Unknown app',
386
+ manager: r.manager,
387
+ originator: who.originator,
388
+ unverified: who.unverified,
279
389
  title: r.renewal ? 'Basket Access Renewal' : 'Basket Access',
280
- description: r.reason || 'wants to access a transaction basket',
390
+ ...siteWords(who.unverified, r.reason, 'wants to access a transaction basket'),
281
391
  renewal: r.renewal,
282
392
  details: r.basket ? [{ label: 'Basket', value: r.basket }] : []
283
393
  }
@@ -325,155 +435,175 @@ export function deriveActive(
325
435
  kind: 'btms',
326
436
  // btms requests are resolved via advanceBtmsQueue, not permissionsManager — use a sentinel requestID
327
437
  requestID: '',
328
- originator: r.originator || 'Unknown app',
438
+ ...presentOriginator(r.originator || 'Unknown app'),
329
439
  title: 'Token Spend Request',
330
440
  description,
331
441
  details
332
442
  }
333
443
  }
334
444
 
335
- // mandala: same shape as btms above — driven purely by queue length, resolved via advanceMandalaQueue
445
+ // mandala: the BRC-207 color module's consent queue — driven purely by queue
446
+ // length, resolved via advanceMandalaQueue (same shape as btms above).
336
447
  if (ctx.mandalaRequests.length > 0) {
337
448
  const r = ctx.mandalaRequests[0]
338
- let promptData: {
339
- type?: string
340
- action?: string
341
- assetId?: string
342
- tokenName?: string
343
- sendAmount?: number
344
- changeAmount?: number
345
- creditAmount?: number
346
- lines?: unknown
347
- // XR-041: relinquishOutput's own resolved-target fields.
348
- amount?: number
349
- display?: string
350
- outpoint?: string
351
- } = {}
352
- try {
353
- promptData = JSON.parse(r.message)
354
- } catch {
355
- // message not valid JSON — ignore, use defaults
356
- }
357
-
358
- const isRelinquish = promptData.type === 'mandala_access' && promptData.action === 'relinquishOutput'
359
- // XR-041: `display` is pre-formatted ("25.00 USDX"); fall back to the raw
360
- // base-unit amount + token name when it is not a string, same convention
361
- // as the spend/credit lines below.
362
- const relinquishAmount =
363
- typeof promptData.display === 'string'
364
- ? promptData.display
365
- : promptData.amount != null
366
- ? `${promptData.amount} ${promptData.tokenName || 'Mandala tokens'}`
367
- : undefined
368
-
369
- let description: string
370
- if (promptData.type === 'mandala_spend' && promptData.sendAmount != null) {
371
- description = `wants to spend ${promptData.sendAmount} ${promptData.tokenName || 'Mandala tokens'}`
372
- } else if (promptData.type === 'mandala_credit' && promptData.creditAmount != null) {
373
- description = `wants to credit ${promptData.creditAmount} ${promptData.tokenName || 'Mandala tokens'} to your wallet`
374
- } else if (isRelinquish && relinquishAmount) {
375
- // Named, not generic (XR-041): which holding, not just that "a" holding
376
- // is being removed.
377
- description = `wants to remove ${relinquishAmount} from your wallet`
378
- } else if (isRelinquish) {
379
- description = 'wants to remove a Mandala token holding from your wallet'
380
- } else if (promptData.type === 'mandala_access') {
381
- description = 'wants to see your Mandala token balance'
382
- } else if (promptData.type === 'mandala_signature') {
383
- description = 'wants to sign with one of your token keys. Only approve if you just asked this app to move tokens'
384
- } else {
385
- description = 'wants to access Mandala tokens'
386
- }
387
-
388
- const details: { label: string; value: string }[] = []
389
- let approvalBlocked = false
390
-
391
- if (promptData.type === 'mandala_spend' || promptData.type === 'mandala_credit') {
392
- // XR-040: `lines` carries EVERY asset this request touches — rendering
393
- // only the primary (back-compat) fields below is how a single approval
394
- // silently released a second, unshown asset. Every sanitized line is
395
- // rendered; an unsanitizable `lines` blocks approval instead of falling
396
- // back to a primary-only view that looks complete but is not.
397
- const lines = sanitizedMandalaLines(promptData.lines)
398
- if (lines === null) {
399
- approvalBlocked = true
400
- details.push({
401
- label: 'Warning',
402
- value: 'Could not verify this is the full request — deny and try again.'
403
- })
404
- } else {
405
- const numbered = lines.length > 1
406
- lines.forEach((line, i) => {
407
- const suffix = numbered ? ` ${i + 1}` : ''
408
- if (typeof line.tokenName === 'string' && line.tokenName) {
409
- details.push({ label: `Token${suffix}`, value: line.tokenName })
410
- }
411
- if (typeof line.sendAmount === 'number') {
412
- details.push({
413
- label: `Send amount${suffix}`,
414
- value: typeof line.display === 'string' ? line.display : String(line.sendAmount)
415
- })
416
- }
417
- if (typeof line.changeAmount === 'number' && line.changeAmount !== 0) {
418
- details.push({ label: `Change${suffix}`, value: String(line.changeAmount) })
419
- }
420
- if (typeof line.creditAmount === 'number') {
421
- details.push({
422
- label: `Credit amount${suffix}`,
423
- value: typeof line.display === 'string' ? line.display : String(line.creditAmount)
424
- })
425
- }
426
- if (typeof line.assetId === 'string' && line.assetId) {
427
- details.push({ label: `Asset ID${suffix}`, value: truncate(line.assetId, 28) })
428
- }
429
- })
449
+ const view = typeof r.message === 'string' ? describeColorRequest(r.message, color.assetInfo, color.t) : null
450
+ if (view === null) {
451
+ // Not readable in full: deny-only, and said in the always-visible description.
452
+ return {
453
+ kind: 'mandala',
454
+ requestID: '',
455
+ ...presentOriginator(r.originator || 'Unknown app'),
456
+ title: 'Token Request',
457
+ description: 'wants to use your tokens, but this request could not be read — deny it.',
458
+ details: [],
459
+ approvalBlocked: true
430
460
  }
431
- } else if (isRelinquish) {
432
- // XR-041: identify the target the same way mandala_spend/mandala_credit
433
- // already identify theirs — token, amount, and the exact outpoint.
434
- if (promptData.tokenName) details.push({ label: 'Token', value: promptData.tokenName })
435
- if (relinquishAmount) details.push({ label: 'Amount', value: relinquishAmount })
436
- if (promptData.assetId) details.push({ label: 'Asset ID', value: truncate(promptData.assetId, 28) })
437
- if (promptData.outpoint) details.push({ label: 'Outpoint', value: truncate(promptData.outpoint, 28) })
438
- } else {
439
- if (promptData.assetId) details.push({ label: 'Asset ID', value: truncate(promptData.assetId, 28) })
440
- }
441
-
442
- // Said in the ALWAYS-VISIBLE description, not only the collapsed Details
443
- // section — the whole point is that this cannot be missed on the way to
444
- // an (already-disabled) Allow button.
445
- if (approvalBlocked) {
446
- description =
447
- 'wants to spend or credit Mandala tokens, but the full request could not be verified — deny and try again.'
448
461
  }
449
-
462
+ const description =
463
+ view.warning === undefined ? COLOR_DESCRIPTIONS[view.type] : `${COLOR_DESCRIPTIONS[view.type]}. ${view.warning}`
450
464
  return {
451
465
  kind: 'mandala',
452
466
  // mandala requests are resolved via advanceMandalaQueue, not permissionsManager — use a sentinel requestID
453
467
  requestID: '',
454
- originator: r.originator || 'Unknown app',
455
- title: 'Token Spend Request',
468
+ ...presentOriginator(r.originator || 'Unknown app'),
469
+ title: view.title,
456
470
  description,
457
- details,
458
- approvalBlocked
471
+ details: view.lines,
472
+ approvalBlocked: false
459
473
  }
460
474
  }
461
475
 
462
476
  return null
463
477
  }
464
478
 
479
+ /** The browser named on a verified connection. Only Safari attests today; anything else is generic. */
480
+ function browserName(transportId: string, t: (key: string) => string): string {
481
+ return /^safari/i.test(transportId) ? 'Safari' : t('bridge_browser_generic')
482
+ }
483
+
465
484
  function truncate(str: string, max: number): string {
466
485
  if (!str) return ''
467
486
  return str.length > max ? str.slice(0, max - 1) + '\u2026' : str
468
487
  }
469
488
 
470
- /** Map permission kind to the themed accent color key. */
489
+ /**
490
+ * The permissions a site asks for as read-only sections (spending with its amount, protocols, baskets,
491
+ * certificates). No checkbox and no switch: the set is granted or refused as a whole. Shared by the
492
+ * group sheet and the merged Connect sheet (spec 6.12).
493
+ */
494
+ function GroupPermissionSections({ group, unverified }: { group: GroupPermissions; unverified?: boolean }) {
495
+ const { t } = useTranslation()
496
+ const { colors } = useTheme()
497
+ // A manifest's own words for an unverified site are shown as the site's quote (spec 6.5).
498
+ const quoted = (text: string) => (unverified ? `\u201C${text}\u201D` : text)
499
+ return (
500
+ <>
501
+ {group.spendingAuthorization && (
502
+ <View style={[styles.groupSection, { borderColor: colors.separator }]}>
503
+ <Text style={[styles.groupSectionTitle, { color: colors.textSecondary }]}>{t('spending_section')}</Text>
504
+ <View style={styles.groupRow}>
505
+ <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>
506
+ <AmountDisplay>{group.spendingAuthorization.amount}</AmountDisplay>
507
+ </Text>
508
+ {group.spendingAuthorization.description && (
509
+ <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>
510
+ {quoted(group.spendingAuthorization.description)}
511
+ </Text>
512
+ )}
513
+ </View>
514
+ </View>
515
+ )}
516
+ {group.protocolPermissions && group.protocolPermissions.length > 0 && (
517
+ <View style={[styles.groupSection, { borderColor: colors.separator }]}>
518
+ <Text style={[styles.groupSectionTitle, { color: colors.textSecondary }]}>{t('protocols_section')}</Text>
519
+ {group.protocolPermissions.map((p, i) => (
520
+ <View key={i} style={styles.groupRow}>
521
+ <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>
522
+ {describeProtocolPrompt(p.protocolID[1], p.counterparty).protocolLabel}
523
+ </Text>
524
+ {p.description && (
525
+ <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>{quoted(p.description)}</Text>
526
+ )}
527
+ </View>
528
+ ))}
529
+ </View>
530
+ )}
531
+ {group.basketAccess && group.basketAccess.length > 0 && (
532
+ <View style={[styles.groupSection, { borderColor: colors.separator }]}>
533
+ <Text style={[styles.groupSectionTitle, { color: colors.textSecondary }]}>{t('baskets_section')}</Text>
534
+ {group.basketAccess.map((b, i) => (
535
+ <View key={i} style={styles.groupRow}>
536
+ <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>{b.basket}</Text>
537
+ {b.description && (
538
+ <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>{quoted(b.description)}</Text>
539
+ )}
540
+ </View>
541
+ ))}
542
+ </View>
543
+ )}
544
+ {group.certificateAccess && group.certificateAccess.length > 0 && (
545
+ <View style={[styles.groupSection, { borderColor: colors.separator }]}>
546
+ <Text style={[styles.groupSectionTitle, { color: colors.textSecondary }]}>{t('certificates_section')}</Text>
547
+ {group.certificateAccess.map((c, i) => (
548
+ <View key={i} style={styles.groupRow}>
549
+ <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>{c.type}</Text>
550
+ {c.description && (
551
+ <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>{quoted(c.description)}</Text>
552
+ )}
553
+ {c.fields && c.fields.length > 0 && (
554
+ <Text style={[styles.groupRowDesc, { color: colors.textTertiary }]}>Fields: {c.fields.join(', ')}</Text>
555
+ )}
556
+ </View>
557
+ ))}
558
+ </View>
559
+ )}
560
+ </>
561
+ )
562
+ }
471
563
 
472
564
  // ---------------------------------------------------------------------------
473
565
  // Component
474
566
  // ---------------------------------------------------------------------------
475
567
 
476
- const PermissionSheet: React.FC = () => {
568
+ /**
569
+ * True while any permission sheet is open or queued (every manager queue, the BTMS and mandala queues and
570
+ * the website connection requests). The Safari bridge's done screen stays hidden while this is true, and a
571
+ * later sheet replaces it (spec 6.12).
572
+ */
573
+ export function usePermissionSheetBusy(): boolean {
574
+ const {
575
+ protocolRequests,
576
+ basketRequests,
577
+ certificateRequests,
578
+ spendingRequests,
579
+ groupRequests,
580
+ btmsRequests,
581
+ mandalaRequests
582
+ } = useContext(WalletContext)
583
+ const connections = useSyncExternalStore(subscribeConsentRequests, getPendingConnections, getPendingConnections)
584
+ return (
585
+ (protocolRequests?.length ?? 0) +
586
+ (basketRequests?.length ?? 0) +
587
+ (certificateRequests?.length ?? 0) +
588
+ (spendingRequests?.length ?? 0) +
589
+ (groupRequests?.length ?? 0) +
590
+ (btmsRequests?.length ?? 0) +
591
+ (mandalaRequests?.length ?? 0) +
592
+ connections.length >
593
+ 0
594
+ )
595
+ }
596
+
597
+ interface PermissionSheetProps {
598
+ /**
599
+ * Whether a backdrop tap or a swipe down answers the prompt as a rejection. Default true. The Android bridge's overlay
600
+ * root passes false: there an outside tap does nothing and only the Reject button rejects. Per instance, so a main-tree
601
+ * sheet mounted at the same time is unaffected.
602
+ */
603
+ backdropDismisses?: boolean
604
+ }
605
+
606
+ const PermissionSheet: React.FC<PermissionSheetProps> = ({ backdropDismisses = true }) => {
477
607
  const { t } = useTranslation()
478
608
  const { colors } = useTheme()
479
609
  const Ionicons = loadIonicons()
@@ -493,8 +623,8 @@ const PermissionSheet: React.FC = () => {
493
623
  advanceGroupQueue,
494
624
  advanceBtmsQueue,
495
625
  advanceMandalaQueue,
496
- managers,
497
- settings
626
+ settings,
627
+ mandala
498
628
  } = useContext(WalletContext)
499
629
 
500
630
  const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
@@ -504,16 +634,47 @@ const PermissionSheet: React.FC = () => {
504
634
  [currency, satoshisPerUSD, usdToFiat]
505
635
  )
506
636
 
507
- const {
508
- protocolAccessModalOpen,
509
- setProtocolAccessModalOpen,
510
- basketAccessModalOpen,
511
- setBasketAccessModalOpen,
512
- certificateAccessModalOpen,
513
- setCertificateAccessModalOpen,
514
- spendingAuthorizationModalOpen,
515
- setSpendingAuthorizationModalOpen
516
- } = useContext(UserContext)
637
+ // Token display metadata for color consent prompts: host-resolved and
638
+ // untrusted (the full asset id is always shown beside it). Loaded when a
639
+ // token prompt is queued; a failed or slow load only means exact base units.
640
+ const [colorAssets, setColorAssets] = useState<ReadonlyMap<string, { ticker: string; decimals: number }>>(
641
+ () => new Map()
642
+ )
643
+ const hasMandalaRequest = mandalaRequests.length > 0
644
+ useEffect(() => {
645
+ if (!hasMandalaRequest || mandala === undefined) return
646
+ let cancelled = false
647
+ // Through Promise.resolve so a synchronous throw is caught too, never
648
+ // crashing the sheet while a token prompt waits.
649
+ Promise.resolve()
650
+ .then(() => mandala.listAssets())
651
+ .then(assets => {
652
+ if (cancelled) return
653
+ setColorAssets(new Map(assets.map(a => [a.assetId, { ticker: a.ticker, decimals: a.decimals }])))
654
+ })
655
+ .catch(() => {
656
+ // Metadata is optional: the prompt falls back to exact base units.
657
+ })
658
+ return () => {
659
+ cancelled = true
660
+ }
661
+ }, [hasMandalaRequest, mandala])
662
+ const colorDeps = useMemo(
663
+ () => ({
664
+ t: (key: string, o?: object) => String(t(key, o as never)),
665
+ assetInfo: (assetId: string) => colorAssets.get(assetId)
666
+ }),
667
+ [t, colorAssets]
668
+ )
669
+
670
+ const { protocolAccessModalOpen, basketAccessModalOpen, certificateAccessModalOpen, spendingAuthorizationModalOpen } =
671
+ useContext(UserContext)
672
+
673
+ const connectionRequests = useSyncExternalStore(
674
+ subscribeConsentRequests,
675
+ getPendingConnections,
676
+ getPendingConnections
677
+ )
517
678
 
518
679
  const [detailsExpanded, setDetailsExpanded] = useState(false)
519
680
  const [granted, setGranted] = useState(false)
@@ -522,6 +683,26 @@ const PermissionSheet: React.FC = () => {
522
683
  // can be flushed synchronously if a higher-priority request preempts.
523
684
  const pendingGrantRef = useRef<(() => void) | null>(null)
524
685
 
686
+ // Whether the request a pending answer was meant for is still in its queue.
687
+ // A withdrawal (profile switch, logout) empties the queues, and the new
688
+ // wallet's manager can then raise a request with the very same ID, so a
689
+ // request is the same one only if it also came from the same manager.
690
+ const queuesRef = useRef({ protocolRequests, basketRequests, certificateRequests, spendingRequests, groupRequests })
691
+ queuesRef.current = { protocolRequests, basketRequests, certificateRequests, spendingRequests, groupRequests }
692
+ const stillQueued = useCallback((request: ActivePermission): boolean => {
693
+ // Connection requests live in the consent store; ids there are never reused.
694
+ if (request.kind === 'connection') return getPendingConnections().some(c => c.requestId === request.requestID)
695
+ const q = queuesRef.current
696
+ const list: any[] | undefined = {
697
+ protocol: q.protocolRequests,
698
+ basket: q.basketRequests,
699
+ certificate: q.certificateRequests,
700
+ spending: q.spendingRequests,
701
+ group: q.groupRequests
702
+ }[request.kind as 'protocol' | 'basket' | 'certificate' | 'spending' | 'group']
703
+ return !!list?.some(r => r.requestID === request.requestID && r.manager === request.manager)
704
+ }, [])
705
+
525
706
  // Clear the pending grant timer (or flush it) on unmount to prevent stale handler calls.
526
707
  useEffect(() => {
527
708
  return () => {
@@ -536,6 +717,21 @@ const PermissionSheet: React.FC = () => {
536
717
  }
537
718
  }, [])
538
719
 
720
+ // React Native pauses JS timers while the app is backgrounded, so a grant waiting out its 400 ms would
721
+ // leave the page's call hanging if the user leaves right after tapping. Answer at once instead.
722
+ useEffect(() => {
723
+ const sub = AppState.addEventListener('change', state => {
724
+ if (state === 'active' || pendingGrantRef.current === null) return
725
+ if (grantTimerRef.current !== null) {
726
+ clearTimeout(grantTimerRef.current)
727
+ grantTimerRef.current = null
728
+ }
729
+ pendingGrantRef.current()
730
+ pendingGrantRef.current = null
731
+ })
732
+ return () => sub.remove()
733
+ }, [])
734
+
539
735
  // Derive what (if anything) we should show.
540
736
  const active = useMemo(
541
737
  () =>
@@ -546,6 +742,8 @@ const PermissionSheet: React.FC = () => {
546
742
  certificateRequests,
547
743
  spendingRequests,
548
744
  groupRequests,
745
+ connectionRequests,
746
+ connectionFlags,
549
747
  btmsRequests,
550
748
  mandalaRequests,
551
749
  protocolAccessModalOpen,
@@ -553,7 +751,8 @@ const PermissionSheet: React.FC = () => {
553
751
  certificateAccessModalOpen,
554
752
  spendingAuthorizationModalOpen
555
753
  },
556
- formatSats
754
+ formatSats,
755
+ colorDeps
557
756
  ),
558
757
  [
559
758
  protocolRequests,
@@ -561,13 +760,15 @@ const PermissionSheet: React.FC = () => {
561
760
  certificateRequests,
562
761
  spendingRequests,
563
762
  groupRequests,
763
+ connectionRequests,
564
764
  btmsRequests,
565
765
  mandalaRequests,
566
766
  protocolAccessModalOpen,
567
767
  basketAccessModalOpen,
568
768
  certificateAccessModalOpen,
569
769
  spendingAuthorizationModalOpen,
570
- formatSats
770
+ formatSats,
771
+ colorDeps
571
772
  ]
572
773
  )
573
774
 
@@ -600,12 +801,35 @@ const PermissionSheet: React.FC = () => {
600
801
  setGranted(false)
601
802
  }, [activeRequestID])
602
803
 
804
+ // Tap protection (spec 6.4): a connection or unverified prompt cannot be approved for the first
805
+ // 700 ms it is at the head of the queue, so a tap aimed at the previous sheet cannot land on it.
806
+ // Keyed on the head's identity, so a request queueing behind it does not restart the window.
807
+ const needsTapDelay = active !== null && (active.kind === 'connection' || active.unverified === true)
808
+ // The manager is part of the identity: a replacement manager restarts its request counters, so a
809
+ // re-raised prompt can repeat the kind, id, originator and description of the one before it.
810
+ const headKey = active
811
+ ? `${active.kind}|${managerToken(active.manager)}|${active.requestID}|${active.originator}|${active.description}`
812
+ : ''
813
+ const [armedKey, setArmedKey] = useState('')
814
+ useEffect(() => {
815
+ // A new head, or none, is never armed from an earlier head's window.
816
+ setArmedKey('')
817
+ if (!needsTapDelay) return
818
+ const timer = setTimeout(() => setArmedKey(headKey), TAP_PROTECTION_MS)
819
+ return () => clearTimeout(timer)
820
+ }, [needsTapDelay, headKey])
821
+ const tapLocked = needsTapDelay && armedKey !== headKey
822
+
603
823
  // ---- Deny ----
604
824
  const handleDeny = useCallback(async () => {
605
825
  if (granted) return
606
826
  if (!active) return
607
827
  haptics.warning()
608
- if (active.kind === 'btms') {
828
+ if (active.kind === 'connection') {
829
+ await answerConnection(active.requestID, false).catch((e: unknown) =>
830
+ console.warn('[bridge] connection decline failed', e)
831
+ )
832
+ } else if (active.kind === 'btms') {
609
833
  // BTMS uses its own promise-based resolution — no permissionsManager.denyPermission
610
834
  advanceBtmsQueue(false)
611
835
  } else if (active.kind === 'mandala') {
@@ -616,52 +840,48 @@ const PermissionSheet: React.FC = () => {
616
840
  // then asked for on its own when used. A hard deny would make the
617
841
  // site's waitForAuthentication throw.
618
842
  try {
619
- await managers.permissionsManager?.dismissGroupedPermission(active.requestID)
843
+ await active.manager?.dismissGroupedPermission(active.requestID)
620
844
  } catch {
621
845
  // Already settled (e.g. the site went away) -- nothing left to answer.
622
846
  }
623
- advanceGroupQueue()
847
+ if (stillQueued(active)) advanceGroupQueue(active.requestID)
624
848
  } else {
625
849
  try {
626
- await managers.permissionsManager?.denyPermission(active.requestID)
850
+ await active.manager?.denyPermission(active.requestID)
627
851
  } catch {
628
852
  // User denial is expected -- not an error condition
629
853
  }
630
- switch (active.kind) {
631
- case 'protocol':
632
- advanceProtocolQueue()
633
- setProtocolAccessModalOpen(false)
634
- break
635
- case 'basket':
636
- advanceBasketQueue()
637
- setBasketAccessModalOpen(false)
638
- break
639
- case 'certificate':
640
- advanceCertificateQueue()
641
- setCertificateAccessModalOpen(false)
642
- break
643
- case 'spending':
644
- advanceSpendingQueue()
645
- setSpendingAuthorizationModalOpen(false)
646
- break
854
+ // The answer went to the manager that raised the request; the queue
855
+ // loses it only if it is still the same one (see stillQueued).
856
+ if (stillQueued(active)) {
857
+ switch (active.kind) {
858
+ case 'protocol':
859
+ advanceProtocolQueue(active.requestID)
860
+ break
861
+ case 'basket':
862
+ advanceBasketQueue(active.requestID)
863
+ break
864
+ case 'certificate':
865
+ advanceCertificateQueue(active.requestID)
866
+ break
867
+ case 'spending':
868
+ advanceSpendingQueue(active.requestID)
869
+ break
870
+ }
647
871
  }
648
872
  }
649
873
  setDetailsExpanded(false)
650
874
  }, [
651
875
  granted,
652
876
  active,
653
- managers.permissionsManager,
877
+ stillQueued,
654
878
  advanceProtocolQueue,
655
879
  advanceBasketQueue,
656
880
  advanceCertificateQueue,
657
881
  advanceSpendingQueue,
658
882
  advanceGroupQueue,
659
883
  advanceBtmsQueue,
660
- advanceMandalaQueue,
661
- setProtocolAccessModalOpen,
662
- setBasketAccessModalOpen,
663
- setCertificateAccessModalOpen,
664
- setSpendingAuthorizationModalOpen
884
+ advanceMandalaQueue
665
885
  ])
666
886
 
667
887
  // ---- Grant ----
@@ -674,46 +894,55 @@ const PermissionSheet: React.FC = () => {
674
894
  // Clear the pending ref so flush-on-preempt guards don't double-fire.
675
895
  pendingGrantRef.current = null
676
896
 
677
- if (request.kind === 'btms') {
897
+ if (request.kind === 'connection') {
898
+ // The store drops the answer if the request is gone or the wallet has changed.
899
+ answerConnection(request.requestID, true).catch((e: unknown) =>
900
+ console.warn('[bridge] connection approval failed', e)
901
+ )
902
+ } else if (request.kind === 'btms') {
678
903
  advanceBtmsQueue(true)
679
904
  } else if (request.kind === 'mandala') {
680
905
  advanceMandalaQueue(true)
906
+ } else if (!stillQueued(request)) {
907
+ // Withdrawn while the checkmark showed (a profile switch or logout
908
+ // emptied the queue): the manager that raised it is gone and what is
909
+ // queued now is not this request. Answer nothing, drop nothing.
681
910
  } else if (request.kind === 'group') {
682
911
  // Grants exactly the set shown. The manager mints the permission
683
912
  // tokens, then resolves the site's waitForAuthentication; if minting
684
913
  // fails it rejects that call itself.
685
- managers.permissionsManager
914
+ request.manager
686
915
  ?.grantGroupedPermission({
687
916
  requestID: request.requestID,
688
917
  // The manager's own request object, passed back unchanged.
689
918
  granted: (request.groupPermissions ?? {}) as GrantedGroupPermissions
690
919
  })
691
920
  .catch((error: unknown) => console.warn('[permissions] grouped grant failed', error))
692
- advanceGroupQueue()
921
+ advanceGroupQueue(request.requestID)
693
922
  } else if (request.kind === 'spending') {
694
- managers.permissionsManager?.grantPermission({
695
- requestID: request.requestID,
696
- ephemeral: true,
697
- amount: request.amount
698
- })
699
- advanceSpendingQueue()
700
- setSpendingAuthorizationModalOpen(false)
923
+ request.manager
924
+ ?.grantPermission({
925
+ requestID: request.requestID,
926
+ ephemeral: true,
927
+ amount: request.amount
928
+ })
929
+ .catch((error: unknown) => console.warn('[permissions] grant failed', error))
930
+ advanceSpendingQueue(request.requestID)
701
931
  } else {
702
- managers.permissionsManager?.grantPermission({
703
- requestID: request.requestID
704
- })
932
+ request.manager
933
+ ?.grantPermission({
934
+ requestID: request.requestID
935
+ })
936
+ .catch((error: unknown) => console.warn('[permissions] grant failed', error))
705
937
  switch (request.kind) {
706
938
  case 'protocol':
707
- advanceProtocolQueue()
708
- setProtocolAccessModalOpen(false)
939
+ advanceProtocolQueue(request.requestID)
709
940
  break
710
941
  case 'basket':
711
- advanceBasketQueue()
712
- setBasketAccessModalOpen(false)
942
+ advanceBasketQueue(request.requestID)
713
943
  break
714
944
  case 'certificate':
715
- advanceCertificateQueue()
716
- setCertificateAccessModalOpen(false)
945
+ advanceCertificateQueue(request.requestID)
717
946
  break
718
947
  }
719
948
  }
@@ -723,26 +952,22 @@ const PermissionSheet: React.FC = () => {
723
952
  setGranted(false)
724
953
  },
725
954
  [
726
- managers.permissionsManager,
955
+ stillQueued,
727
956
  advanceProtocolQueue,
728
957
  advanceBasketQueue,
729
958
  advanceCertificateQueue,
730
959
  advanceSpendingQueue,
731
960
  advanceGroupQueue,
732
961
  advanceBtmsQueue,
733
- advanceMandalaQueue,
734
- setProtocolAccessModalOpen,
735
- setBasketAccessModalOpen,
736
- setCertificateAccessModalOpen,
737
- setSpendingAuthorizationModalOpen
962
+ advanceMandalaQueue
738
963
  ]
739
964
  )
740
965
 
741
966
  const handleGrant = useCallback(() => {
742
967
  // XR-040: belt-and-braces alongside the Allow button's own `disabled` —
743
- // a mandala_spend/mandala_credit prompt whose `lines` this sheet could
744
- // not fully enumerate must never be approvable, from any call path.
745
- if (!active || granted || active.approvalBlocked) return
968
+ // a token consent message this sheet could not read in full must never
969
+ // be approvable, from any call path.
970
+ if (!active || granted || active.approvalBlocked || tapLocked) return
746
971
  haptics.success()
747
972
  setGranted(true)
748
973
  if (grantTimerRef.current !== null) {
@@ -756,10 +981,10 @@ const PermissionSheet: React.FC = () => {
756
981
  grantTimerRef.current = null
757
982
  pendingFn()
758
983
  }, 400)
759
- }, [active, granted, executeGrant])
984
+ }, [active, granted, tapLocked, executeGrant])
760
985
 
761
986
  return (
762
- <Sheet visible={visible} onClose={handleDeny} heightPercent={0.92} fitContent>
987
+ <Sheet visible={visible} onClose={handleDeny} dismissible={backdropDismisses} heightPercent={0.92} fitContent>
763
988
  {active && (
764
989
  <View>
765
990
  <View style={styles.content}>
@@ -775,10 +1000,37 @@ const PermissionSheet: React.FC = () => {
775
1000
  {(active.originator[0] ?? '?').toUpperCase()}
776
1001
  </Text>
777
1002
  </View>
778
- <Text style={[styles.originator, { color: colors.textPrimary }]} numberOfLines={1}>
779
- {active.originator}
780
- </Text>
1003
+ <View style={styles.originatorText}>
1004
+ <Text
1005
+ style={[
1006
+ styles.originator,
1007
+ active.unverified || active.kind === 'connection' ? styles.originatorMono : null,
1008
+ { color: colors.textPrimary }
1009
+ ]}
1010
+ numberOfLines={1}
1011
+ testID="bridge-connect-origin"
1012
+ >
1013
+ {active.originator}
1014
+ </Text>
1015
+ {active.kind === 'connection' && active.connection && !active.unverified && (
1016
+ <Text style={[styles.originatorSub, { color: colors.textSecondary }]} numberOfLines={1}>
1017
+ {t('bridge_verified_by', { browser: browserName(active.connection.transportId, t) })}
1018
+ </Text>
1019
+ )}
1020
+ </View>
1021
+ {active.unverified && (
1022
+ <View style={[styles.unverifiedBadge, { backgroundColor: colors.warning + '26' }]}>
1023
+ <Text style={[styles.unverifiedBadgeText, { color: colors.warning }]}>
1024
+ {t('bridge_badge_unverified')}
1025
+ </Text>
1026
+ </View>
1027
+ )}
781
1028
  </View>
1029
+ {active.unverified && (
1030
+ <Text style={[styles.channelNote, { color: colors.textSecondary }]}>
1031
+ {t('bridge_unverified_channel')}
1032
+ </Text>
1033
+ )}
782
1034
 
783
1035
  {/* -------- Renewal badge -------- */}
784
1036
  {active.renewal && (
@@ -787,82 +1039,53 @@ const PermissionSheet: React.FC = () => {
787
1039
  </View>
788
1040
  )}
789
1041
 
790
- {/* -------- Group permissions list -------- */}
791
- {active.kind === 'group' && active.groupPermissions && (
1042
+ {/* -------- Site connection: what connecting allows, in the wallet's words -------- */}
1043
+ {active.kind === 'connection' && active.connection && (
792
1044
  <ScrollView style={styles.groupScroll} bounces={false}>
793
- {active.groupPermissions.spendingAuthorization && (
794
- <View style={[styles.groupSection, { borderColor: colors.separator }]}>
795
- <Text style={[styles.groupSectionTitle, { color: colors.textSecondary }]}>
796
- {t('spending_section')}
1045
+ <Text style={[styles.connectHeader, { color: colors.textSecondary }]}>{t('bridge_allows_header')}</Text>
1046
+ {['bridge_allows_sign_in', ...active.connection.allows].map(key => (
1047
+ <Text key={key} style={[styles.connectItem, { color: colors.textPrimary }]}>
1048
+ {'\u2022'} {t(key)}
1049
+ </Text>
1050
+ ))}
1051
+ {active.connection.asksFirst.length > 0 && (
1052
+ <>
1053
+ <Text style={[styles.connectHeader, { color: colors.textSecondary }]}>
1054
+ {t('bridge_asks_header')}
797
1055
  </Text>
798
- <View style={styles.groupRow}>
799
- <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>
800
- <AmountDisplay>{active.groupPermissions.spendingAuthorization.amount}</AmountDisplay>
1056
+ {active.connection.asksFirst.map(key => (
1057
+ <Text key={key} style={[styles.connectItem, { color: colors.textPrimary }]}>
1058
+ {'\u2022'} {t(key)}
801
1059
  </Text>
802
- {active.groupPermissions.spendingAuthorization.description && (
803
- <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>
804
- {active.groupPermissions.spendingAuthorization.description}
805
- </Text>
806
- )}
807
- </View>
808
- </View>
809
- )}
810
- {active.groupPermissions.protocolPermissions &&
811
- active.groupPermissions.protocolPermissions.length > 0 && (
812
- <View style={[styles.groupSection, { borderColor: colors.separator }]}>
813
- <Text style={[styles.groupSectionTitle, { color: colors.textSecondary }]}>
814
- {t('protocols_section')}
815
- </Text>
816
- {active.groupPermissions.protocolPermissions.map((p, i) => (
817
- <View key={i} style={styles.groupRow}>
818
- <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>
819
- {describeProtocolPrompt(p.protocolID[1], p.counterparty).protocolLabel}
820
- </Text>
821
- {p.description && (
822
- <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>{p.description}</Text>
823
- )}
824
- </View>
825
- ))}
826
- </View>
827
- )}
828
- {active.groupPermissions.basketAccess && active.groupPermissions.basketAccess.length > 0 && (
829
- <View style={[styles.groupSection, { borderColor: colors.separator }]}>
830
- <Text style={[styles.groupSectionTitle, { color: colors.textSecondary }]}>
831
- {t('baskets_section')}
832
- </Text>
833
- {active.groupPermissions.basketAccess.map((b, i) => (
834
- <View key={i} style={styles.groupRow}>
835
- <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>{b.basket}</Text>
836
- {b.description && (
837
- <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>{b.description}</Text>
838
- )}
839
- </View>
840
1060
  ))}
841
- </View>
1061
+ </>
842
1062
  )}
843
- {active.groupPermissions.certificateAccess && active.groupPermissions.certificateAccess.length > 0 && (
844
- <View style={[styles.groupSection, { borderColor: colors.separator }]}>
845
- <Text style={[styles.groupSectionTitle, { color: colors.textSecondary }]}>
846
- {t('certificates_section')}
847
- </Text>
848
- {active.groupPermissions.certificateAccess.map((c, i) => (
849
- <View key={i} style={styles.groupRow}>
850
- <Text style={[styles.groupRowLabel, { color: colors.textPrimary }]}>{c.type}</Text>
851
- {c.description && (
852
- <Text style={[styles.groupRowDesc, { color: colors.textSecondary }]}>{c.description}</Text>
853
- )}
854
- {c.fields && c.fields.length > 0 && (
855
- <Text style={[styles.groupRowDesc, { color: colors.textTertiary }]}>
856
- Fields: {c.fields.join(', ')}
857
- </Text>
858
- )}
859
- </View>
860
- ))}
861
- </View>
1063
+ {active.connection.payments && (
1064
+ <Text style={[styles.connectNote, { color: colors.textPrimary }]}>
1065
+ {t(active.connection.payments)}
1066
+ </Text>
1067
+ )}
1068
+ <Text style={[styles.connectNote, { color: colors.textSecondary }]}>
1069
+ {t(active.unverified ? 'bridge_remember_unverified' : 'bridge_remember_verified')}
1070
+ </Text>
1071
+ {active.unverified && active.connection.connectedBefore && (
1072
+ <Text style={[styles.connectNote, { color: colors.textPrimary }]}>
1073
+ {t('bridge_connected_before')}
1074
+ </Text>
1075
+ )}
1076
+ {active.groupPermissions && (
1077
+ <GroupPermissionSections group={active.groupPermissions} unverified={active.unverified} />
862
1078
  )}
863
1079
  </ScrollView>
864
1080
  )}
865
1081
 
1082
+ {/* -------- Group permissions list -------- */}
1083
+ {active.kind === 'group' && active.groupPermissions && (
1084
+ <ScrollView style={styles.groupScroll} bounces={false}>
1085
+ <GroupPermissionSections group={active.groupPermissions} unverified={active.unverified} />
1086
+ </ScrollView>
1087
+ )}
1088
+
866
1089
  {/* -------- Expandable details (scrollable if tall) -------- */}
867
1090
  {active.kind !== 'group' && (active.details.length > 0 || (active.fields && active.fields.length > 0)) && (
868
1091
  <View style={styles.detailsSection}>
@@ -893,7 +1116,17 @@ const PermissionSheet: React.FC = () => {
893
1116
  {active.details.map((d, i) => (
894
1117
  <View key={i} style={styles.detailRow}>
895
1118
  <Text style={[styles.detailLabel, { color: colors.textSecondary }]}>{d.label}</Text>
896
- <Text style={[styles.detailValue, { color: colors.textPrimary }]} numberOfLines={1}>
1119
+ {/* Token prompts wrap instead of truncating: the full asset id and
1120
+ exact amounts are what the user approves (IC §2.5). */}
1121
+ <Text
1122
+ style={[
1123
+ styles.detailValue,
1124
+ { color: colors.textPrimary },
1125
+ active.kind === 'mandala' ? styles.detailValueWrap : null
1126
+ ]}
1127
+ numberOfLines={active.kind === 'mandala' ? undefined : 1}
1128
+ selectable={active.kind === 'mandala'}
1129
+ >
897
1130
  {d.value}
898
1131
  {d.unit ? (
899
1132
  <Text style={[styles.detailUnit, { color: colors.textSecondary }]}> {d.unit}</Text>
@@ -923,6 +1156,17 @@ const PermissionSheet: React.FC = () => {
923
1156
  <View style={styles.askBlock}>
924
1157
  <Text style={[styles.description, { color: colors.textSecondary }]}>{active.description}</Text>
925
1158
 
1159
+ {active.siteSays ? (
1160
+ <View style={[styles.siteSays, { borderColor: colors.separator }]}>
1161
+ <Text style={[styles.siteSaysLabel, { color: colors.textTertiary }]}>{t('bridge_site_says')}</Text>
1162
+ <Text style={[styles.siteSaysText, { color: colors.textSecondary }]}>
1163
+ {'\u201C'}
1164
+ {active.siteSays}
1165
+ {'\u201D'}
1166
+ </Text>
1167
+ </View>
1168
+ ) : null}
1169
+
926
1170
  {active.kind === 'spending' && active.amount != null && (
927
1171
  <Text style={[styles.amountValue, { color: colors.textPrimary }]}>
928
1172
  {amountParts.value}
@@ -943,8 +1187,11 @@ const PermissionSheet: React.FC = () => {
943
1187
  ]}
944
1188
  onPress={handleDeny}
945
1189
  disabled={granted}
1190
+ testID="bridge-deny"
946
1191
  >
947
- <Text style={[styles.buttonDenyText, { color: colors.textPrimary }]}>{t('reject')}</Text>
1192
+ <Text style={[styles.buttonDenyText, { color: colors.textPrimary }]}>
1193
+ {t(active.kind === 'connection' ? 'bridge_dont_connect' : 'reject')}
1194
+ </Text>
948
1195
  </PressableScale>
949
1196
 
950
1197
  {/* Accent-filled and the only shadowed element in the drawer, so the
@@ -953,12 +1200,15 @@ const PermissionSheet: React.FC = () => {
953
1200
  <PressableScale
954
1201
  style={[styles.buttonAllow, { backgroundColor: colors.accent }]}
955
1202
  onPress={handleGrant}
956
- disabled={granted || active.approvalBlocked}
1203
+ disabled={granted || active.approvalBlocked || tapLocked}
1204
+ testID="bridge-approve"
957
1205
  >
958
1206
  {granted ? (
959
1207
  <Ionicons name="checkmark" size={22} color={colors.textOnAccent} />
960
1208
  ) : (
961
- <Text style={[styles.buttonAllowText, { color: colors.textOnAccent }]}>{t('authorize')}</Text>
1209
+ <Text style={[styles.buttonAllowText, { color: colors.textOnAccent }]}>
1210
+ {t(active.kind === 'connection' ? 'bridge_connect' : 'authorize')}
1211
+ </Text>
962
1212
  )}
963
1213
  </PressableScale>
964
1214
  </View>
@@ -998,11 +1248,68 @@ const styles = StyleSheet.create({
998
1248
  fontSize: 17,
999
1249
  fontWeight: '700'
1000
1250
  },
1251
+ originatorText: {
1252
+ flex: 1
1253
+ },
1001
1254
  originator: {
1002
1255
  fontSize: 15,
1003
1256
  fontWeight: '600',
1004
- letterSpacing: -0.1,
1005
- flex: 1
1257
+ letterSpacing: -0.1
1258
+ },
1259
+ // The raw origin is the identity being asked about, so it is set in a face where lookalike
1260
+ // characters stay distinct.
1261
+ originatorMono: {
1262
+ fontFamily: Platform.select({ ios: 'Menlo', default: 'monospace' }),
1263
+ fontSize: 14,
1264
+ letterSpacing: 0
1265
+ },
1266
+ originatorSub: {
1267
+ ...typography.caption1,
1268
+ marginTop: 1
1269
+ },
1270
+ unverifiedBadge: {
1271
+ paddingHorizontal: spacing.sm,
1272
+ paddingVertical: spacing.xs,
1273
+ borderRadius: radii.sm,
1274
+ marginLeft: spacing.sm
1275
+ },
1276
+ unverifiedBadgeText: {
1277
+ ...typography.caption1,
1278
+ fontWeight: '700'
1279
+ },
1280
+ channelNote: {
1281
+ ...typography.footnote,
1282
+ marginBottom: spacing.md
1283
+ },
1284
+ connectHeader: {
1285
+ ...typography.caption1,
1286
+ fontWeight: '600',
1287
+ marginTop: spacing.sm,
1288
+ marginBottom: spacing.xs
1289
+ },
1290
+ connectItem: {
1291
+ ...typography.footnote,
1292
+ marginLeft: spacing.sm,
1293
+ marginTop: 2
1294
+ },
1295
+ connectNote: {
1296
+ ...typography.footnote,
1297
+ marginTop: spacing.md
1298
+ },
1299
+ siteSays: {
1300
+ borderLeftWidth: 2,
1301
+ paddingLeft: spacing.md,
1302
+ marginTop: spacing.lg,
1303
+ alignSelf: 'stretch'
1304
+ },
1305
+ siteSaysLabel: {
1306
+ ...typography.caption1,
1307
+ fontWeight: '600',
1308
+ marginBottom: 2
1309
+ },
1310
+ siteSaysText: {
1311
+ ...typography.footnote,
1312
+ fontStyle: 'italic'
1006
1313
  },
1007
1314
 
1008
1315
  // Renewal badge
@@ -1084,6 +1391,9 @@ const styles = StyleSheet.create({
1084
1391
  textAlign: 'right',
1085
1392
  fontVariant: ['tabular-nums']
1086
1393
  },
1394
+ detailValueWrap: {
1395
+ flexShrink: 1
1396
+ },
1087
1397
  detailUnit: {
1088
1398
  fontSize: 11.5,
1089
1399
  fontWeight: '500'