@bsv/expo-wallet-toolbox 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +10 -9
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  16. package/core/bridge/bindings.ts +459 -0
  17. package/core/bridge/conformance.ts +222 -0
  18. package/core/bridge/consent.ts +494 -0
  19. package/core/bridge/consentSheetSource.ts +98 -0
  20. package/core/bridge/dispatcher.ts +621 -0
  21. package/core/bridge/inbox.ts +569 -0
  22. package/core/bridge/index.ts +48 -0
  23. package/core/bridge/loopback/cors.ts +57 -0
  24. package/core/bridge/loopback/endpoints.ts +11 -0
  25. package/core/bridge/loopback/hostCheck.ts +25 -0
  26. package/core/bridge/loopback/index.ts +7 -0
  27. package/core/bridge/loopback/launchProof.ts +166 -0
  28. package/core/bridge/loopback/router.ts +770 -0
  29. package/core/bridge/loopback/routerTypes.ts +115 -0
  30. package/core/bridge/loopback/status.ts +52 -0
  31. package/core/bridge/memoryInboxStore.ts +231 -0
  32. package/core/bridge/permissionPolicy.ts +247 -0
  33. package/core/bridge/policy.ts +72 -0
  34. package/core/bridge/protocol/base64url.ts +64 -0
  35. package/core/bridge/protocol/connectionError.ts +79 -0
  36. package/core/bridge/protocol/constants.ts +21 -0
  37. package/core/bridge/protocol/continuity.ts +21 -0
  38. package/core/bridge/protocol/descriptor.ts +395 -0
  39. package/core/bridge/protocol/envelopes.ts +188 -0
  40. package/core/bridge/protocol/errorCodec.ts +164 -0
  41. package/core/bridge/protocol/json.ts +237 -0
  42. package/core/bridge/protocol/limits.ts +43 -0
  43. package/core/bridge/protocol/methods.ts +55 -0
  44. package/core/bridge/protocol/origin.ts +130 -0
  45. package/core/bridge/runtime.ts +642 -0
  46. package/core/bridge/runtimeFlags.ts +34 -0
  47. package/core/bridge/testing/conformanceCases.ts +149 -0
  48. package/core/bridge/testing/pageClient.ts +44 -0
  49. package/core/bridge/unverifiedManager.ts +97 -0
  50. package/core/bridge/unverifiedOriginator.ts +79 -0
  51. package/core/config.tsx +1 -16
  52. package/core/constants.ts +7 -11
  53. package/core/context/WalletConnectionContext.tsx +92 -49
  54. package/core/context/WalletContext.tsx +288 -165
  55. package/core/context/sessionTeardown.ts +46 -0
  56. package/core/context/usePairingAttempt.ts +31 -0
  57. package/core/e2e/broadcaster.ts +25 -0
  58. package/core/e2e/consentFixture.ts +46 -0
  59. package/core/e2e/mode.ts +42 -0
  60. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  61. package/core/headers/headerConsensus.ts +230 -0
  62. package/core/headers/headerStore.ts +344 -122
  63. package/core/headers/prewarm.ts +4 -7
  64. package/core/headers/syncHeaders.ts +82 -12
  65. package/core/hooks/usePermissionQueue.ts +89 -34
  66. package/core/i18n/translations.tsx +958 -24
  67. package/core/identity/handleRegistry/client.ts +4 -2
  68. package/core/identity/handleRegistry/resolver.ts +7 -11
  69. package/core/index.ts +17 -0
  70. package/core/localpay/pending.ts +39 -4
  71. package/core/network/boundedFetch.ts +101 -0
  72. package/core/networks.ts +11 -13
  73. package/core/pay/rails/address.ts +5 -4
  74. package/core/pay/rails/handle.ts +3 -1
  75. package/core/pay/rails/sweep.ts +791 -0
  76. package/core/peerpay/brc29.ts +4 -0
  77. package/core/peerpay/handleResendRequests.ts +15 -2
  78. package/core/peerpay/outbox.ts +115 -2
  79. package/core/profiles/assertProfileEmpty.ts +2 -2
  80. package/core/profiles/profileStore.ts +3 -2
  81. package/core/services/arcadeBroadcastProvider.ts +260 -114
  82. package/core/services/autoApprovePolicy.ts +7 -1
  83. package/core/services/capWalletArgs.ts +2 -1
  84. package/core/services/permissionPrompts.ts +132 -0
  85. package/core/services/secrets/kek.ts +5 -0
  86. package/core/services/secrets/migration.ts +27 -2
  87. package/core/services/secrets/policy.ts +6 -0
  88. package/core/services/signingPermissionPolicy.ts +230 -2
  89. package/core/services/vault/VaultKeyService.ts +5 -2
  90. package/core/services/vault/ceremony.ts +2 -2
  91. package/core/services/vault/ceremonyHost.ts +1 -1
  92. package/core/services/vault/guard.ts +20 -0
  93. package/core/services/vault/outputAuthority.ts +76 -0
  94. package/core/services/vault/transfers.ts +52 -28
  95. package/core/services/vault/vaultStore.ts +60 -14
  96. package/core/services/walletArgLimits.ts +17 -2
  97. package/core/services/walletConnectionValidation.ts +13 -1
  98. package/core/services/walletServiceConfig.ts +8 -7
  99. package/core/storage/encryptedDbImage.ts +325 -0
  100. package/core/stores/ConnectionStore.ts +17 -0
  101. package/core/toolboxConfig.ts +78 -2
  102. package/expo-module.config.json +5 -0
  103. package/ios/BoundedBody.swift +15 -0
  104. package/ios/BsvBoundedFetch.podspec +17 -0
  105. package/ios/BsvBoundedFetchModule.swift +121 -0
  106. package/package.json +12 -8
  107. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  108. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  109. package/ui/components/pay/AddressReceive.tsx +6 -2
  110. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  111. package/ui/components/pay/PayCellRow.tsx +3 -1
  112. package/ui/components/pay/PayForm.tsx +12 -2
  113. package/ui/components/pay/RecipientField.tsx +1 -0
  114. package/ui/components/pay/RequestHub.tsx +1 -0
  115. package/ui/components/pay/UniversalSend.tsx +110 -42
  116. package/ui/components/ui/ListRow.tsx +10 -2
  117. package/ui/components/ui/PermissionSheet.tsx +534 -158
  118. package/ui/components/ui/Sheet.tsx +59 -7
  119. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  120. package/ui/components/vault/KeyChooser.tsx +1 -1
  121. package/ui/components/wallet/AmountInput.tsx +4 -1
  122. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  123. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  124. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  125. package/ui/components/wallet/ProfileButton.tsx +1 -0
  126. package/ui/exportDatabases.ts +94 -5
  127. package/ui/hooks/useExportWalletData.ts +37 -24
  128. package/ui/importDatabases.ts +154 -34
  129. package/ui/index.ts +4 -0
  130. package/ui/screens/ConnectionsScreen.tsx +12 -3
  131. package/ui/screens/PairScreen.tsx +10 -3
  132. package/ui/screens/PayScreen.tsx +1 -0
  133. package/ui/screens/TrustScreen.tsx +6 -3
  134. package/ui/screens/VaultScreen.tsx +13 -3
  135. package/ui/screens/VaultTransferScreen.tsx +6 -3
  136. package/ui/screens/WalletConfigScreen.tsx +30 -3
  137. package/ui/screens/WalletHomeScreen.tsx +7 -1
@@ -12,7 +12,8 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
12
12
  import * as SecureStore from 'expo-secure-store'
13
13
  import { openSecret, sealSecret } from './envelope'
14
14
  import { destroyKek, peekKek, provisionKek, readSentinel, recordSecretName } from './kek'
15
- import { envKey, envOptions } from './storage'
15
+ import { envKey, envOptions, kekOptions } from './storage'
16
+ import { KEK_AUTH_KEY, KEK_PLAIN_KEY } from './policy'
16
17
  import { EnvelopeBlob, SECRET_NAMES, SecretName } from './types'
17
18
 
18
19
  /** Keys written by the pre-envelope LocalStorageProvider. */
@@ -112,7 +113,12 @@ export async function migrationAttemptsExhausted(): Promise<boolean> {
112
113
  export async function migrateLegacySecrets(): Promise<MigrationResult> {
113
114
  // Step 0 — idempotence. A committed sentinel means we already migrated;
114
115
  // sweeping here is what makes a crash between commit and delete harmless.
115
- const existing = await readSentinel()
116
+ let existing: Awaited<ReturnType<typeof readSentinel>>
117
+ try {
118
+ existing = await readSentinel({ strict: true })
119
+ } catch {
120
+ return { outcome: 'failed', stage: 'existing-identity', retryable: true }
121
+ }
116
122
  if (existing && existing.names.length > 0) {
117
123
  await sweepLegacyKeys()
118
124
  return { outcome: 'not-needed' }
@@ -136,6 +142,25 @@ export async function migrateLegacySecrets(): Promise<MigrationResult> {
136
142
  return { outcome: 'failed', stage: 'attempts-exhausted', retryable: false }
137
143
  }
138
144
 
145
+ // The sentinel is unauthenticated and can disappear independently of the
146
+ // protected KEK. Never interpret its absence as permission to replace an
147
+ // existing envelope identity with legacy plaintext. Read errors also fail
148
+ // closed; no destructive provisioning or rollback has started yet.
149
+ try {
150
+ for (const name of SECRET_NAMES) {
151
+ if ((await SecureStore.getItemAsync(envKey(name), envOptions)) !== null) {
152
+ return { outcome: 'failed', stage: 'existing-identity', retryable: false }
153
+ }
154
+ }
155
+ for (const [key, authenticated] of [[KEK_AUTH_KEY, true], [KEK_PLAIN_KEY, false]] as const) {
156
+ if ((await SecureStore.getItemAsync(key, kekOptions(authenticated))) !== null) {
157
+ return { outcome: 'failed', stage: 'existing-identity', retryable: false }
158
+ }
159
+ }
160
+ } catch {
161
+ return { outcome: 'failed', stage: 'existing-identity', retryable: true }
162
+ }
163
+
139
164
  // Step 3 — mint the KEK. Costs one prompt on Android, none on iOS.
140
165
  const provisioned = await provisionKek()
141
166
  if (provisioned.status !== 'unlocked') {
@@ -10,6 +10,7 @@
10
10
  * item written with requireAuthentication.
11
11
  */
12
12
  import * as LocalAuthentication from 'expo-local-authentication'
13
+ import { isE2eBuild } from '../../e2e/mode'
13
14
  import { KekPolicy } from './types'
14
15
 
15
16
  /** ALWAYS written with requireAuthentication: true. */
@@ -98,6 +99,10 @@ export async function biometricKind(): Promise<'face' | 'fingerprint' | 'iris' |
98
99
  * so it is not merely unreachable in production, it is not present.
99
100
  */
100
101
  export async function resolveProvisioningPolicy(): Promise<ResolvedPolicy> {
102
+ // The harness stores the key without a biometric ceremony so a simulator
103
+ // with nothing enrolled, and one with Face ID enrolled, take the same path.
104
+ // Production never sets the harness flag, so this branch is not taken there.
105
+ if (isE2eBuild()) return DEV_PLAIN
101
106
  const strong = await hasStrongBiometrics()
102
107
  if (strong) return BIOMETRIC
103
108
  return __DEV__ ? DEV_PLAIN : DEGRADED
@@ -114,6 +119,7 @@ export async function resolveProvisioningPolicy(): Promise<ResolvedPolicy> {
114
119
  * *can* do biometrics must be re-wrapped before the KEK is honoured.
115
120
  */
116
121
  export async function needsUpgrade(current: KekPolicy): Promise<boolean> {
122
+ if (isE2eBuild()) return false
117
123
  if (current === 'biometric') return false
118
124
  if (__DEV__) return false
119
125
  return hasStrongBiometrics()
@@ -1,5 +1,8 @@
1
1
  import { Hash, Utils } from '@bsv/sdk'
2
- import { WalletPermissionsManager } from '@bsv/wallet-toolbox-mobile'
2
+ import { WalletPermissionsManager, type GroupedPermissions } from '@bsv/wallet-toolbox-mobile'
3
+
4
+ /** A site's manifest group request (BRC-73), as the Connect sheet shows it and `mintGroupedPermissions` mints it. */
5
+ export type GroupPermissions = GroupedPermissions
3
6
 
4
7
  /**
5
8
  * Protocols a connected app may sign under without a protocol prompt, even
@@ -92,8 +95,88 @@ interface ManagerInternals {
92
95
  firePermissionRequestEvent(request: ProtocolRequest, key: string): Promise<void>
93
96
  underlying: { verifySignature: WalletPermissionsManager['verifySignature'] }
94
97
  fetchManifestPermissions(originator: string): Promise<ManifestPermissions>
98
+ callEvent(eventName: string, param: unknown): Promise<void>
99
+ denyActiveRequest(requestID: string): void
100
+ filterAlreadyGrantedPermissions(originator: string, group: GroupPermissions): Promise<GroupPermissions>
101
+ buildOriginatorLookupValues(displayOriginator: string | undefined, originator: string): unknown
102
+ persistPermissionGrant(toCreate: MintItem[], toRenew: MintItem[]): Promise<void>
103
+ }
104
+
105
+ /** One permission token to create or renew, as `persistPermissionGrant` takes it. */
106
+ interface MintItem {
107
+ request: Record<string, unknown>
108
+ expiry: number
109
+ amount?: number
110
+ oldToken?: unknown
95
111
  }
96
112
 
113
+ const str = (v: unknown): string => (typeof v === 'string' ? v : '')
114
+ const isObject = (v: unknown): v is Record<string, any> => v !== null && typeof v === 'object' && !Array.isArray(v)
115
+
116
+ /**
117
+ * The manifest group as a well-formed GroupPermissions, or null when it lists nothing. A site writes
118
+ * the manifest, so every entry is checked: one that does not have the shape the manager reads is
119
+ * left out, and what remains is both what the Connect sheet shows and what Connect mints.
120
+ */
121
+ function sanitizeGroup(raw: unknown): GroupPermissions | null {
122
+ if (!isObject(raw)) return null
123
+ const group: GroupPermissions = {}
124
+ if (typeof raw.description === 'string') group.description = raw.description
125
+ const spending = raw.spendingAuthorization
126
+ if (isObject(spending) && Number.isSafeInteger(spending.amount) && spending.amount > 0) {
127
+ group.spendingAuthorization = { amount: spending.amount, description: str(spending.description) }
128
+ }
129
+ const list = (v: unknown): any[] => (Array.isArray(v) ? v.filter(isObject) : [])
130
+ group.protocolPermissions = list(raw.protocolPermissions)
131
+ .filter(
132
+ p =>
133
+ Array.isArray(p.protocolID) &&
134
+ p.protocolID.length === 2 &&
135
+ [0, 1, 2].includes(p.protocolID[0]) &&
136
+ typeof p.protocolID[1] === 'string' &&
137
+ (p.counterparty === undefined || typeof p.counterparty === 'string')
138
+ )
139
+ .map(p => ({
140
+ protocolID: [p.protocolID[0], p.protocolID[1]] as [0 | 1 | 2, string],
141
+ ...(p.counterparty !== undefined ? { counterparty: p.counterparty as string } : {}),
142
+ description: str(p.description)
143
+ }))
144
+ group.basketAccess = list(raw.basketAccess)
145
+ .filter(b => typeof b.basket === 'string' && b.basket.length > 0)
146
+ .map(b => ({ basket: b.basket as string, description: str(b.description) }))
147
+ group.certificateAccess = list(raw.certificateAccess)
148
+ .filter(
149
+ c =>
150
+ typeof c.type === 'string' &&
151
+ typeof c.verifierPublicKey === 'string' &&
152
+ Array.isArray(c.fields) &&
153
+ c.fields.every((f: unknown) => typeof f === 'string')
154
+ )
155
+ .map(c => ({
156
+ type: c.type as string,
157
+ fields: [...c.fields] as string[],
158
+ verifierPublicKey: c.verifierPublicKey as string,
159
+ description: str(c.description)
160
+ }))
161
+ const empty =
162
+ group.spendingAuthorization === undefined &&
163
+ !group.protocolPermissions.length &&
164
+ !group.basketAccess.length &&
165
+ !group.certificateAccess.length
166
+ return empty ? null : group
167
+ }
168
+
169
+ /** The events that put a question to the user (all carry a `requestID`). A
170
+ * retired manager denies these instead of raising them. */
171
+ const PROMPT_EVENTS = new Set([
172
+ 'onProtocolPermissionRequested',
173
+ 'onBasketAccessRequested',
174
+ 'onCertificateAccessRequested',
175
+ 'onSpendingAuthorizationRequested',
176
+ 'onGroupedPermissionRequested',
177
+ 'onCounterpartyPermissionRequested'
178
+ ])
179
+
97
180
  /** The parts of a site's manifest.json permissions the manager reads. */
98
181
  interface ManifestPermissions {
99
182
  groupPermissions: { protocolPermissions?: Array<{ protocolID?: unknown }> } | null
@@ -134,7 +217,10 @@ function withoutAskEveryTime(manifest: ManifestPermissions): ManifestPermissions
134
217
  * cover is ever read back for them; a site's manifest never puts them in a
135
218
  * grouped request; and one origin's createSignature calls under them run
136
219
  * one at a time, so a burst of calls cannot ride on one approval;
137
- * - a non-privileged verifySignature is never prompted.
220
+ * - a non-privileged verifySignature is never prompted;
221
+ * - once retired (its wallet was replaced), it raises no prompt: every prompt
222
+ * event is denied on the spot, so a call still parked inside it ends instead
223
+ * of surfacing a sheet for a wallet that is gone.
138
224
  * Every other check runs unchanged.
139
225
  */
140
226
  export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
@@ -142,6 +228,8 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
142
228
  /** Key ID of the ask-every-time createSignature call each (normalized)
143
229
  * origin has in flight. The per-origin queue keeps it to one at a time. */
144
230
  private readonly keyIDInFlight = new Map<string, string>()
231
+ private retired = false
232
+ private readonly retireHooks: Array<() => void> = []
145
233
 
146
234
  constructor(...args: ConstructorParameters<typeof WalletPermissionsManager>) {
147
235
  super(...args)
@@ -177,6 +265,22 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
177
265
  }
178
266
  return await firePermissionRequestEvent(request, key)
179
267
  }
268
+ // Deny, never throw: a throw out of callEvent would leave the entry its
269
+ // caller registered unsettled (its waiter hangs, and a grouped one holds
270
+ // the per-originator lock). Denying settles the waiter and removes it.
271
+ const callEvent = internals.callEvent.bind(this)
272
+ internals.callEvent = async (eventName, param) => {
273
+ const requestID = (param as { requestID?: unknown } | null | undefined)?.requestID
274
+ if (this.retired && PROMPT_EVENTS.has(eventName) && typeof requestID === 'string') {
275
+ try {
276
+ internals.denyActiveRequest.call(this, requestID)
277
+ } catch {
278
+ // Already settled.
279
+ }
280
+ return
281
+ }
282
+ await callEvent(eventName, param)
283
+ }
180
284
  const fetchManifestPermissions = internals.fetchManifestPermissions.bind(this)
181
285
  internals.fetchManifestPermissions = async originator =>
182
286
  withoutAskEveryTime(await fetchManifestPermissions(originator))
@@ -186,6 +290,130 @@ export class SigningPolicyPermissionsManager extends WalletPermissionsManager {
186
290
  return this as unknown as ManagerInternals
187
291
  }
188
292
 
293
+ /**
294
+ * One-way: from here on this manager raises no prompt. Call it only on a
295
+ * manager that has been replaced, never on the one just published. `onRetire`
296
+ * hooks run in this same synchronous step.
297
+ */
298
+ retire(): void {
299
+ if (this.retired) return
300
+ this.retired = true
301
+ for (const hook of this.retireHooks.splice(0)) {
302
+ try {
303
+ hook()
304
+ } catch {
305
+ // A hook must not stop the others.
306
+ }
307
+ }
308
+ }
309
+
310
+ isRetired(): boolean {
311
+ return this.retired
312
+ }
313
+
314
+ /** Runs `hook` when this manager is retired (immediately if it already is). */
315
+ onRetire(hook: () => void): void {
316
+ if (this.retired) hook()
317
+ else this.retireHooks.push(hook)
318
+ }
319
+
320
+ /**
321
+ * The group this origin's manifest asks for, as the later group check will read it: the same
322
+ * `fetchManifestPermissions` and its 5-minute cache, with ask-every-time protocols already
323
+ * filtered (and, on the unverified manager, spending and token modules). Null when there is no
324
+ * manifest, it lists nothing, or the fetch fails. Raises no prompt.
325
+ */
326
+ async peekGroupPermissions(originator: string): Promise<GroupPermissions | null> {
327
+ try {
328
+ const { normalized } = this.internals.prepareOriginator(originator)
329
+ const { groupPermissions } = await this.internals.fetchManifestPermissions(normalized)
330
+ return sanitizeGroup(groupPermissions)
331
+ } catch {
332
+ return null
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Mints a permission token for every item of `group` that does not already hold one, the way
338
+ * `grantGroupedPermission` does for a granted item, but with no active request to answer. An
339
+ * expired token is renewed. Ask-every-time protocols are never minted. Throws if the mint fails;
340
+ * the caller decides what that means.
341
+ */
342
+ async mintGroupedPermissions(originator: string, group: GroupPermissions): Promise<void> {
343
+ const i = this.internals
344
+ const { normalized } = i.prepareOriginator(originator)
345
+ const wanted: GroupPermissions = {
346
+ ...group,
347
+ protocolPermissions: (group.protocolPermissions ?? []).filter(p => !isAskEveryTimeProtocol(p.protocolID))
348
+ }
349
+ const todo = await i.filterAlreadyGrantedPermissions(normalized, wanted)
350
+ const lookup = i.buildOriginatorLookupValues(originator, normalized)
351
+ const toCreate: MintItem[] = []
352
+ const toRenew: MintItem[] = []
353
+ if (todo.spendingAuthorization != null) {
354
+ toCreate.push({
355
+ request: {
356
+ type: 'spending',
357
+ originator: normalized,
358
+ spending: { satoshis: todo.spendingAuthorization.amount },
359
+ reason: todo.spendingAuthorization.description
360
+ },
361
+ expiry: 0,
362
+ amount: todo.spendingAuthorization.amount
363
+ })
364
+ }
365
+ for (const p of todo.protocolPermissions ?? []) {
366
+ const counterparty = (p.protocolID?.[0] ?? 0) === 1 ? '' : p.counterparty || 'self'
367
+ const request = {
368
+ type: 'protocol',
369
+ originator: normalized,
370
+ privileged: false,
371
+ protocolID: p.protocolID,
372
+ counterparty,
373
+ reason: p.description
374
+ }
375
+ const token = await i.findProtocolToken(normalized, false, p.protocolID, counterparty, true, lookup)
376
+ if (token == null) toCreate.push({ request, expiry: 0 })
377
+ else toRenew.push({ oldToken: token, request, expiry: 0 })
378
+ }
379
+ for (const b of todo.basketAccess ?? []) {
380
+ toCreate.push({
381
+ request: { type: 'basket', originator: normalized, basket: b.basket, reason: b.description },
382
+ expiry: 0
383
+ })
384
+ }
385
+ for (const c of todo.certificateAccess ?? []) {
386
+ toCreate.push({
387
+ request: {
388
+ type: 'certificate',
389
+ originator: normalized,
390
+ privileged: false,
391
+ certificate: { verifier: c.verifierPublicKey, certType: c.type, fields: c.fields },
392
+ reason: c.description
393
+ },
394
+ expiry: 0
395
+ })
396
+ }
397
+ if (toCreate.length === 0 && toRenew.length === 0) return
398
+ await i.persistPermissionGrant(toCreate, toRenew)
399
+ }
400
+
401
+ /** Whether a prompt with this ID is still waiting for an answer. */
402
+ hasActiveRequest(requestID: string): boolean {
403
+ return this.internals.activeRequests.has(requestID)
404
+ }
405
+
406
+ /** Denies every request still waiting for an answer. Never throws. */
407
+ denyAllActiveRequests(): void {
408
+ for (const requestID of [...this.internals.activeRequests.keys()]) {
409
+ try {
410
+ this.internals.denyActiveRequest(requestID)
411
+ } catch {
412
+ // Already settled.
413
+ }
414
+ }
415
+ }
416
+
189
417
  override async ensureProtocolPermission(args: EnsureProtocolPermissionArgs): Promise<boolean> {
190
418
  if (isPromptFreeSigning(args)) {
191
419
  // Still refuse a missing or malformed originator, as the full check
@@ -1180,8 +1180,11 @@ export async function addVaultKey(
1180
1180
  await requireReadyEnrollmentDrafts([record], token, authority)
1181
1181
  const scope = vaultStore.getScope()
1182
1182
  if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
1183
- const meta = await vaultStore.addKey(record, token, next =>
1184
- computeVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, next, scope)
1183
+ const meta = await vaultStore.addKey(
1184
+ record,
1185
+ token,
1186
+ next => computeVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, next, scope),
1187
+ existing
1185
1188
  )
1186
1189
  // XQ-014: record the newly committed serial device-wide.
1187
1190
  await enrolledSerialRegistry.record(record.serial)
@@ -298,8 +298,8 @@ export class CeremonyController {
298
298
  /**
299
299
  * Report post-arm progress from the spend path.
300
300
  *
301
- * Guarded on an armed session: a note with no signer armed (a deposit, which
302
- * is hardware-free, or a caller that has already released) must not raise a
301
+ * Guarded on an armed session: a note with no signer armed (for example,
302
+ * after a deposit's possession proof has been released) must not raise a
303
303
  * sheet, and anything arriving mid-arm is ignored because the arming phases
304
304
  * own the display.
305
305
  *
@@ -46,7 +46,7 @@ export function requestVaultSigner(reason: string, chosenSerial: string): Promis
46
46
  * the ceremony sheet can show activity through the seconds-long stretches
47
47
  * where the JS thread or the network is busy, and so the retention window
48
48
  * tracks a live operation instead of expiring underneath it. A no-op when
49
- * nothing is armed — which is what keeps the hardware-free deposit sheet-free. */
49
+ * nothing is armed, such as after a deposit's possession proof is released. */
50
50
  export function noteVaultProgress(p: VaultProgress): void {
51
51
  ceremony.noteProgress(p)
52
52
  }
@@ -38,6 +38,7 @@ import {
38
38
  type WalletAction,
39
39
  type WalletInterface
40
40
  } from '@bsv/sdk'
41
+ import { DB_EXPORT_PROTOCOL } from '../../storage/encryptedDbImage'
41
42
  import { ownOriginatorLabel } from '../../storage/methods/vaultGuardSql'
42
43
  import { bakedCommitments, R1C_LOCK_LEN, R1C_MAX_KEYS } from './r1comb'
43
44
 
@@ -193,6 +194,15 @@ const CONNECTION_AUTHORITY_PROTOCOL_NAMES = new Set(['connection authority'])
193
194
  * RPC method, authenticating nothing. */
194
195
  const PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES = new Set(['pending abort authority'])
195
196
 
197
+ /** Browser bridge: the `bridge site authority` namespace tags site-consent records and the
198
+ * stored permission policy (core/bridge/permissionPolicy.ts). Reserved for the same reason as
199
+ * `connection authority`: a connected origin must not be able to mint or verify the tag. */
200
+ const BRIDGE_SITE_AUTHORITY_PROTOCOL_NAMES = new Set(['bridge site authority'])
201
+
202
+ /** Export headers wrap the database's AES key under this ordinary self key.
203
+ * Only the admin may use it, including imports of already-created exports. */
204
+ const DB_EXPORT_PROTOCOL_NAMES = new Set([DB_EXPORT_PROTOCOL[1]])
205
+
196
206
  function matchesProtocolNamespace(args: unknown, names: Set<string>): boolean {
197
207
  if (args === null || typeof args !== 'object' || Array.isArray(args)) return false
198
208
  const protocolID = (args as { protocolID?: unknown }).protocolID
@@ -211,6 +221,10 @@ function requestsConnectionAuthorityProtocol(args: unknown): boolean {
211
221
  return matchesProtocolNamespace(args, CONNECTION_AUTHORITY_PROTOCOL_NAMES)
212
222
  }
213
223
 
224
+ function requestsBridgeSiteAuthorityProtocol(args: unknown): boolean {
225
+ return matchesProtocolNamespace(args, BRIDGE_SITE_AUTHORITY_PROTOCOL_NAMES)
226
+ }
227
+
214
228
  function requestsPendingAbortAuthorityProtocol(args: unknown): boolean {
215
229
  return matchesProtocolNamespace(args, PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES)
216
230
  }
@@ -697,12 +711,18 @@ export function guardVaultAccess<T extends WalletInterface>(
697
711
 
698
712
  return async (args: any, originator?: string) => {
699
713
  if (originator === adminOriginator) return await bound(args, originator)
714
+ // Counterparty linkage reveals a root shared secret without naming a
715
+ // protocol. It cannot honor namespace reservations, including the
716
+ // export self key when a caller chooses a related public key.
717
+ if (method === 'revealCounterpartyKeyLinkage') return deny(String(method), originator)
700
718
  if (
701
719
  PRIVILEGED_CAPABLE.has(method) &&
702
720
  (args?.privileged ||
703
721
  requestsVaultProtocol(args) ||
704
722
  requestsConnectionAuthorityProtocol(args) ||
705
723
  requestsPendingAbortAuthorityProtocol(args) ||
724
+ requestsBridgeSiteAuthorityProtocol(args) ||
725
+ matchesProtocolNamespace(args, DB_EXPORT_PROTOCOL_NAMES) ||
706
726
  requestsAddressRailKey(args))
707
727
  ) {
708
728
  return deny(String(method), originator)
@@ -0,0 +1,76 @@
1
+ /** Fresh hardware authority for new funds. A valid root MAC proves that an
2
+ * enrollment was once approved, but cannot distinguish a retired enrollment
3
+ * replayed from storage. R1C is 1-of-N: prove one key that the new lock commits
4
+ * to, for this exact output, before any funding action is created. */
5
+ import { Hash, Utils } from '@bsv/sdk'
6
+ import { p256 } from '@noble/curves/nist.js'
7
+ import { requestVaultSigner } from './ceremonyHost'
8
+ import { randomBytes } from './random'
9
+ import { VaultError } from './types'
10
+ import { vaultStore, type VaultMeta, type VaultScopeToken } from './vaultStore'
11
+
12
+ interface VaultOutputAuthorityContext {
13
+ satoshis: number
14
+ saltKeyId: string
15
+ lockingScript: string
16
+ }
17
+
18
+ export async function requireVaultOutputKeyPossession(
19
+ meta: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'lastUsedSerial'>,
20
+ scope: VaultScopeToken,
21
+ output: VaultOutputAuthorityContext,
22
+ chosenSerial?: string
23
+ ): Promise<void> {
24
+ vaultStore.assertScopeToken(scope)
25
+ const chosen =
26
+ chosenSerial !== undefined
27
+ ? meta.keys.find(key => key.serial === chosenSerial)
28
+ : (meta.keys.find(key => key.serial === meta.lastUsedSerial) ?? meta.keys[0])
29
+ if (!chosen) throw new VaultError('not-enrolled', 'Choose a key committed to the new vault output')
30
+ const digest = Hash.sha256(
31
+ Utils.toArray(
32
+ JSON.stringify({
33
+ v: 1,
34
+ kind: 'vault-new-output',
35
+ walletScope: scope.storageKey,
36
+ chain: scope.chain,
37
+ vaultId: meta.vaultId,
38
+ revision: meta.revision,
39
+ createdAt: meta.createdAt,
40
+ keys: meta.keys.map(key => ({ serial: key.serial, slot: key.slot, pubkey: key.pubkey })),
41
+ satoshis: output.satoshis,
42
+ saltKeyId: output.saltKeyId,
43
+ lockingScriptHash: Utils.toHex(Hash.sha256(Utils.toArray(output.lockingScript, 'hex'))),
44
+ nonce: Utils.toHex(randomBytes(32))
45
+ }),
46
+ 'utf8'
47
+ )
48
+ )
49
+ const signer = await requestVaultSigner('Verify vault key for new funds', chosen.serial)
50
+ try {
51
+ vaultStore.assertScopeToken(scope)
52
+ if (signer.serial !== chosen.serial || signer.pubkey !== chosen.pubkey) {
53
+ throw new VaultError('wrong-key', 'Hardware does not match the new vault output key')
54
+ }
55
+ const signature = await signer.sign(Utils.toHex(digest))
56
+ vaultStore.assertScopeToken(scope)
57
+ let valid = false
58
+ try {
59
+ const der = p256.Signature.fromBytes(Uint8Array.from(signature), 'der')
60
+ valid = p256.verify(
61
+ der.toBytes(),
62
+ Uint8Array.from(digest),
63
+ Uint8Array.from(Utils.toArray(chosen.pubkey, 'hex')),
64
+ {
65
+ prehash: false,
66
+ lowS: false
67
+ }
68
+ )
69
+ } catch {
70
+ /* malformed signatures are failed possession proofs */
71
+ }
72
+ if (!valid) throw new VaultError('wrong-key', 'Hardware failed the new vault output possession challenge')
73
+ } finally {
74
+ signer.release()
75
+ }
76
+ }