@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
@@ -17,6 +17,11 @@ import { KeyDeriver, PrivateKey, MerklePath, Transaction, Utils } from '@bsv/sdk
17
17
  import { DEFAULT_SETTINGS } from './defaultWalletSettings'
18
18
  import { conformWalletResults } from '../services/conformWalletResults'
19
19
  import { SigningPolicyPermissionsManager } from '../services/signingPermissionPolicy'
20
+ import {
21
+ guardTokenPromptHandlers,
22
+ handleSpendingPrompt,
23
+ withdrawPrompts as withdrawPromptsFrom
24
+ } from '../services/permissionPrompts'
20
25
  import { VAULT_RETENTION_MS, ceremony as vaultCeremony } from '../services/vault/ceremonyHost'
21
26
  import { getVaultDriver } from '../services/vault/driver'
22
27
  import { backupAttestation } from '../services/vault/backupAttestation'
@@ -127,6 +132,10 @@ function disposeColorModule(ref: { current: BuiltColorModule | undefined }): voi
127
132
  }
128
133
 
129
134
  import type { AppChain } from '../config'
135
+ import { effectiveUnverified, loadStoredPolicy, resolvePermissionPolicy } from '../bridge/permissionPolicy'
136
+ import { notifyPromptRaised } from '../bridge/runtime'
137
+ import { hasUnattestedTransport, onUnattestedTransportChange } from '../bridge/runtimeFlags'
138
+ import { buildUnverifiedPermissionsManager } from '../bridge/unverifiedManager'
130
139
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
131
140
  import { NETWORKS, isAppChain } from '../networks'
132
141
  import { getBackupUrl, getHandleRegistryConfig, getMandalaEndpoints, getPushAdapter } from '../toolboxConfig'
@@ -159,7 +168,7 @@ import {
159
168
  import type { MandalaRuntime } from '../mandala/runtime'
160
169
  import { mandalaSettlementDeps, type CancelParkedSettlementDeps } from '../offline/cancelParked'
161
170
  import { drainMandalaInbox } from '../pay/rails/handle'
162
- import { disconnectActivePairedSession } from './WalletConnectionContext'
171
+ import { runSessionTeardown } from './sessionTeardown'
163
172
  import connectionStore from '../stores/ConnectionStore'
164
173
  import { loadUserAvatarIcon } from '../userAvatar'
165
174
  import { createServices, chaintracksUrlFor } from '../services/walletServiceConfig'
@@ -371,6 +380,15 @@ const profilePurgeIo: PurgeProfileIo = {
371
380
  interface ManagerState {
372
381
  walletManager?: SimpleWalletManager
373
382
  permissionsManager?: WalletPermissionsManager
383
+ /** The attested manager itself, before the guard and conformance wrappers
384
+ * `permissionsManager` carries. What `withdrawPrompts` retires. */
385
+ signingPermissionsManager?: SigningPolicyPermissionsManager
386
+ /** The manager for unverified (unattested) browser origins, behind the same wrapper stack as
387
+ * `permissionsManager`. Present only when a transport that can deliver unattested calls was
388
+ * registered when the wallet was built (spec 6.5). */
389
+ unverifiedPermissionsManager?: WalletPermissionsManager
390
+ /** The unverified manager itself, before its wrappers. What `withdrawPrompts` retires. */
391
+ unverifiedSigningPermissionsManager?: SigningPolicyPermissionsManager
374
392
  settingsManager?: WalletSettingsManager
375
393
  }
376
394
 
@@ -441,13 +459,23 @@ export interface WalletContextValue {
441
459
  groupRequests: GroupPermissionRequest[]
442
460
  btmsRequests: BtmsRequest[]
443
461
  mandalaRequests: MandalaRequest[]
444
- advanceBasketQueue: () => void
445
- advanceCertificateQueue: () => void
446
- advanceProtocolQueue: () => void
447
- advanceSpendingQueue: () => void
448
- advanceGroupQueue: () => void
462
+ advanceBasketQueue: (requestID?: string) => void
463
+ advanceCertificateQueue: (requestID?: string) => void
464
+ advanceProtocolQueue: (requestID?: string) => void
465
+ advanceSpendingQueue: (requestID?: string) => void
466
+ advanceGroupQueue: (requestID?: string) => void
449
467
  advanceBtmsQueue: (approved: boolean) => void
450
468
  advanceMandalaQueue: (approved: boolean) => void
469
+ /**
470
+ * Retires the given (replaced) managers, denies what they still hold and
471
+ * empties every permission queue. Idempotent. Runs by itself on every
472
+ * teardown the context performs; the bridge runtime calls it for a wallet it
473
+ * sees replaced some other way.
474
+ */
475
+ withdrawPrompts: (oldManagers: SigningPolicyPermissionsManager[]) => void
476
+ /** Registers something else to clear on a withdrawal (pending connection
477
+ * requests). Returns the unregister function. */
478
+ registerPromptWithdrawal: (clear: () => void) => () => void
451
479
  finalizeConfig: (wabConfig: WABConfig) => boolean
452
480
  setConfigStatus: (status: ConfigStatus) => void
453
481
  configStatus: ConfigStatus
@@ -587,6 +615,8 @@ export const WalletContext = createContext<WalletContextValue>({
587
615
  advanceGroupQueue: () => {},
588
616
  advanceBtmsQueue: () => {},
589
617
  advanceMandalaQueue: () => {},
618
+ withdrawPrompts: () => {},
619
+ registerPromptWithdrawal: () => () => {},
590
620
  finalizeConfig: () => false,
591
621
  setConfigStatus: () => {},
592
622
  configStatus: 'initial',
@@ -653,7 +683,12 @@ export const useWalletManagers = (): WalletManagersSlice => useContext(WalletMan
653
683
 
654
684
  type PermissionType = 'identity' | 'protocol' | 'renewal' | 'basket'
655
685
 
656
- type BasketAccessRequest = {
686
+ /** Each prompt callback is bound per manager and each queue item records the
687
+ * manager that raised it; the sheet answers that manager, never whichever one
688
+ * is current, so a stale answer cannot reach a replacement. */
689
+ type RaisedBy = { manager?: SigningPolicyPermissionsManager }
690
+
691
+ type BasketAccessRequest = RaisedBy & {
657
692
  requestID: string
658
693
  basket?: string
659
694
  originator: string
@@ -661,7 +696,7 @@ type BasketAccessRequest = {
661
696
  renewal?: boolean
662
697
  }
663
698
 
664
- type CertificateAccessRequest = {
699
+ type CertificateAccessRequest = RaisedBy & {
665
700
  requestID: string
666
701
  certificate?: {
667
702
  certType?: string
@@ -673,7 +708,7 @@ type CertificateAccessRequest = {
673
708
  renewal?: boolean
674
709
  }
675
710
 
676
- type ProtocolAccessRequest = {
711
+ type ProtocolAccessRequest = RaisedBy & {
677
712
  requestID: string
678
713
  protocolSecurityLevel: number
679
714
  protocolID: string
@@ -687,7 +722,7 @@ type ProtocolAccessRequest = {
687
722
  type?: PermissionType
688
723
  }
689
724
 
690
- type SpendingRequest = {
725
+ type SpendingRequest = RaisedBy & {
691
726
  requestID: string
692
727
  originator: string
693
728
  description?: string
@@ -701,7 +736,7 @@ type SpendingRequest = {
701
736
 
702
737
  /** A site's grouped permission request, from its manifest's
703
738
  * `metanet.groupPermissions` (WalletPermissionsManager.waitForAuthentication). */
704
- export type GroupPermissionRequest = {
739
+ export type GroupPermissionRequest = RaisedBy & {
705
740
  requestID: string
706
741
  originator: string
707
742
  permissions: {
@@ -1101,7 +1136,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1101
1136
  setSpendingAuthorizationModalOpen
1102
1137
  } = useContext(UserContext)
1103
1138
 
1104
- const focusOpts = { isFocused, onFocusRequested, onFocusRelinquished }
1139
+ // A prompt raised for a connected site while the app is in the background must pull the user to
1140
+ // the sheet; the bridge decides whether that applies (live binding of this originator, not active).
1141
+ const notePromptRaised = useCallback((item: unknown) => {
1142
+ const originator = (item as { originator?: unknown } | null)?.originator
1143
+ if (typeof originator === 'string') notifyPromptRaised(originator)
1144
+ }, [])
1145
+ const focusOpts = { isFocused, onFocusRequested, onFocusRelinquished, onEnqueue: notePromptRaised }
1105
1146
 
1106
1147
  const basketQueue = usePermissionQueue<BasketAccessRequest>({
1107
1148
  ...focusOpts,
@@ -1160,6 +1201,70 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1160
1201
  [mandalaQueue.enqueue]
1161
1202
  )
1162
1203
 
1204
+ // The five manager-backed queues answer by identity: with a requestID only
1205
+ // that item is removed, and nothing if it is no longer queued (a withdrawal
1206
+ // emptied the queue while the user's answer was on its way).
1207
+ const advanceBasketQueue = useCallback(
1208
+ (requestID?: string) => basketQueue.advance(undefined, requestID),
1209
+ [basketQueue.advance]
1210
+ )
1211
+ const advanceCertificateQueue = useCallback(
1212
+ (requestID?: string) => certificateQueue.advance(undefined, requestID),
1213
+ [certificateQueue.advance]
1214
+ )
1215
+ const advanceProtocolQueue = useCallback(
1216
+ (requestID?: string) => protocolQueue.advance(undefined, requestID),
1217
+ [protocolQueue.advance]
1218
+ )
1219
+ const advanceSpendingQueue = useCallback(
1220
+ (requestID?: string) => spendingQueue.advance(undefined, requestID),
1221
+ [spendingQueue.advance]
1222
+ )
1223
+ const advanceGroupQueue = useCallback(
1224
+ (requestID?: string) => groupQueue.advance(undefined, requestID),
1225
+ [groupQueue.advance]
1226
+ )
1227
+
1228
+ const promptWithdrawalsRef = useRef(new Set<() => void>())
1229
+ const registerPromptWithdrawal = useCallback((clear: () => void) => {
1230
+ promptWithdrawalsRef.current.add(clear)
1231
+ return () => {
1232
+ promptWithdrawalsRef.current.delete(clear)
1233
+ }
1234
+ }, [])
1235
+ const withdrawPrompts = useCallback(
1236
+ (oldManagers: SigningPolicyPermissionsManager[]) => {
1237
+ withdrawPromptsFrom(oldManagers, {
1238
+ managerQueues: [basketQueue, certificateQueue, protocolQueue, spendingQueue, groupQueue],
1239
+ tokenQueues: [btmsQueue, mandalaQueue],
1240
+ others: [...promptWithdrawalsRef.current]
1241
+ })
1242
+ },
1243
+ [
1244
+ basketQueue.clear,
1245
+ certificateQueue.clear,
1246
+ protocolQueue.clear,
1247
+ spendingQueue.clear,
1248
+ groupQueue.clear,
1249
+ btmsQueue.clear,
1250
+ mandalaQueue.clear
1251
+ ]
1252
+ )
1253
+ // Teardown paths are declared far from here and must not re-create on every
1254
+ // queue change, so they reach the current function through a ref.
1255
+ const withdrawPromptsRef = useRef(withdrawPrompts)
1256
+ withdrawPromptsRef.current = withdrawPrompts
1257
+ /** Withdraws the prompts of the managers currently published, before the
1258
+ * wallet they belong to is torn down. */
1259
+ const withdrawCurrentPrompts = useCallback(() => {
1260
+ const { signingPermissionsManager, unverifiedSigningPermissionsManager } = managersRef.current
1261
+ withdrawPromptsRef.current(
1262
+ [signingPermissionsManager, unverifiedSigningPermissionsManager].filter(
1263
+ (m): m is SigningPolicyPermissionsManager => m !== undefined
1264
+ )
1265
+ )
1266
+ }, [])
1267
+
1163
1268
  const updateSettings = useCallback(
1164
1269
  async (newSettings: WalletSettings) => {
1165
1270
  setSettings(newSettings)
@@ -1176,7 +1281,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1176
1281
  originator: string
1177
1282
  reason?: string
1178
1283
  renewal?: boolean
1179
- }
1284
+ },
1285
+ manager?: SigningPolicyPermissionsManager
1180
1286
  ) => {
1181
1287
  if (incomingRequest?.requestID) {
1182
1288
  basketQueue.enqueue({
@@ -1184,7 +1290,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1184
1290
  basket: incomingRequest.basket,
1185
1291
  originator: incomingRequest.originator,
1186
1292
  reason: incomingRequest.reason,
1187
- renewal: incomingRequest.renewal
1293
+ renewal: incomingRequest.renewal,
1294
+ manager
1188
1295
  })
1189
1296
  }
1190
1297
  },
@@ -1203,7 +1310,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1203
1310
  originator: string
1204
1311
  reason?: string
1205
1312
  renewal?: boolean
1206
- }
1313
+ },
1314
+ manager?: SigningPolicyPermissionsManager
1207
1315
  ) => {
1208
1316
  if (incomingRequest?.requestID) {
1209
1317
  const certificate = incomingRequest.certificate as any
@@ -1214,7 +1322,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1214
1322
  certificateType: certificate?.certType || '',
1215
1323
  fieldsArray: certificate?.fields || [],
1216
1324
  description: incomingRequest.reason,
1217
- renewal: incomingRequest.renewal
1325
+ renewal: incomingRequest.renewal,
1326
+ manager
1218
1327
  } as any)
1219
1328
  }
1220
1329
  },
@@ -1222,7 +1331,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1222
1331
  )
1223
1332
 
1224
1333
  const protocolPermissionCallback = useCallback(
1225
- (args: PermissionRequest & { requestID: string }): Promise<void> => {
1334
+ (args: PermissionRequest & { requestID: string }, manager?: SigningPolicyPermissionsManager): Promise<void> => {
1226
1335
  const { requestID, counterparty, originator, reason, renewal, protocolID } = args
1227
1336
  const keyID = (args as { keyID?: unknown }).keyID
1228
1337
  if (!requestID || !protocolID) return Promise.resolve()
@@ -1243,7 +1352,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1243
1352
  originator,
1244
1353
  description: reason,
1245
1354
  renewal,
1246
- type: permissionType
1355
+ type: permissionType,
1356
+ manager
1247
1357
  })
1248
1358
  return Promise.resolve()
1249
1359
  },
@@ -1251,67 +1361,46 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1251
1361
  )
1252
1362
 
1253
1363
  const spendingAuthorizationCallback = useCallback(
1254
- async (args: PermissionRequest & { requestID: string }): Promise<void> => {
1255
- const { requestID, originator, reason, renewal, spending } = args
1256
- if (!requestID || !spending) return
1257
-
1364
+ async (
1365
+ args: PermissionRequest & { requestID: string },
1366
+ manager?: SigningPolicyPermissionsManager
1367
+ ): Promise<void> => {
1258
1368
  // Auto-approve small transactions if within threshold, per-originator
1259
1369
  // cooldown, and the global rolling 24h cap (misc-p2-04) — accounting
1260
1370
  // lives in autoApprovePolicy.ts. Read the persisted threshold fresh on
1261
1371
  // every request so a change made in wallet-config takes effect
1262
1372
  // immediately (the mount-time ref read alone left the old value live
1263
1373
  // until app restart — felt like auto-approve was "stuck on").
1264
- try {
1265
- const stored = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY))
1266
- // Unset means this profile never chose one: the default, never another profile's.
1267
- autoApproveThresholdRef.current = stored !== null ? Number(stored) || 0 : DEFAULT_AUTO_APPROVE_THRESHOLD
1268
- } catch {}
1269
- const threshold = autoApproveThresholdRef.current
1270
- autoApproveThresholdSnapshot = threshold
1271
- // Logging gated behind __DEV__: an unconditional console.log here flushes
1272
- // over the JS↔native bridge on every spend request — i.e. on the payment
1273
- // hot path — and shows up as jank under any burst of micropayments.
1274
- const autoApproveDecision = autoApprovePolicy.shouldAutoApprove({
1275
- originator,
1276
- satoshis: spending.satoshis
1277
- })
1278
- if (autoApproveDecision.approve) {
1279
- autoApprovePolicy.record({ originator, satoshis: spending.satoshis, at: Date.now() })
1280
- persistAutoApproveLedger()
1281
- if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
1282
- managersRef.current.permissionsManager?.grantPermission({
1283
- requestID,
1284
- ephemeral: true,
1285
- amount: spending.satoshis
1286
- })
1287
- return
1288
- }
1289
- if (__DEV__) {
1290
- console.log(
1291
- `[spend-auth] not eligible (${autoApproveDecision.reason}) → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
1292
- )
1293
- }
1294
-
1295
- spendingQueue.enqueue({
1296
- requestID,
1297
- originator,
1298
- description: reason,
1299
- transactionAmount: 0,
1300
- totalPastSpending: 0,
1301
- amountPreviouslyAuthorized: 0,
1302
- authorizationAmount: spending.satoshis,
1303
- renewal,
1304
- lineItems: spending.lineItems || []
1374
+ // The flow itself (including what a withdrawal during that read means)
1375
+ // is handleSpendingPrompt's.
1376
+ await handleSpendingPrompt<SpendingRequest>(args as never, manager, {
1377
+ loadThreshold: async () => {
1378
+ try {
1379
+ const stored = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY))
1380
+ // Unset means this profile never chose one: the default, never another profile's.
1381
+ autoApproveThresholdRef.current = stored !== null ? Number(stored) || 0 : DEFAULT_AUTO_APPROVE_THRESHOLD
1382
+ } catch {}
1383
+ },
1384
+ decide: (originator, satoshis) => {
1385
+ autoApproveThresholdSnapshot = autoApproveThresholdRef.current
1386
+ return autoApprovePolicy.shouldAutoApprove({ originator, satoshis })
1387
+ },
1388
+ recordAutoApproved: (originator, satoshis) => {
1389
+ autoApprovePolicy.record({ originator, satoshis, at: Date.now() })
1390
+ persistAutoApproveLedger()
1391
+ },
1392
+ enqueue: spendingQueue.enqueue,
1393
+ currentManager: () => managersRef.current.signingPermissionsManager
1305
1394
  })
1306
1395
  },
1307
1396
  [spendingQueue.enqueue]
1308
1397
  )
1309
1398
 
1310
1399
  const groupedPermissionCallback = useCallback(
1311
- async (args: GroupPermissionRequest): Promise<void> => {
1400
+ async (args: GroupPermissionRequest, manager?: SigningPolicyPermissionsManager): Promise<void> => {
1312
1401
  const { requestID, originator, permissions } = args ?? ({} as GroupPermissionRequest)
1313
1402
  if (!requestID || !permissions) return
1314
- groupQueue.enqueue({ requestID, originator, permissions })
1403
+ groupQueue.enqueue({ requestID, originator, permissions, manager })
1315
1404
  },
1316
1405
  [groupQueue.enqueue]
1317
1406
  )
@@ -1958,7 +2047,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1958
2047
 
1959
2048
  // Create BTMS permission module, wiring in the prompt handler so that
1960
2049
  // "p btms" operations surface a UI modal rather than silently denying.
1961
- const btmsModule = loadBtmsPermissionModule().createBtmsModule({ wallet, promptHandler: btmsPromptHandler })
2050
+ // Both token-module prompt functions are tied to this build: once its
2051
+ // manager is retired (the wallet was replaced) they resolve false
2052
+ // without enqueueing. The manager below retires them with itself.
2053
+ const buildPrompts = guardTokenPromptHandlers({ btms: btmsPromptHandler, mandala: mandalaPromptHandler })
2054
+ const btmsModule = loadBtmsPermissionModule().createBtmsModule({ wallet, promptHandler: buildPrompts.btms })
1962
2055
 
1963
2056
  // The BRC-207 color module (plan 07 Task 10): all token custody and
1964
2057
  // evidence, registered below as `permissionModules.color`, so every
@@ -1999,7 +2092,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1999
2092
  wallet,
2000
2093
  endpoints: mandalaEndpoints,
2001
2094
  kv: phoneStorage,
2002
- requestTokenAccess: createColorAccessPolicy({ adminOriginator, prompt: mandalaPromptHandler })
2095
+ requestTokenAccess: createColorAccessPolicy({ adminOriginator, prompt: buildPrompts.mandala })
2003
2096
  })
2004
2097
  } catch (error) {
2005
2098
  console.error('[WalletContext] could not build the color module; p color calls will be refused:', error)
@@ -2008,53 +2101,44 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2008
2101
  colorModule = colorRef.current?.module
2009
2102
  }
2010
2103
 
2104
+ // The user's stored prompt policy for this profile (spec 6.5), authenticated by the admin
2105
+ // key. It applies from this build on; absent or not authentic means the defaults.
2106
+ const builtPolicy = resolvePermissionPolicy(
2107
+ await loadStoredPolicy(profileScopedKey(''), wallet as never, adminOriginator)
2108
+ )
2109
+
2011
2110
  // Setup permissions with provided callbacks and BTMS module.
2012
2111
  const permissionsManager = new SigningPolicyPermissionsManager(wallet, adminOriginator, {
2013
2112
  differentiatePrivilegedOperations: true,
2014
- seekBasketInsertionPermissions: false,
2015
- seekBasketListingPermissions: false,
2016
- seekBasketRemovalPermissions: false,
2017
- seekCertificateAcquisitionPermissions: false,
2018
- seekCertificateDisclosurePermissions: false,
2019
- seekCertificateRelinquishmentPermissions: false,
2020
- seekCertificateListingPermissions: false,
2021
- // A site whose manifest declares metanet.groupPermissions is asked
2022
- // for them all in one sheet during waitForAuthentication. The request
2023
- // holds that origin's permission lock until answered, so it MUST be
2024
- // handled (onGroupedPermissionRequested, below) or the site hangs.
2025
- seekGroupedPermission: true,
2026
- seekPermissionsForIdentityKeyRevelation: false,
2027
- seekPermissionsForIdentityResolution: false,
2028
- seekPermissionsForKeyLinkageRevelation: false,
2029
- seekPermissionsForPublicKeyRevelation: false,
2030
- seekPermissionWhenApplyingActionLabels: false,
2031
- seekPermissionWhenListingActionsByLabel: false,
2032
- seekProtocolPermissionsForEncrypting: false,
2033
- seekProtocolPermissionsForHMAC: false,
2034
- // On, unlike Metanet Desktop: the vault guard no longer refuses
2035
- // external BRC-29 ([2,'3241645161d8']) signing outright, and that
2036
- // namespace also derives this wallet's own address-rail keys
2037
- // (counterparty 'anyone'), so a site signing under it must be
2038
- // asked first -- for BRC-29, on every signature. BRC-103/104 auth
2039
- // signing is exempt (SigningPolicyPermissionsManager).
2040
- seekProtocolPermissionsForSigning: true,
2041
- seekSpendingPermissions: true,
2113
+ // The prompt settings live in core/bridge/permissionPolicy.ts (default: exactly the
2114
+ // configuration this literal used to hold).
2115
+ ...builtPolicy.verified,
2042
2116
  permissionModules: colorModule ? { btms: btmsModule, color: colorModule } : { btms: btmsModule }
2043
2117
  } as any)
2044
2118
 
2045
- if (protocolPermissionCallback) {
2046
- permissionsManager.bindCallback('onProtocolPermissionRequested', protocolPermissionCallback)
2047
- }
2048
- if (basketAccessCallback) {
2049
- permissionsManager.bindCallback('onBasketAccessRequested', basketAccessCallback)
2050
- }
2051
- if (spendingAuthorizationCallback) {
2052
- permissionsManager.bindCallback('onSpendingAuthorizationRequested', spendingAuthorizationCallback)
2053
- }
2054
- permissionsManager.bindCallback('onGroupedPermissionRequested', groupedPermissionCallback as any)
2055
- if (certificateAccessCallback) {
2056
- permissionsManager.bindCallback('onCertificateAccessRequested', certificateAccessCallback)
2119
+ permissionsManager.onRetire(buildPrompts.retire)
2120
+
2121
+ const bindPromptCallbacks = (mgr: SigningPolicyPermissionsManager) => {
2122
+ // Bound per manager: each queue item records the manager that raised
2123
+ // it, and the sheet answers that one (see RaisedBy).
2124
+ if (protocolPermissionCallback) {
2125
+ mgr.bindCallback('onProtocolPermissionRequested', (args: any) => protocolPermissionCallback(args, mgr))
2126
+ }
2127
+ if (basketAccessCallback) {
2128
+ mgr.bindCallback('onBasketAccessRequested', (args: any) => basketAccessCallback(args, mgr))
2129
+ }
2130
+ if (spendingAuthorizationCallback) {
2131
+ mgr.bindCallback('onSpendingAuthorizationRequested', (args: any) =>
2132
+ spendingAuthorizationCallback(args, mgr)
2133
+ )
2134
+ }
2135
+ mgr.bindCallback('onGroupedPermissionRequested', ((args: any) => groupedPermissionCallback(args, mgr)) as any)
2136
+ if (certificateAccessCallback) {
2137
+ mgr.bindCallback('onCertificateAccessRequested', (args: any) => certificateAccessCallback(args, mgr))
2138
+ }
2057
2139
  }
2140
+ bindPromptCallbacks(permissionsManager)
2141
+ newManagers.signingPermissionsManager = permissionsManager
2058
2142
 
2059
2143
  // Publish one idempotently guarded manager for both trusted in-app
2060
2144
  // Vault calls and external WalletClient calls; external call sites may
@@ -2085,15 +2169,29 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2085
2169
  // `mandalaRef.current`, whose `undefined` also covers a runtime that
2086
2170
  // threw or is mid-rebuild, both of which can leave real journal rows
2087
2171
  // unreadable rather than absent.
2088
- newManagers.permissionsManager = guardVaultAccess(
2089
- wrapAbortActionForSettlements(
2090
- conformWalletResults(adminOriginator, permissionsManager),
2091
- () => mandalaRef.current?.journal,
2092
- () => mandalaEndpoints !== undefined
2093
- ),
2094
- adminOriginator,
2095
- { lookup: phoneStorage }
2096
- )
2172
+ // The unverified manager gets the same stack (spec 6.5).
2173
+ const guardedStack = (mgr: SigningPolicyPermissionsManager) =>
2174
+ guardVaultAccess(
2175
+ wrapAbortActionForSettlements(
2176
+ conformWalletResults(adminOriginator, mgr),
2177
+ () => mandalaRef.current?.journal,
2178
+ () => mandalaEndpoints !== undefined
2179
+ ),
2180
+ adminOriginator,
2181
+ { lookup: phoneStorage }
2182
+ )
2183
+ newManagers.permissionsManager = guardedStack(permissionsManager)
2184
+
2185
+ if (hasUnattestedTransport()) {
2186
+ const unverified = buildUnverifiedPermissionsManager(
2187
+ wallet,
2188
+ adminOriginator,
2189
+ effectiveUnverified(builtPolicy)
2190
+ )
2191
+ bindPromptCallbacks(unverified)
2192
+ newManagers.unverifiedSigningPermissionsManager = unverified
2193
+ newManagers.unverifiedPermissionsManager = guardedStack(unverified)
2194
+ }
2097
2195
 
2098
2196
  // THE MANDALA RUNTIME'S ONE CONSTRUCTION SITE.
2099
2197
  //
@@ -3041,6 +3139,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3041
3139
  * anything can resume against the departing wallet.
3042
3140
  */
3043
3141
  const teardownBuiltWallet = useCallback(async () => {
3142
+ // Prompts raised by the departing wallet are withdrawn, and its managers
3143
+ // retired, before anything yields: otherwise a sheet for it survives the
3144
+ // switch and answering it throws on the new manager.
3145
+ withdrawCurrentPrompts()
3044
3146
  // Invalidate Vault operations before the first teardown await. Otherwise a
3045
3147
  // signer/listing already in flight can resume against the departing wallet.
3046
3148
  vaultStore.clearScope()
@@ -3112,6 +3214,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3112
3214
  reviewImportedCoinsRef.current = opts?.reviewImportedCoins === true
3113
3215
  // Any build already in flight belongs to the configuration being replaced.
3114
3216
  const token = buildGenRef.current.bump()
3217
+ // The bridge's bindings and published managers belong to the wallet being torn down: close
3218
+ // and drop them before anything yields (spec G9), not when the next build publishes.
3219
+ runSessionTeardown('rebuild')
3115
3220
  await teardownBuiltWallet()
3116
3221
 
3117
3222
  // Re-finalize with current config — triggers auto-build effect
@@ -3133,6 +3238,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3133
3238
  [selectedNetwork, teardownBuiltWallet, finalizeConfig, waitForRebuild]
3134
3239
  )
3135
3240
 
3241
+ // A transport that can deliver unattested calls registered after this wallet was built: the
3242
+ // unverified manager is made in the build, so build again to get it (spec 6.5). Normally the
3243
+ // provider registers before the first build and this never fires.
3244
+ const rebuildWalletRef = useRef(rebuildWallet)
3245
+ rebuildWalletRef.current = rebuildWallet
3246
+ useEffect(
3247
+ () =>
3248
+ onUnattestedTransportChange(present => {
3249
+ if (!present || !walletBuiltRef.current || managersRef.current.unverifiedPermissionsManager) return
3250
+ void rebuildWalletRef.current().catch(() => {})
3251
+ }),
3252
+ []
3253
+ )
3254
+
3136
3255
  // Switch network: tear down wallet, update config, and rebuild on new chain.
3137
3256
  // The network belongs to the active profile, so this changes that profile's.
3138
3257
  //
@@ -3145,6 +3264,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3145
3264
  // The ref, not the state: the fallback below runs inside the same call.
3146
3265
  const from = selectedNetworkRef.current
3147
3266
  if (network === from || switchInFlightRef.current) return
3267
+ runSessionTeardown('network')
3148
3268
  logWithTimestamp(F, `Switching network from ${from} to ${network}`)
3149
3269
  const token = buildGenRef.current.bump()
3150
3270
  // Same hold-off as switchProfile: no build may start on the old network
@@ -3226,7 +3346,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3226
3346
  let __tBuild = 0
3227
3347
  try {
3228
3348
  // Pairings belong to the departing identity.
3229
- disconnectActivePairedSession()
3349
+ runSessionTeardown('profile')
3230
3350
  profileTransitionRef.current = true
3231
3351
  try {
3232
3352
  await teardownBuiltWallet()
@@ -3920,7 +4040,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3920
4040
  // XR-018: a live paired RPC socket otherwise outlives logout/wallet
3921
4041
  // deletion — the peer would keep dispatching allowlisted BRC-100 methods
3922
4042
  // against a wallet the user believes they've logged out of.
3923
- disconnectActivePairedSession()
4043
+ runSessionTeardown('logout')
4044
+ withdrawCurrentPrompts()
3924
4045
  // The IIFE's promise IS returned (unlike the old fire-and-forget version):
3925
4046
  // XR-107 needs the caller to await the verified outcome of the secret
3926
4047
  // erasure below, not just the synchronous kickoff. This does not
@@ -4589,13 +4710,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4589
4710
  groupRequests: groupQueue.requests,
4590
4711
  btmsRequests: btmsQueue.requests,
4591
4712
  mandalaRequests: mandalaQueue.requests,
4592
- advanceBasketQueue: basketQueue.advance,
4593
- advanceCertificateQueue: certificateQueue.advance,
4594
- advanceProtocolQueue: protocolQueue.advance,
4595
- advanceSpendingQueue: spendingQueue.advance,
4596
- advanceGroupQueue: groupQueue.advance,
4713
+ advanceBasketQueue,
4714
+ advanceCertificateQueue,
4715
+ advanceProtocolQueue,
4716
+ advanceSpendingQueue,
4717
+ advanceGroupQueue,
4597
4718
  advanceBtmsQueue,
4598
4719
  advanceMandalaQueue,
4720
+ withdrawPrompts,
4721
+ registerPromptWithdrawal,
4599
4722
  finalizeConfig,
4600
4723
  setConfigStatus,
4601
4724
  configStatus,
@@ -4649,13 +4772,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4649
4772
  groupQueue.requests,
4650
4773
  btmsQueue.requests,
4651
4774
  mandalaQueue.requests,
4652
- basketQueue.advance,
4653
- certificateQueue.advance,
4654
- protocolQueue.advance,
4655
- spendingQueue.advance,
4656
- groupQueue.advance,
4775
+ advanceBasketQueue,
4776
+ advanceCertificateQueue,
4777
+ advanceProtocolQueue,
4778
+ advanceSpendingQueue,
4779
+ advanceGroupQueue,
4657
4780
  advanceBtmsQueue,
4658
4781
  advanceMandalaQueue,
4782
+ withdrawPrompts,
4783
+ registerPromptWithdrawal,
4659
4784
  finalizeConfig,
4660
4785
  setConfigStatus,
4661
4786
  configStatus,
@@ -4760,11 +4885,11 @@ export interface WalletQueuesSlice {
4760
4885
  groupRequests: GroupPermissionRequest[]
4761
4886
  btmsRequests: BtmsRequest[]
4762
4887
  mandalaRequests: MandalaRequest[]
4763
- advanceBasketQueue: () => void
4764
- advanceCertificateQueue: () => void
4765
- advanceProtocolQueue: () => void
4766
- advanceSpendingQueue: () => void
4767
- advanceGroupQueue: () => void
4888
+ advanceBasketQueue: (requestID?: string) => void
4889
+ advanceCertificateQueue: (requestID?: string) => void
4890
+ advanceProtocolQueue: (requestID?: string) => void
4891
+ advanceSpendingQueue: (requestID?: string) => void
4892
+ advanceGroupQueue: (requestID?: string) => void
4768
4893
  advanceBtmsQueue: (approved: boolean) => void
4769
4894
  advanceMandalaQueue: (approved: boolean) => void
4770
4895
  }