@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -14,6 +14,7 @@ import {
14
14
  Validation,
15
15
  type ListActionsArgs,
16
16
  type ListActionsResult,
17
+ type ListOutputsArgs,
17
18
  type WalletAction,
18
19
  type WalletInterface
19
20
  } from '@bsv/sdk'
@@ -30,6 +31,20 @@ const MAX_EXTERNAL_ACTION_RESULTS = 500
30
31
  const MAX_EXTERNAL_ACTION_LABELS = 64
31
32
  const MAX_EXTERNAL_ACTION_LABEL_BYTES = 4096
32
33
  const MAX_EXTERNAL_ACTION_OFFSET = MAX_ACTION_SCAN
34
+ /**
35
+ * XR-019: listOutputs had no bridge-level bound at all beyond the SDK's own
36
+ * hard ceiling (limit <= 10000) — a normal-sized *request* from an
37
+ * authenticated paired peer can still force a normal-sized *response* to
38
+ * balloon, because each row can carry a full aggregate BEEF
39
+ * (includeTransactions) or a locking script. These are deliberately far
40
+ * below the SDK's 10000 cap: they bound what a legitimate basket check
41
+ * (a handful to a few hundred rows) ever needs, the same relationship
42
+ * MAX_EXTERNAL_ACTION_RESULTS has to listActions' own 10000 SDK ceiling.
43
+ * The transactions variant is tighter because each row then also carries a
44
+ * full BEEF, not just an outpoint + locking script.
45
+ */
46
+ const MAX_EXTERNAL_LIST_OUTPUTS_RESULTS = 200
47
+ const MAX_EXTERNAL_LIST_OUTPUTS_RESULTS_WITH_TRANSACTIONS = 25
33
48
  /** Permission-backed reads must never retain the exclusive inventory slot
34
49
  * indefinitely while a connected origin leaves a prompt unanswered. */
35
50
  export const EXTERNAL_ACTION_READ_TIMEOUT_MS = 30_000
@@ -73,19 +88,78 @@ const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
73
88
  ])
74
89
  /** Protocol namespaces whose derived keys are internal Vault state. The
75
90
  * permissions manager deliberately exempts ordinary public-key revelation,
76
- * so this boundary must reserve them even when `privileged` is false. */
77
- const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt'])
78
-
79
- function requestsVaultProtocol(args: unknown): boolean {
91
+ * so this boundary must reserve them even when `privileged` is false.
92
+ *
93
+ * XR-001 / XR-002: `vault meta` is the namespace metaAuthority.ts computes
94
+ * every vault-meta and enrollment-draft integrity tag under (see its own
95
+ * header). Reserving it here means a connected/paired origin can never mint
96
+ * or verify one of those tags itself over the site-scoped WalletClient's
97
+ * forwarded createHmac/verifyHmac (WalletConnectionContext.tsx's
98
+ * IMPLEMENTED_METHODS) — only an admin-originator call from this package's
99
+ * own vault code ever reaches it. */
100
+ const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt', 'vault marker', 'vault descriptor', 'vault meta'])
101
+
102
+ /** Protocol namespaces this package's OWN internal, fund-controlling payment
103
+ * rails derive under: the BRC-29 address rail / PeerPay (address.ts's
104
+ * BRC29_PROTOCOL_ID and localpay/pending.ts's identical PEERPAY_PROTOCOL_ID,
105
+ * both `[2, '3241645161d8']`) and the FT/mandala-token rail (localpay/verify.ts's
106
+ * FT_PROTOCOL_ID, `[2, 'mandala token']`). These are not Vault state, but
107
+ * core/localpay/build.ts proves createSignature+getPublicKey over them is
108
+ * sufficient to construct a valid spend -- so a connected origin must not be
109
+ * able to mint either primitive under these namespaces itself, exactly as
110
+ * for Vault's own namespaces. */
111
+ const RESERVED_RAIL_PROTOCOL_NAMES = new Set(['3241645161d8', 'mandala token'])
112
+
113
+ /** XR-027: protocol namespace this package's own saved-pairing authority tag
114
+ * is derived under. A saved connection's approved (origin, topic, protocolID,
115
+ * backendIdentityKey) tuple is MAC'd with the admin-scoped wallet at approval
116
+ * time (core/services/connectionAuthority.ts) and re-verified before every
117
+ * reconnect. A connected/paired origin must never be able to mint or verify
118
+ * this tag itself: the site-scoped WalletClient handed to a paired peer
119
+ * forwards createHmac/verifyHmac for any NON-reserved namespace (see
120
+ * IMPLEMENTED_METHODS in WalletConnectionContext.tsx), so computing this tag
121
+ * there would make it trivially reproducible by that same peer over the
122
+ * already-allowlisted RPC method -- worse than no tag at all. Reserving the
123
+ * namespace here, exactly like Vault's own, is what makes the admin-only
124
+ * computation in connectionAuthority.ts actually mean something. */
125
+ const CONNECTION_AUTHORITY_PROTOCOL_NAMES = new Set(['connection authority'])
126
+
127
+ /** XR-102 (non-Vault residual): protocol namespace `core/localpay/
128
+ * pendingAbortAuthority.ts`'s HMAC tag is derived under. `pending_aborts` is a
129
+ * plain KV record with no MAC of its own; `queuePendingAbort` tags each entry
130
+ * it writes, and `replayPendingAborts` drops any entry whose tag is missing or
131
+ * does not verify before ever calling `abortAction` -- see that module's own
132
+ * doc. Reserved for exactly the same reason as `connection authority` above:
133
+ * a connected/paired origin's site-scoped WalletClient forwards createHmac/
134
+ * verifyHmac for any non-reserved namespace, so without this reservation that
135
+ * same peer could mint or verify the tag itself over the already-allowlisted
136
+ * RPC method, authenticating nothing. */
137
+ const PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES = new Set(['pending abort authority'])
138
+
139
+ function matchesProtocolNamespace(args: unknown, names: Set<string>): boolean {
80
140
  if (args === null || typeof args !== 'object' || Array.isArray(args)) return false
81
141
  const protocolID = (args as { protocolID?: unknown }).protocolID
82
142
  // Match KeyDeriver.computeInvoiceNumber's namespace normalization exactly.
83
143
  // Otherwise e.g. ` VAULT SALT ` reaches the same child key while evading a
84
144
  // literal boundary comparison. Reject matching malformed/extended tuples
85
145
  // here too; validation deeper in the wallet is not an authorization layer.
86
- return Array.isArray(protocolID) &&
87
- typeof protocolID[1] === 'string' &&
88
- VAULT_PROTOCOL_NAMES.has(protocolID[1].toLowerCase().trim())
146
+ return Array.isArray(protocolID) && typeof protocolID[1] === 'string' && names.has(protocolID[1].toLowerCase().trim())
147
+ }
148
+
149
+ function requestsVaultProtocol(args: unknown): boolean {
150
+ return matchesProtocolNamespace(args, VAULT_PROTOCOL_NAMES)
151
+ }
152
+
153
+ function requestsReservedRailProtocol(args: unknown): boolean {
154
+ return matchesProtocolNamespace(args, RESERVED_RAIL_PROTOCOL_NAMES)
155
+ }
156
+
157
+ function requestsConnectionAuthorityProtocol(args: unknown): boolean {
158
+ return matchesProtocolNamespace(args, CONNECTION_AUTHORITY_PROTOCOL_NAMES)
159
+ }
160
+
161
+ function requestsPendingAbortAuthorityProtocol(args: unknown): boolean {
162
+ return matchesProtocolNamespace(args, PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES)
89
163
  }
90
164
 
91
165
  /** Operations that can name an existing output or unsigned action without
@@ -98,6 +172,27 @@ const OUTPUT_NAMING = new Set<keyof WalletInterface>([
98
172
  'abortAction'
99
173
  ])
100
174
 
175
+ /**
176
+ * XR-102: opts an `abortAction` call made WITH `adminOriginator` into the same
177
+ * vault-inventory reference check every non-admin caller already gets below,
178
+ * instead of the admin bypass.
179
+ *
180
+ * `core/localpay/pendingAborts.ts`'s `replayPendingAborts` runs unattended at
181
+ * every wallet build, over a `reference` it read back from a plain KV record —
182
+ * writable by anything with local storage access, and never independently
183
+ * verified. It MUST call the real wallet with `adminOriginator`: the
184
+ * toolbox's own `assertPendingActionOriginator` requires the exact originator
185
+ * an action was created under, and every first-party `createAction` in this
186
+ * app (every ordinary nearby payment included) uses `adminOriginator` — so a
187
+ * different originator here would fail every legitimate replay, not just a
188
+ * forged one. That leaves no way to tell a replay apart from a live
189
+ * interactive admin flow by originator alone; this marker is the side
190
+ * channel instead. It travels only as an in-process object property — never
191
+ * serialized, never sent anywhere — and guard.ts strips it before the real
192
+ * wallet ever sees an `args` object.
193
+ */
194
+ export const VAULT_ABORT_REPLAY_MARKER = Symbol('vault-guard-replay-abort')
195
+
101
196
  interface ExtendedWalletAction extends WalletAction {
102
197
  reference?: string
103
198
  }
@@ -153,7 +248,9 @@ async function withGuardSlot<T>(runtime: GuardRuntime, work: () => Promise<T>, t
153
248
  runtime.queued++
154
249
  const predecessor = runtime.tail
155
250
  let release!: () => void
156
- runtime.tail = new Promise<void>(resolve => { release = resolve })
251
+ runtime.tail = new Promise<void>(resolve => {
252
+ release = resolve
253
+ })
157
254
  await predecessor
158
255
  try {
159
256
  return await work()
@@ -202,6 +299,28 @@ function externalReadKey(args: ValidatedListActionsArgs, originator: string): st
202
299
  return `${originator}\0${JSON.stringify(args)}`
203
300
  }
204
301
 
302
+ type ValidatedListOutputsArgs = ReturnType<typeof Validation.validateListOutputsArgs>
303
+
304
+ /**
305
+ * XR-019: bound limit/offset for an external listOutputs call BEFORE it
306
+ * reaches the underlying wallet, mirroring validateExternalListActionsArgs
307
+ * above. The SDK's own validateListOutputsArgs already clamps limit to
308
+ * [1, 10000] and offset to a non-negative integer — this only tightens that
309
+ * ceiling for a non-admin caller, it does not relax anything the SDK enforces.
310
+ */
311
+ function validateExternalListOutputsArgs(args: unknown): ValidatedListOutputsArgs {
312
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) {
313
+ throw new Error('Invalid listOutputs arguments')
314
+ }
315
+ const requested = Validation.validateListOutputsArgs(args as ListOutputsArgs)
316
+ const cap = requested.includeTransactions
317
+ ? MAX_EXTERNAL_LIST_OUTPUTS_RESULTS_WITH_TRANSACTIONS
318
+ : MAX_EXTERNAL_LIST_OUTPUTS_RESULTS
319
+ if (requested.limit > cap) throw new Error('listOutputs limit is too large')
320
+ if (requested.offset > MAX_EXTERNAL_ACTION_OFFSET) throw new Error('listOutputs offset is too large')
321
+ return requested
322
+ }
323
+
205
324
  interface ReadDeadline {
206
325
  expiresAt: number
207
326
  }
@@ -212,8 +331,14 @@ async function beforeReadDeadline<T>(promise: Promise<T>, deadline: ReadDeadline
212
331
  return await new Promise<T>((resolve, reject) => {
213
332
  const timer = setTimeout(() => reject(new Error('Guarded wallet read timed out')), remaining)
214
333
  promise.then(
215
- value => { clearTimeout(timer); resolve(value) },
216
- error => { clearTimeout(timer); reject(error) }
334
+ value => {
335
+ clearTimeout(timer)
336
+ resolve(value)
337
+ },
338
+ error => {
339
+ clearTimeout(timer)
340
+ reject(error)
341
+ }
217
342
  )
218
343
  })
219
344
  }
@@ -328,10 +453,19 @@ function sanitizeAction(action: ExtendedWalletAction, requested: ListActionsArgs
328
453
  })
329
454
  }
330
455
  if (!requested.includeOutputs) delete safe.outputs
331
- else if (!requested.includeOutputLockingScripts && safe.outputs) {
456
+ else if (safe.outputs) {
457
+ // XR-037 (defense-in-depth): customInstructions is wallet-private
458
+ // metadata (a BRC-42 keyID/counterparty derivation tuple, for a Mandala
459
+ // output) that only the app's own admin originator may ever see. The
460
+ // vendored Wallet.listActions patch already strips it beneath this
461
+ // layer, but this external-facing sanitizer must not rely solely on
462
+ // that patch surviving a future @bsv/wallet-toolbox-mobile bump — it
463
+ // never reaches a non-admin caller through THIS path either way.
464
+ const stripLockingScript = !requested.includeOutputLockingScripts
332
465
  safe.outputs = safe.outputs.map(output => {
333
466
  const copy = { ...output }
334
- delete copy.lockingScript
467
+ if (stripLockingScript) delete copy.lockingScript
468
+ delete copy.customInstructions
335
469
  return copy
336
470
  })
337
471
  }
@@ -347,11 +481,17 @@ async function listActionsForExternal(
347
481
  const { offset, limit } = requested
348
482
  let visibleCount = 0
349
483
  const visible: ExtendedWalletAction[] = []
350
- await scanAllActions(call, { ...requested, limit: undefined, offset: undefined }, originator, action => {
351
- if (isSensitiveAction(action)) return
352
- if (visibleCount >= offset && visible.length < limit) visible.push(sanitizeAction(action, requested))
353
- visibleCount++
354
- }, deadline)
484
+ await scanAllActions(
485
+ call,
486
+ { ...requested, limit: undefined, offset: undefined },
487
+ originator,
488
+ action => {
489
+ if (isSensitiveAction(action)) return
490
+ if (visibleCount >= offset && visible.length < limit) visible.push(sanitizeAction(action, requested))
491
+ visibleCount++
492
+ },
493
+ deadline
494
+ )
355
495
  return {
356
496
  totalActions: visibleCount,
357
497
  actions: visible
@@ -423,11 +563,12 @@ function requestedOutpoints(method: keyof WalletInterface, args: any): string[]
423
563
  }
424
564
  }
425
565
  const canonical = values.map(canonicalOutpoint)
426
- return canonical.some(value => value === undefined) ? undefined : canonical as string[]
566
+ return canonical.some(value => value === undefined) ? undefined : (canonical as string[])
427
567
  }
428
568
 
429
569
  function carriesR1COutput(method: keyof WalletInterface, args: any): boolean {
430
- if (method === 'createAction') return !!args?.outputs?.some((output: any) => isR1CLockingScript(output?.lockingScript))
570
+ if (method === 'createAction')
571
+ return !!args?.outputs?.some((output: any) => isR1CLockingScript(output?.lockingScript))
431
572
  if (method !== 'internalizeAction') return false
432
573
  try {
433
574
  const tx = Transaction.fromAtomicBEEF(args?.tx)
@@ -471,9 +612,8 @@ export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOrig
471
612
  // stalls, later reads expire together instead of each retaining the
472
613
  // critical slot for another full timeout.
473
614
  const deadline = { expiresAt: Date.now() + EXTERNAL_ACTION_READ_TIMEOUT_MS }
474
- const pending = withGuardSlot(
475
- runtime,
476
- () => listActionsForExternal(bound, requested, externalOriginator, deadline)
615
+ const pending = withGuardSlot(runtime, () =>
616
+ listActionsForExternal(bound, requested, externalOriginator, deadline)
477
617
  )
478
618
  runtime.reads.set(key, pending)
479
619
  try {
@@ -487,24 +627,70 @@ export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOrig
487
627
  }
488
628
  }
489
629
 
630
+ // XR-019: listOutputs had no bridge-level bound at all — a non-admin
631
+ // caller could request an arbitrarily (well, SDK-cap-arbitrarily: up to
632
+ // 10000) large page, and includeTransactions makes each row carry a
633
+ // full aggregate BEEF, big enough to plausibly OOM a mobile app. This
634
+ // is a resource bound, not a Vault-outpoint check, so it runs for every
635
+ // non-admin originator regardless of PRIVILEGED_CAPABLE/OUTPUT_NAMING
636
+ // membership, exactly like the listActions case above.
637
+ if (method === 'listOutputs') {
638
+ return async (args: unknown, originator?: string) => {
639
+ if (originator === adminOriginator) return await bound(args, originator)
640
+ // Only the bound-validation step is caught here: a rejection from
641
+ // `bound` itself (the underlying wallet/permissions-manager call)
642
+ // must propagate unchanged, not be swallowed into a generic
643
+ // "not permitted" — the admin-basket rule that already refuses an
644
+ // admin-vault listOutputs one layer further out (see this test's
645
+ // own file: proofBar.railIsolation.test.ts's I3 listOutputs case)
646
+ // throws its own specific error, and this bound must never mask it.
647
+ let requested: ValidatedListOutputsArgs
648
+ try {
649
+ requested = validateExternalListOutputsArgs(args)
650
+ } catch {
651
+ return deny(String(method), originator)
652
+ }
653
+ return await bound(requested, originator)
654
+ }
655
+ }
656
+
490
657
  if (!PRIVILEGED_CAPABLE.has(method) && !OUTPUT_NAMING.has(method)) return value.bind(target)
491
658
 
492
659
  return async (args: any, originator?: string) => {
493
- if (PRIVILEGED_CAPABLE.has(method) && originator !== adminOriginator && requestsVaultProtocol(args)) {
660
+ if (
661
+ PRIVILEGED_CAPABLE.has(method) &&
662
+ originator !== adminOriginator &&
663
+ (requestsVaultProtocol(args) ||
664
+ requestsReservedRailProtocol(args) ||
665
+ requestsConnectionAuthorityProtocol(args) ||
666
+ requestsPendingAbortAuthorityProtocol(args))
667
+ ) {
494
668
  return deny(String(method), originator)
495
669
  }
496
670
  if (PRIVILEGED_CAPABLE.has(method) && args?.privileged && originator !== adminOriginator) {
497
671
  return deny(String(method), originator)
498
672
  }
673
+ // XR-102: an admin-originator `abortAction` marked as a replay (see
674
+ // `VAULT_ABORT_REPLAY_MARKER`) is never trusted with the bypass below —
675
+ // it did not come from a live interactive admin flow, only from a
676
+ // locally-stored reference nothing has independently verified. Strip
677
+ // the marker before either branch below ever sees `args`: it is a
678
+ // guard-internal signal, not part of the real abortAction shape.
679
+ const isReplayAbort =
680
+ method === 'abortAction' &&
681
+ args != null &&
682
+ typeof args === 'object' &&
683
+ (args as Record<PropertyKey, unknown>)[VAULT_ABORT_REPLAY_MARKER] === true
684
+ const callArgs = isReplayAbort ? { reference: (args as { reference?: unknown }).reference } : args
499
685
  // Admin output/action mutations use the same exclusive slot as the
500
686
  // external inventory scan + use. This closes the same-count/TOCTOU
501
687
  // race without caching an inventory snapshot. The raw underlying
502
688
  // wallet remains an internal trust boundary; every externally handed
503
689
  // proxy shares this runtime through the WeakMap above.
504
- if (originator === adminOriginator && OUTPUT_NAMING.has(method)) {
505
- return await withGuardSlot(runtime, () => bound(args, originator), true)
690
+ if (originator === adminOriginator && OUTPUT_NAMING.has(method) && !isReplayAbort) {
691
+ return await withGuardSlot(runtime, () => bound(callArgs, originator), true)
506
692
  }
507
- if (originator !== adminOriginator && OUTPUT_NAMING.has(method)) {
693
+ if ((originator !== adminOriginator || isReplayAbort) && OUTPUT_NAMING.has(method)) {
508
694
  if (runtime.queued >= MAX_GUARDED_QUEUE) return deny(String(method), originator)
509
695
  return await withGuardSlot(runtime, async () => {
510
696
  let inventory: VaultInventory
@@ -516,25 +702,25 @@ export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOrig
516
702
  } catch {
517
703
  return deny(String(method), originator)
518
704
  }
519
- const outpoints = requestedOutpoints(method, args)
705
+ const outpoints = requestedOutpoints(method, callArgs)
520
706
  if (outpoints === undefined || outpoints.some(outpoint => inventory.outpoints.has(outpoint))) {
521
707
  return deny(String(method), originator)
522
708
  }
523
709
  if (
524
710
  (method === 'signAction' || method === 'abortAction') &&
525
- inventory.references.has(String(args?.reference ?? ''))
711
+ inventory.references.has(String(callArgs?.reference ?? ''))
526
712
  ) {
527
713
  return deny(String(method), originator)
528
714
  }
529
- const sendWith = requestedSendWithTxids(method, args)
715
+ const sendWith = requestedSendWithTxids(method, callArgs)
530
716
  if (sendWith === undefined || sendWith.some(txid => inventory.txids.has(txid))) {
531
717
  return deny(String(method), originator)
532
718
  }
533
- if (carriesR1COutput(method, args)) return deny(String(method), originator)
534
- return await bound(args, originator)
719
+ if (carriesR1COutput(method, callArgs)) return deny(String(method), originator)
720
+ return await bound(callArgs, originator)
535
721
  })
536
722
  }
537
- return await bound(args, originator)
723
+ return await bound(callArgs, originator)
538
724
  }
539
725
  }
540
726
  })
@@ -9,10 +9,29 @@ import { VaultError } from './types'
9
9
  */
10
10
  let holder: symbol | null = null
11
11
 
12
+ /** XR-004: bumped by every successful acquireVaultHardwareLease() call. The
13
+ * JS-visible timeout/detach race in session.ts's withKeySession can settle —
14
+ * and free this lease — while the real work() promise it raced is still
15
+ * pending: the native calls it wraps cannot be cancelled. A caller that
16
+ * captured its own generation right after acquiring can later ask
17
+ * isCurrentVaultHardwareGeneration whether a NEWER session has since been
18
+ * acquired, i.e. whether its own continuation has been abandoned and
19
+ * superseded — and refuse its next mutation instead of racing a retry. */
20
+ let generation = 0
21
+
22
+ export function currentVaultHardwareGeneration(): number {
23
+ return generation
24
+ }
25
+
26
+ export function isCurrentVaultHardwareGeneration(capturedGeneration: number): boolean {
27
+ return capturedGeneration === generation
28
+ }
29
+
12
30
  export function acquireVaultHardwareLease(): () => void {
13
31
  if (holder) throw new VaultError('ceremony-active', 'Another Vault hardware operation is already active')
14
32
  const token = Symbol('vault-hardware-lease')
15
33
  holder = token
34
+ generation++
16
35
  let released = false
17
36
  return () => {
18
37
  if (released) return
@@ -0,0 +1,210 @@
1
+ /**
2
+ * XR-001 / XR-002 — wallet-root-authenticated integrity tags for Vault
3
+ * metadata and enrollment drafts.
4
+ *
5
+ * Threat (SEC2-087 / SEC2-088): an attacker who can WRITE the app's
6
+ * SecureStore (vault meta and enrollment drafts) but does not hold the
7
+ * wallet root (the mnemonic-derived key, behind the biometric-protected KEK
8
+ * in release builds) can forge (a) a higher-revision vault meta with a
9
+ * substituted key set, so the next deposit/re-vault/re-lock commits only
10
+ * attacker keys, or (b) a `ready` enrollment draft that injects an attacker
11
+ * key. Both were previously accepted on bare structural validation alone
12
+ * (isVaultMeta / isVaultKeyRecord), which proves SHAPE, never AUTHORITY.
13
+ *
14
+ * Fix: every legitimate code path that writes vault meta or a `ready` draft
15
+ * computes an HMAC over a canonical encoding of exactly the fields that
16
+ * confer spend authority, using `wallet.createHmac` under the
17
+ * ADMIN-reserved `vault meta` protocol namespace (guard.ts's
18
+ * VAULT_PROTOCOL_NAMES) — a namespace a connected/paired caller is refused,
19
+ * exactly mirroring connectionAuthority.ts's `connection authority` tag.
20
+ * A SecureStore-only attacker never runs the wallet's own code at all, so
21
+ * they cannot compute a valid tag no matter what content they write.
22
+ *
23
+ * The tag is stored BESIDE the record (vaultStore.ts keeps it in a separate
24
+ * SecureStore item, never inside the VaultMeta/EnrollmentDraft JSON itself)
25
+ * and re-verified before that record is ever trusted as authority: before
26
+ * any output-creating operation uses `meta.keys`/`meta.revision`
27
+ * (transfers.ts's `requireAuthenticatedMeta`), and before
28
+ * `requireReadyEnrollmentDrafts`/`resumeEnrollmentDraft` trust a `ready`
29
+ * draft (VaultKeyService.ts).
30
+ *
31
+ * WHY THESE FIELDS AND NOT OTHERS. The tagged meta payload is exactly
32
+ * `vaultId`, `revision`, `createdAt`, the ordered key list (serial/slot/
33
+ * pubkey) and `pendingRemoval` — the fields `newVaultOutput` bakes into a
34
+ * new R1C lock, or that gate a two-phase key removal. Cosmetic/local-only
35
+ * fields (`nickname`, `enrolledAt`, `lastUsedAt`/`lastUsedSerial`,
36
+ * `recovery.adoptedSerials`) are deliberately EXCLUDED: they never feed a
37
+ * new output's lock, and including them would force a fresh tag on every
38
+ * rename/last-use/adoption write in addition to every revision-bumping one,
39
+ * without closing any additional attack surface (see vaultStore.ts's
40
+ * markKeyAdopted/noteLastUsed/renameKey for where this matters).
41
+ */
42
+ import type { WalletInterface } from '@bsv/sdk'
43
+ import type { VaultKeyRecord, VaultMeta, VaultPendingRemoval, VaultStoreScope } from './vaultStore'
44
+
45
+ /** Reserved in core/services/vault/guard.ts's VAULT_PROTOCOL_NAMES so a
46
+ * connected/paired caller can never mint or verify this tag itself. */
47
+ export const VAULT_META_PROTOCOL_ID = [2, 'vault meta'] as const
48
+
49
+ /** The narrow wallet surface this module needs — matches
50
+ * connectionAuthority.ts's HmacCapableWallet. Real callers pass the
51
+ * ADMIN-scoped wallet (guardVaultAccess(..., adminOriginator)), and must call
52
+ * with `adminOriginator` so guard.ts's reservation recognizes the call as
53
+ * trusted rather than refusing it. */
54
+ export type HmacCapableWallet = Pick<WalletInterface, 'createHmac' | 'verifyHmac'>
55
+
56
+ type TaggedMetaFields = Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'pendingRemoval'>
57
+
58
+ function canonicalKeyFields(k: Pick<VaultKeyRecord, 'serial' | 'slot' | 'pubkey'>) {
59
+ return { serial: k.serial, slot: k.slot, pubkey: k.pubkey }
60
+ }
61
+
62
+ function canonicalPendingRemoval(p: VaultPendingRemoval | undefined) {
63
+ if (!p) return null
64
+ return { key: canonicalKeyFields(p.key), keyIndex: p.keyIndex, revision: p.revision, state: p.state }
65
+ }
66
+
67
+ function bytesOf(payload: unknown): number[] {
68
+ return Array.from(new TextEncoder().encode(JSON.stringify(payload)))
69
+ }
70
+
71
+ /** Canonical, versioned message for a VaultMeta's authority fields. */
72
+ function vaultMetaAuthorityMessage(meta: TaggedMetaFields, scope: VaultStoreScope): number[] {
73
+ return bytesOf({
74
+ v: 1,
75
+ kind: 'vault-meta',
76
+ identityKey: scope.identityKey,
77
+ chain: scope.chain,
78
+ vaultId: meta.vaultId,
79
+ revision: meta.revision,
80
+ createdAt: meta.createdAt,
81
+ keys: meta.keys.map(canonicalKeyFields),
82
+ pendingRemoval: canonicalPendingRemoval(meta.pendingRemoval)
83
+ })
84
+ }
85
+
86
+ function metaKeyId(scope: VaultStoreScope): string {
87
+ return `${scope.chain}:meta`
88
+ }
89
+
90
+ /** Called by every legitimate meta-writing path immediately before its
91
+ * SecureStore write (see vaultStore.ts's `VaultMetaTagger`). */
92
+ export async function computeVaultMetaAuthorityTag(
93
+ wallet: HmacCapableWallet,
94
+ adminOriginator: string,
95
+ meta: TaggedMetaFields,
96
+ scope: VaultStoreScope
97
+ ): Promise<string> {
98
+ const { hmac } = await wallet.createHmac(
99
+ {
100
+ protocolID: [...VAULT_META_PROTOCOL_ID],
101
+ keyID: metaKeyId(scope),
102
+ counterparty: 'self',
103
+ data: vaultMetaAuthorityMessage(meta, scope)
104
+ },
105
+ adminOriginator
106
+ )
107
+ return Buffer.from(hmac).toString('base64url')
108
+ }
109
+
110
+ /**
111
+ * Re-derives the tag over the CURRENT (possibly tampered) meta and compares
112
+ * it to the one on file. Never throws: a missing tag, a malformed tag, a
113
+ * mismatched meta, or any wallet-side failure are all indistinguishable
114
+ * "not authentic" outcomes — the caller must fail closed on every one of
115
+ * them, never distinguish "corrupt tag" from "wrong tag" for the user.
116
+ */
117
+ export async function verifyVaultMetaAuthorityTag(
118
+ wallet: HmacCapableWallet,
119
+ adminOriginator: string,
120
+ meta: TaggedMetaFields,
121
+ scope: VaultStoreScope,
122
+ tag: string | null | undefined
123
+ ): Promise<boolean> {
124
+ if (!tag) return false
125
+ try {
126
+ const hmac = Array.from(Buffer.from(tag, 'base64url'))
127
+ if (hmac.length === 0) return false
128
+ const { valid } = await wallet.verifyHmac(
129
+ {
130
+ protocolID: [...VAULT_META_PROTOCOL_ID],
131
+ keyID: metaKeyId(scope),
132
+ counterparty: 'self',
133
+ data: vaultMetaAuthorityMessage(meta, scope),
134
+ hmac
135
+ },
136
+ adminOriginator
137
+ )
138
+ return valid === true
139
+ } catch {
140
+ return false
141
+ }
142
+ }
143
+
144
+ /** Canonical, versioned message for one enrollment draft record's `ready`
145
+ * authority — the sole assurance level a commit path (finalizeEnrollment /
146
+ * addVaultKey via requireReadyEnrollmentDrafts, or resumeEnrollmentDraft's
147
+ * fast path) ever trusts without repeating a live driver challenge. Lower
148
+ * assurance levels ('management-uncertain', 'challenge-required') are never
149
+ * tagged: every code path that reads them already requires a fresh
150
+ * driver.signEcdsa challenge before doing anything with them, so a forged
151
+ * draft at those levels gains nothing. */
152
+ function vaultDraftAuthorityMessage(record: Pick<VaultKeyRecord, 'serial' | 'slot' | 'pubkey'>, scope: VaultStoreScope): number[] {
153
+ return bytesOf({
154
+ v: 1,
155
+ kind: 'vault-enrollment-draft',
156
+ identityKey: scope.identityKey,
157
+ chain: scope.chain,
158
+ assurance: 'ready',
159
+ record: canonicalKeyFields(record)
160
+ })
161
+ }
162
+
163
+ function draftKeyId(scope: VaultStoreScope, serial: string): string {
164
+ return `${scope.chain}:draft:${serial}`
165
+ }
166
+
167
+ export async function computeVaultDraftAuthorityTag(
168
+ wallet: HmacCapableWallet,
169
+ adminOriginator: string,
170
+ record: Pick<VaultKeyRecord, 'serial' | 'slot' | 'pubkey'>,
171
+ scope: VaultStoreScope
172
+ ): Promise<string> {
173
+ const { hmac } = await wallet.createHmac(
174
+ {
175
+ protocolID: [...VAULT_META_PROTOCOL_ID],
176
+ keyID: draftKeyId(scope, record.serial),
177
+ counterparty: 'self',
178
+ data: vaultDraftAuthorityMessage(record, scope)
179
+ },
180
+ adminOriginator
181
+ )
182
+ return Buffer.from(hmac).toString('base64url')
183
+ }
184
+
185
+ export async function verifyVaultDraftAuthorityTag(
186
+ wallet: HmacCapableWallet,
187
+ adminOriginator: string,
188
+ record: Pick<VaultKeyRecord, 'serial' | 'slot' | 'pubkey'>,
189
+ scope: VaultStoreScope,
190
+ tag: string | null | undefined
191
+ ): Promise<boolean> {
192
+ if (!tag) return false
193
+ try {
194
+ const hmac = Array.from(Buffer.from(tag, 'base64url'))
195
+ if (hmac.length === 0) return false
196
+ const { valid } = await wallet.verifyHmac(
197
+ {
198
+ protocolID: [...VAULT_META_PROTOCOL_ID],
199
+ keyID: draftKeyId(scope, record.serial),
200
+ counterparty: 'self',
201
+ data: vaultDraftAuthorityMessage(record, scope),
202
+ hmac
203
+ },
204
+ adminOriginator
205
+ )
206
+ return valid === true
207
+ } catch {
208
+ return false
209
+ }
210
+ }