@bsv/expo-wallet-toolbox 0.4.0 → 0.5.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 (118) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +0 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +9 -1
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +409 -20
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +97 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/storage/StorageExpoSQLite.ts +382 -56
  54. package/core/storage/dbImage.ts +48 -0
  55. package/core/storage/methods/findSql.ts +0 -54
  56. package/core/storage/methods/listOutputsSql.ts +7 -3
  57. package/core/storage/methods/offlineActions.ts +15 -0
  58. package/core/storage/methods/processOfflineActions.ts +263 -6
  59. package/core/storage/methods/walletBalanceSql.ts +16 -4
  60. package/core/storage/schema/createTables.ts +123 -0
  61. package/core/storage/sqlUpdateValue.ts +24 -0
  62. package/core/toolboxConfig.ts +112 -1
  63. package/core/walletRepair/runWalletCheck.ts +19 -2
  64. package/package.json +25 -24
  65. package/ui/components/QRScanner.tsx +1 -1
  66. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  67. package/ui/components/pay/AssetPicker.tsx +184 -0
  68. package/ui/components/pay/AvailableBalance.tsx +33 -2
  69. package/ui/components/pay/HandleReceive.tsx +213 -50
  70. package/ui/components/pay/NearbyFlow.tsx +616 -69
  71. package/ui/components/pay/PayForm.tsx +73 -8
  72. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  73. package/ui/components/pay/RecipientField.tsx +49 -4
  74. package/ui/components/pay/RequestHub.tsx +68 -8
  75. package/ui/components/pay/ResultBanner.tsx +41 -4
  76. package/ui/components/pay/UniversalSend.tsx +534 -30
  77. package/ui/components/pay/tokenSendCopy.ts +116 -0
  78. package/ui/components/pay/useRecipientInput.ts +36 -7
  79. package/ui/components/ui/PermissionSheet.tsx +65 -4
  80. package/ui/components/ui/Sheet.tsx +9 -2
  81. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  82. package/ui/components/vault/KeyChooser.tsx +96 -0
  83. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  84. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  85. package/ui/components/wallet/ActivityRow.tsx +101 -17
  86. package/ui/components/wallet/AmountInput.tsx +77 -25
  87. package/ui/components/wallet/AssetAmount.tsx +95 -0
  88. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  89. package/ui/components/wallet/tokenEviction.ts +65 -0
  90. package/ui/hooks/useExportWalletData.ts +39 -0
  91. package/ui/hooks/useMandala.ts +303 -0
  92. package/ui/hooks/useVaultBalance.ts +105 -7
  93. package/ui/hooks/useVaultCoverage.ts +52 -0
  94. package/ui/importDatabases.ts +7 -3
  95. package/ui/index.ts +50 -7
  96. package/ui/screens/ConnectionsScreen.tsx +46 -29
  97. package/ui/screens/PairScreen.tsx +12 -12
  98. package/ui/screens/PayScreen.tsx +130 -10
  99. package/ui/screens/SettingsScreen.tsx +18 -9
  100. package/ui/screens/VaultScreen.tsx +925 -171
  101. package/ui/screens/VaultTransferScreen.tsx +376 -123
  102. package/ui/screens/WalletCheckScreen.tsx +10 -1
  103. package/ui/screens/WalletConfigScreen.tsx +38 -16
  104. package/ui/screens/WalletHomeScreen.tsx +417 -86
  105. package/ui/screens/homeBadges.ts +9 -1
  106. package/ui/screens/tokenRowTitle.ts +68 -0
  107. package/ui/tokenFormat.ts +108 -0
  108. package/ui/tokenSeen.ts +75 -0
  109. package/ui/tokenStatus.ts +79 -0
  110. package/assets/sounds/vault-close.wav +0 -0
  111. package/assets/sounds/vault-open.wav +0 -0
  112. package/core/services/vault/k1.ts +0 -75
  113. package/core/services/vault/sealing.ts +0 -84
  114. package/core/services/vault/vaultDerivation.ts +0 -152
  115. package/core/services/vault/vaultPassphrase.ts +0 -287
  116. package/ui/components/vault/PassphraseField.tsx +0 -306
  117. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  118. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,40 +1,62 @@
1
1
  /**
2
- * Vault access guard (fixes the privilege-escalation review finding).
2
+ * External-wallet boundary for the Vault.
3
3
  *
4
- * PrivilegedKeyManager's key universe is the wallet's master HD root key — a
5
- * strictly more sensitive key than the per-app `primaryKey` (m/0'/0') that
6
- * every ordinary, non-privileged operation signs with. That is true whether
7
- * or not a vault is enrolled: the vault does not route through this manager
8
- * at all (vault inputs are signed from the vault's own HD node — the
9
- * YubiKey-unwrapped seed, equivalently derived from the main mnemonic plus a
10
- * vault passphrase that the root key cannot reach, since BIP39's `toSeed` is
11
- * one-way and passphrase-dependent). The toolbox routes every
12
- * BRC-100 `privileged: true` op through PrivilegedKeyManager regardless, and
13
- * this app runs with `seekProtocolPermissionsForSigning` / public-key-
14
- * revelation permissions OFF, so nothing else gates them. That let any web
15
- * origin, via the CWI bridge, use `getPublicKey({ privileged: true, ... })`,
16
- * `createSignature`, `encrypt`/`decrypt`, or HMAC ops to reveal or sign with
17
- * the root key — none of which are spend actions, so none of them ever trip
18
- * the spending-authorization sheet.
19
- *
20
- * Blocking privileged ops for external originators is what closes that
21
- * exposure: it is the only thing standing between a web page and the root
22
- * key, now that the keyGetter itself no longer discriminates by enrollment
23
- * or caller. (It is not what keeps the YubiKey ceremony admin-only — that
24
- * follows separately, because nothing outside `services/vault` ever calls
25
- * `requestVaultKey`/`ceremony.requestKey` in the first place; a page
26
- * cannot reach the ceremony through this guarded surface even in principle,
27
- * privileged or not.)
28
- *
29
- * Privileged operations have never been used by external origins in this app
30
- * (the keyGetter has only ever returned the root key with no ceremony and no
31
- * web caller — first because there was no vault, now because the vault no
32
- * longer routes through it either), so denying them breaks nothing real.
4
+ * Vault ownership is determined from authenticated wallet history and the exact
5
+ * current R1C locking script. It is never inferred from a basket name supplied
6
+ * by an external caller. This matters because BRC-100 operations can name an
7
+ * existing output by outpoint: without this guard an application that learned a
8
+ * Vault outpoint could reserve it with createAction or reclassify it with
9
+ * internalizeAction without first obtaining access to the `admin vault` basket.
33
10
  */
34
- import type { WalletInterface } from '@bsv/sdk'
11
+ import {
12
+ LockingScript,
13
+ Transaction,
14
+ Validation,
15
+ type ListActionsArgs,
16
+ type ListActionsResult,
17
+ type WalletAction,
18
+ type WalletInterface
19
+ } from '@bsv/sdk'
20
+ import { bakedCommitments, R1C_LOCK_LEN, R1C_MAX_KEYS } from './r1comb'
21
+
22
+ const VAULT_BASKET = 'admin vault'
23
+ const VAULT_LABEL = 'vault'
24
+ // An R1C locking script is about 45 KB before JS string/object overhead. Keep
25
+ // only a small enriched page live at once; the scanners below stream rows and
26
+ // retain only compact identifiers or the caller's requested visible slice.
27
+ const ACTION_PAGE = 32
28
+ const MAX_ACTION_SCAN = 10_000
29
+ const MAX_EXTERNAL_ACTION_RESULTS = 500
30
+ const MAX_EXTERNAL_ACTION_LABELS = 64
31
+ const MAX_EXTERNAL_ACTION_LABEL_BYTES = 4096
32
+ const MAX_EXTERNAL_ACTION_OFFSET = MAX_ACTION_SCAN
33
+ /** Permission-backed reads must never retain the exclusive inventory slot
34
+ * indefinitely while a connected origin leaves a prompt unanswered. */
35
+ export const EXTERNAL_ACTION_READ_TIMEOUT_MS = 30_000
36
+ /** Bound queued scans as well as active scans. A connected origin can issue
37
+ * concurrent RPCs, so serialization alone would otherwise turn the promise
38
+ * queue into another unbounded memory sink. */
39
+ const MAX_GUARDED_QUEUE = 16
40
+ const LIST_ACTION_BOOLEAN_FIELDS = [
41
+ 'includeLabels',
42
+ 'includeInputs',
43
+ 'includeInputSourceLockingScripts',
44
+ 'includeInputUnlockingScripts',
45
+ 'includeOutputs',
46
+ 'includeOutputLockingScripts',
47
+ 'seekPermission'
48
+ ] as const
49
+ const LIST_ACTION_FIELDS = new Set<string>([
50
+ 'labels',
51
+ 'labelQueryMode',
52
+ ...LIST_ACTION_BOOLEAN_FIELDS,
53
+ 'limit',
54
+ 'offset'
55
+ ])
35
56
 
36
- /** BRC-100 methods that accept `privileged: true` and would return / use
37
- * privileged (root) key material. */
57
+ /** BRC-100 methods that accept `privileged: true` and would return or use the
58
+ * wallet's root key. Vault keys do not live in that hierarchy, but exposing the
59
+ * root key to a connected application would still compromise the wallet. */
38
60
  const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
39
61
  'getPublicKey',
40
62
  'revealCounterpartyKeyLinkage',
@@ -45,46 +67,482 @@ const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
45
67
  'verifyHmac',
46
68
  'createSignature',
47
69
  'verifySignature',
48
- // Certificate ops thread `privileged` straight into the underlying wallet
49
- // too: acquireCertificate's 'direct' branch calls getPublicKey({
50
- // identityKey: true, privileged, privilegedReason }) on the unwrapped
51
- // wallet, and proveCertificate threads privileged into
52
- // MasterCertificate.createKeyringForVerifier. Omitting these left a hole
53
- // to the same root key the other entries above are here to block.
54
70
  'acquireCertificate',
55
71
  'proveCertificate',
56
72
  'listCertificates'
57
73
  ])
74
+ /** Protocol namespaces whose derived keys are internal Vault state. The
75
+ * 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 {
80
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) return false
81
+ const protocolID = (args as { protocolID?: unknown }).protocolID
82
+ // Match KeyDeriver.computeInvoiceNumber's namespace normalization exactly.
83
+ // Otherwise e.g. ` VAULT SALT ` reaches the same child key while evading a
84
+ // literal boundary comparison. Reject matching malformed/extended tuples
85
+ // 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())
89
+ }
90
+
91
+ /** Operations that can name an existing output or unsigned action without
92
+ * going through basket-listing permission checks. */
93
+ const OUTPUT_NAMING = new Set<keyof WalletInterface>([
94
+ 'createAction',
95
+ 'internalizeAction',
96
+ 'relinquishOutput',
97
+ 'signAction',
98
+ 'abortAction'
99
+ ])
100
+
101
+ interface ExtendedWalletAction extends WalletAction {
102
+ reference?: string
103
+ }
104
+
105
+ interface VaultInventory {
106
+ outpoints: Set<string>
107
+ references: Set<string>
108
+ /** Signed noSend Vault actions can be released by options.sendWith, so their
109
+ * transaction ids are capabilities too, even when no protected outpoint is
110
+ * named in the outer request. */
111
+ txids: Set<string>
112
+ }
113
+
114
+ interface GuardRuntime {
115
+ tail: Promise<void>
116
+ queued: number
117
+ /** Concurrent byte-identical external listActions reads share one scan.
118
+ * Entries exist only while the scan is in flight; there is no stale cache. */
119
+ reads: Map<string, Promise<ListActionsResult>>
120
+ }
121
+
122
+ /** One runtime per underlying wallet even if it is wrapped more than once. */
123
+ const GUARD_RUNTIMES = new WeakMap<object, GuardRuntime>()
124
+ /** Keep wrapping idempotent. Call sites compose wallet capabilities in several
125
+ * layers, and wrapping an existing guard again must not acquire a second slot
126
+ * around the first one and deadlock. Different admin authorities still get
127
+ * distinct proxies, backed by the same underlying runtime. */
128
+ const GUARD_TARGETS = new WeakMap<object, object>()
129
+ const GUARDED_PROXIES = new WeakMap<object, Map<string, object>>()
130
+
131
+ function underlyingWallet(wallet: object): object {
132
+ return GUARD_TARGETS.get(wallet) ?? wallet
133
+ }
134
+
135
+ function runtimeFor(wallet: object): GuardRuntime {
136
+ let runtime = GUARD_RUNTIMES.get(wallet)
137
+ if (!runtime) {
138
+ runtime = { tail: Promise.resolve(), queued: 0, reads: new Map() }
139
+ GUARD_RUNTIMES.set(wallet, runtime)
140
+ }
141
+ return runtime
142
+ }
143
+
144
+ /** Run one enriched-history operation at a time. The slot covers both the
145
+ * inventory scan and the guarded mutation, so a second external request can
146
+ * never act on a snapshot made stale by the first one. */
147
+ async function withGuardSlot<T>(runtime: GuardRuntime, work: () => Promise<T>, trusted = false): Promise<T> {
148
+ // Trusted admin calls may enter behind a full external queue. Once queued,
149
+ // continuous attacker traffic is rejected at the bound and cannot jump in
150
+ // front of it; this keeps admin repair available without unbounding the
151
+ // untrusted queue.
152
+ if (!trusted && runtime.queued >= MAX_GUARDED_QUEUE) throw new Error('Too many guarded wallet operations')
153
+ runtime.queued++
154
+ const predecessor = runtime.tail
155
+ let release!: () => void
156
+ runtime.tail = new Promise<void>(resolve => { release = resolve })
157
+ await predecessor
158
+ try {
159
+ return await work()
160
+ } finally {
161
+ runtime.queued--
162
+ release()
163
+ }
164
+ }
165
+
166
+ type ValidatedListActionsArgs = ReturnType<typeof Validation.validateListActionsArgs>
167
+
168
+ /** Apply bridge-specific structural and aggregate bounds before serialising a
169
+ * read key. The SDK validates each label but places no bound on their count and
170
+ * ignores unknown fields, so calling JSON.stringify on the raw object would
171
+ * duplicate an attacker-sized graph before the guarded queue can refuse it. */
172
+ function validateExternalListActionsArgs(args: unknown): ValidatedListActionsArgs {
173
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) {
174
+ throw new Error('Invalid listActions arguments')
175
+ }
176
+ const raw = args as Record<string, unknown>
177
+ for (const key of Object.keys(raw)) {
178
+ if (!LIST_ACTION_FIELDS.has(key)) throw new Error(`Unknown listActions field ${key}`)
179
+ }
180
+ if (raw.labels !== undefined && !Array.isArray(raw.labels)) throw new Error('Invalid listActions labels')
181
+ const labels = (raw.labels ?? []) as unknown[]
182
+ if (labels.length > MAX_EXTERNAL_ACTION_LABELS) throw new Error('Too many listActions labels')
183
+ let labelBytes = 0
184
+ for (const label of labels) {
185
+ if (typeof label !== 'string' || label.length > 300) throw new Error('Invalid listActions label')
186
+ labelBytes += new TextEncoder().encode(label).length
187
+ if (labelBytes > MAX_EXTERNAL_ACTION_LABEL_BYTES) throw new Error('listActions labels are too large')
188
+ }
189
+ for (const field of LIST_ACTION_BOOLEAN_FIELDS) {
190
+ if (raw[field] !== undefined && typeof raw[field] !== 'boolean') {
191
+ throw new Error(`Invalid listActions ${field}`)
192
+ }
193
+ }
194
+ const requested = Validation.validateListActionsArgs(args as ListActionsArgs)
195
+ if (requested.limit > MAX_EXTERNAL_ACTION_RESULTS) throw new Error('listActions limit is too large')
196
+ if (requested.offset > MAX_EXTERNAL_ACTION_OFFSET) throw new Error('listActions offset is too large')
197
+ return requested
198
+ }
199
+
200
+ function externalReadKey(args: ValidatedListActionsArgs, originator: string): string {
201
+ // `args` is a small, normalized object produced by the validator above.
202
+ return `${originator}\0${JSON.stringify(args)}`
203
+ }
204
+
205
+ interface ReadDeadline {
206
+ expiresAt: number
207
+ }
208
+
209
+ async function beforeReadDeadline<T>(promise: Promise<T>, deadline: ReadDeadline): Promise<T> {
210
+ const remaining = deadline.expiresAt - Date.now()
211
+ if (remaining <= 0) throw new Error('Guarded wallet read timed out')
212
+ return await new Promise<T>((resolve, reject) => {
213
+ const timer = setTimeout(() => reject(new Error('Guarded wallet read timed out')), remaining)
214
+ promise.then(
215
+ value => { clearTimeout(timer); resolve(value) },
216
+ error => { clearTimeout(timer); reject(error) }
217
+ )
218
+ })
219
+ }
58
220
 
59
221
  export class VaultAccessDenied extends Error {
222
+ readonly code = 6
223
+
60
224
  constructor(method: string, originator: string) {
61
- super(`Privileged operation "${method}" is not permitted for origin "${originator || 'unknown'}"`)
225
+ super(`Wallet operation "${method}" is not permitted for origin "${originator || 'unknown'}"`)
62
226
  this.name = 'VaultAccessDenied'
63
227
  }
64
228
  }
65
229
 
66
- /**
67
- * Wrap a wallet so that `privileged: true` operations from any originator other
68
- * than `adminOriginator` are rejected. All other calls pass straight through.
69
- * Apply this to the wallet handed to EXTERNAL callers (the in-tab CWI bridge and
70
- * the desktop-pairing WalletClient); the vault's own UI keeps calling the
71
- * unwrapped permissions manager with the admin originator.
72
- */
230
+ function deny(method: string, originator?: string): never {
231
+ throw new VaultAccessDenied(method, originator ?? '')
232
+ }
233
+
234
+ /** Exact parser, including byte-for-byte regeneration of the current template. */
235
+ export function isR1CLockingScript(lockingScript: unknown): boolean {
236
+ if (typeof lockingScript !== 'string') return false
237
+ // The SDK trims locking-script strings during createAction validation. Match
238
+ // that normalization here so whitespace cannot turn an exact R1C lock into
239
+ // something the guard overlooks but the wallet later accepts.
240
+ const normalized = lockingScript.trim()
241
+ if (!/^[0-9a-fA-F]+$/.test(normalized) || normalized.length % 2 !== 0) {
242
+ return false
243
+ }
244
+ const bytes = normalized.length / 2
245
+ let possible = false
246
+ for (let n = 1; n <= R1C_MAX_KEYS; n++) possible ||= bytes === R1C_LOCK_LEN(n)
247
+ if (!possible) return false
248
+ try {
249
+ bakedCommitments(LockingScript.fromHex(normalized))
250
+ return true
251
+ } catch {
252
+ return false
253
+ }
254
+ }
255
+
256
+ function isSensitiveAction(action: ExtendedWalletAction): boolean {
257
+ if (action.labels?.includes(VAULT_LABEL)) return true
258
+ if (action.outputs?.some(output => output.basket.startsWith('admin') || isR1CLockingScript(output.lockingScript))) {
259
+ return true
260
+ }
261
+ return !!action.inputs?.some(input => isR1CLockingScript(input.sourceLockingScript))
262
+ }
263
+
264
+ function enrichedArgs(args: ListActionsArgs, offset: number): ListActionsArgs {
265
+ return {
266
+ ...args,
267
+ includeLabels: true,
268
+ includeInputs: true,
269
+ includeInputSourceLockingScripts: true,
270
+ includeInputUnlockingScripts: false,
271
+ includeOutputs: true,
272
+ includeOutputLockingScripts: true,
273
+ limit: ACTION_PAGE,
274
+ offset
275
+ }
276
+ }
277
+
278
+ /** Stream one stable logical list so protected rows cannot distort pagination
279
+ * without retaining thousands of enriched R1C scripts in memory. */
280
+ async function scanAllActions(
281
+ call: (args: ListActionsArgs, originator?: string) => Promise<ListActionsResult>,
282
+ args: ListActionsArgs,
283
+ originator: string,
284
+ visit: (action: ExtendedWalletAction) => void,
285
+ deadline?: ReadDeadline
286
+ ): Promise<void> {
287
+ const seen = new Set<string>()
288
+ let expectedTotal: number | undefined
289
+ let offset = 0
290
+ for (;;) {
291
+ const request = call(enrichedArgs(args, offset), originator)
292
+ const page = deadline ? await beforeReadDeadline(request, deadline) : await request
293
+ if (!page || !Array.isArray(page.actions) || !Number.isSafeInteger(page.totalActions) || page.totalActions < 0) {
294
+ throw new Error('Wallet returned an invalid action page')
295
+ }
296
+ if (page.totalActions > MAX_ACTION_SCAN || page.actions.length > ACTION_PAGE) {
297
+ throw new Error('Wallet action list exceeds the guarded scan bound')
298
+ }
299
+ if (expectedTotal === undefined) expectedTotal = page.totalActions
300
+ else if (expectedTotal !== page.totalActions) throw new Error('Wallet action list changed while it was inspected')
301
+
302
+ for (const action of page.actions as ExtendedWalletAction[]) {
303
+ const identity = action.txid || (action.reference ? `reference:${action.reference}` : '')
304
+ if (!identity || seen.has(identity)) throw new Error('Wallet returned a duplicate or unidentified action')
305
+ seen.add(identity)
306
+ visit(action)
307
+ }
308
+ if (page.actions.length === 0) {
309
+ if (offset < page.totalActions) throw new Error('Wallet action list stopped before its reported total')
310
+ break
311
+ }
312
+ offset += page.actions.length
313
+ if (offset > page.totalActions) throw new Error('Wallet action list exceeded its reported total')
314
+ if (offset === page.totalActions) break
315
+ }
316
+ }
317
+
318
+ function sanitizeAction(action: ExtendedWalletAction, requested: ListActionsArgs): ExtendedWalletAction {
319
+ const safe: ExtendedWalletAction = { ...action }
320
+ if (!requested.includeLabels) delete safe.labels
321
+ if (!requested.includeInputs) delete safe.inputs
322
+ else if (safe.inputs) {
323
+ safe.inputs = safe.inputs.map(input => {
324
+ const copy = { ...input }
325
+ if (!requested.includeInputSourceLockingScripts) delete copy.sourceLockingScript
326
+ if (!requested.includeInputUnlockingScripts) delete copy.unlockingScript
327
+ return copy
328
+ })
329
+ }
330
+ if (!requested.includeOutputs) delete safe.outputs
331
+ else if (!requested.includeOutputLockingScripts && safe.outputs) {
332
+ safe.outputs = safe.outputs.map(output => {
333
+ const copy = { ...output }
334
+ delete copy.lockingScript
335
+ return copy
336
+ })
337
+ }
338
+ return safe
339
+ }
340
+
341
+ async function listActionsForExternal(
342
+ call: (args: ListActionsArgs, originator?: string) => Promise<ListActionsResult>,
343
+ requested: ValidatedListActionsArgs,
344
+ originator: string,
345
+ deadline: ReadDeadline
346
+ ): Promise<ListActionsResult> {
347
+ const { offset, limit } = requested
348
+ let visibleCount = 0
349
+ 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)
355
+ return {
356
+ totalActions: visibleCount,
357
+ actions: visible
358
+ }
359
+ }
360
+
361
+ /** Authenticated all-action history is also a durable output inventory. The
362
+ * exact script check protects a mislabeled R1C output as defense in depth. */
363
+ async function loadVaultInventory(
364
+ call: (args: ListActionsArgs, originator?: string) => Promise<ListActionsResult>,
365
+ adminOriginator: string
366
+ ): Promise<VaultInventory> {
367
+ const inventory: VaultInventory = { outpoints: new Set(), references: new Set(), txids: new Set() }
368
+ await scanAllActions(call, { labels: [] }, adminOriginator, action => {
369
+ const sensitive = isSensitiveAction(action)
370
+ if (action.reference && sensitive) inventory.references.add(action.reference)
371
+ if (action.txid && sensitive) inventory.txids.add(action.txid.toLowerCase())
372
+ for (const output of action.outputs ?? []) {
373
+ if (action.txid && (output.basket === VAULT_BASKET || isR1CLockingScript(output.lockingScript))) {
374
+ inventory.outpoints.add(`${action.txid.toLowerCase()}.${output.outputIndex}`)
375
+ }
376
+ }
377
+ for (const input of action.inputs ?? []) {
378
+ if (isR1CLockingScript(input.sourceLockingScript)) inventory.outpoints.add(input.sourceOutpoint.toLowerCase())
379
+ }
380
+ })
381
+ return inventory
382
+ }
383
+
384
+ /** `sendWith` is a broadcast capability for a previously signed noSend action.
385
+ * Both createAction and signAction accept it, including when the surrounding
386
+ * request does not otherwise touch a Vault input/output/reference. */
387
+ function requestedSendWithTxids(method: keyof WalletInterface, args: any): string[] | undefined {
388
+ if (method !== 'createAction' && method !== 'signAction') return []
389
+ const value = args?.options?.sendWith
390
+ if (value === undefined) return []
391
+ if (!Array.isArray(value)) return undefined
392
+ const txids: string[] = []
393
+ for (const txid of value) {
394
+ if (typeof txid !== 'string' || !/^[0-9a-fA-F]{64}$/.test(txid)) return undefined
395
+ txids.push(txid.toLowerCase())
396
+ }
397
+ return txids
398
+ }
399
+
400
+ function canonicalOutpoint(value: unknown): string | undefined {
401
+ if (typeof value !== 'string') return undefined
402
+ const parts = value.split('.')
403
+ if (parts.length !== 2 || !/^[0-9a-fA-F]{64}$/.test(parts[0])) return undefined
404
+ // Mirror the SDK's Number(...) normalization so alternate spellings accepted
405
+ // downstream ("00", "0e0", "-0", or even an empty suffix) cannot evade an
406
+ // exact string comparison here.
407
+ const vout = Number(parts[1])
408
+ if (!Number.isSafeInteger(vout) || vout < 0) return undefined
409
+ return `${parts[0].toLowerCase()}.${vout}`
410
+ }
411
+
412
+ function requestedOutpoints(method: keyof WalletInterface, args: any): string[] | undefined {
413
+ let values: unknown[]
414
+ if (method === 'createAction') values = (args?.inputs ?? []).map((input: any) => input?.outpoint)
415
+ else if (method === 'relinquishOutput') values = [args?.output]
416
+ else if (method !== 'internalizeAction') return []
417
+ else {
418
+ try {
419
+ const txid = Transaction.fromAtomicBEEF(args?.tx).id('hex').toLowerCase()
420
+ values = (args?.outputs ?? []).map((output: any) => `${txid}.${String(output?.outputIndex ?? '')}`)
421
+ } catch {
422
+ return undefined
423
+ }
424
+ }
425
+ const canonical = values.map(canonicalOutpoint)
426
+ return canonical.some(value => value === undefined) ? undefined : canonical as string[]
427
+ }
428
+
429
+ function carriesR1COutput(method: keyof WalletInterface, args: any): boolean {
430
+ if (method === 'createAction') return !!args?.outputs?.some((output: any) => isR1CLockingScript(output?.lockingScript))
431
+ if (method !== 'internalizeAction') return false
432
+ try {
433
+ const tx = Transaction.fromAtomicBEEF(args?.tx)
434
+ return !!args?.outputs?.some((output: any) => {
435
+ // Match the SDK's numeric coercion. Alternate spellings such as "00"
436
+ // must identify the same output here as they do during internalization.
437
+ const index = Number(output?.outputIndex ?? '')
438
+ return Number.isSafeInteger(index) && index >= 0 && isR1CLockingScript(tx.outputs[index]?.lockingScript?.toHex())
439
+ })
440
+ } catch {
441
+ return false
442
+ }
443
+ }
444
+
445
+ /** Wrap every wallet handed to an external caller. */
73
446
  export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOriginator: string): T {
74
- return new Proxy(wallet, {
447
+ const targetWallet = underlyingWallet(wallet as object) as T
448
+ let byAuthority = GUARDED_PROXIES.get(targetWallet as object)
449
+ const existing = byAuthority?.get(adminOriginator)
450
+ if (existing) return existing as T
451
+
452
+ const runtime = runtimeFor(targetWallet as object)
453
+ const guarded = new Proxy(targetWallet, {
75
454
  get(target, prop, receiver) {
76
455
  const value = Reflect.get(target, prop, receiver)
77
- if (typeof value !== 'function' || !PRIVILEGED_CAPABLE.has(prop as keyof WalletInterface)) {
78
- return typeof value === 'function' ? value.bind(target) : value
456
+ if (typeof value !== 'function') return value
457
+ const method = prop as keyof WalletInterface
458
+ const bound = (value as (a: any, o?: string) => Promise<any>).bind(target)
459
+
460
+ if (method === 'listActions') {
461
+ return async (args: ListActionsArgs, originator?: string) => {
462
+ if (originator === adminOriginator) return await bound(args, originator)
463
+ const externalOriginator = originator ?? ''
464
+ try {
465
+ if (externalOriginator.length > 250) return deny(String(method), originator)
466
+ const requested = validateExternalListActionsArgs(args)
467
+ const key = externalReadKey(requested, externalOriginator)
468
+ const existing = runtime.reads.get(key)
469
+ if (existing) return await existing
470
+ // The deadline starts before queueing. If one permission prompt
471
+ // stalls, later reads expire together instead of each retaining the
472
+ // critical slot for another full timeout.
473
+ const deadline = { expiresAt: Date.now() + EXTERNAL_ACTION_READ_TIMEOUT_MS }
474
+ const pending = withGuardSlot(
475
+ runtime,
476
+ () => listActionsForExternal(bound, requested, externalOriginator, deadline)
477
+ )
478
+ runtime.reads.set(key, pending)
479
+ try {
480
+ return await pending
481
+ } finally {
482
+ if (runtime.reads.get(key) === pending) runtime.reads.delete(key)
483
+ }
484
+ } catch {
485
+ return deny(String(method), originator)
486
+ }
487
+ }
79
488
  }
80
- const bound = (value as (a: unknown, o?: string) => unknown).bind(target)
81
- return (args: unknown, originator?: string) => {
82
- const privileged = !!(args && typeof args === 'object' && (args as { privileged?: boolean }).privileged)
83
- if (privileged && originator !== adminOriginator) {
84
- return Promise.reject(new VaultAccessDenied(String(prop), originator ?? ''))
489
+
490
+ if (!PRIVILEGED_CAPABLE.has(method) && !OUTPUT_NAMING.has(method)) return value.bind(target)
491
+
492
+ return async (args: any, originator?: string) => {
493
+ if (PRIVILEGED_CAPABLE.has(method) && originator !== adminOriginator && requestsVaultProtocol(args)) {
494
+ return deny(String(method), originator)
495
+ }
496
+ if (PRIVILEGED_CAPABLE.has(method) && args?.privileged && originator !== adminOriginator) {
497
+ return deny(String(method), originator)
498
+ }
499
+ // Admin output/action mutations use the same exclusive slot as the
500
+ // external inventory scan + use. This closes the same-count/TOCTOU
501
+ // race without caching an inventory snapshot. The raw underlying
502
+ // wallet remains an internal trust boundary; every externally handed
503
+ // 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)
85
506
  }
86
- return bound(args, originator)
507
+ if (originator !== adminOriginator && OUTPUT_NAMING.has(method)) {
508
+ if (runtime.queued >= MAX_GUARDED_QUEUE) return deny(String(method), originator)
509
+ return await withGuardSlot(runtime, async () => {
510
+ let inventory: VaultInventory
511
+ try {
512
+ inventory = await loadVaultInventory(
513
+ target.listActions.bind(target) as (a: ListActionsArgs, o?: string) => Promise<ListActionsResult>,
514
+ adminOriginator
515
+ )
516
+ } catch {
517
+ return deny(String(method), originator)
518
+ }
519
+ const outpoints = requestedOutpoints(method, args)
520
+ if (outpoints === undefined || outpoints.some(outpoint => inventory.outpoints.has(outpoint))) {
521
+ return deny(String(method), originator)
522
+ }
523
+ if (
524
+ (method === 'signAction' || method === 'abortAction') &&
525
+ inventory.references.has(String(args?.reference ?? ''))
526
+ ) {
527
+ return deny(String(method), originator)
528
+ }
529
+ const sendWith = requestedSendWithTxids(method, args)
530
+ if (sendWith === undefined || sendWith.some(txid => inventory.txids.has(txid))) {
531
+ return deny(String(method), originator)
532
+ }
533
+ if (carriesR1COutput(method, args)) return deny(String(method), originator)
534
+ return await bound(args, originator)
535
+ })
536
+ }
537
+ return await bound(args, originator)
87
538
  }
88
539
  }
89
540
  })
541
+ if (!byAuthority) {
542
+ byAuthority = new Map()
543
+ GUARDED_PROXIES.set(targetWallet as object, byAuthority)
544
+ }
545
+ byAuthority.set(adminOriginator, guarded as object)
546
+ GUARD_TARGETS.set(guarded as object, targetWallet as object)
547
+ return guarded
90
548
  }
@@ -0,0 +1,22 @@
1
+ import { VaultError } from './types'
2
+
3
+ /**
4
+ * The YubiKey native modules expose one process-wide discovery/session object.
5
+ * Every Vault path must therefore own this lease from before it subscribes or
6
+ * starts discovery until after its final unsubscribe/stop. Queuing would keep
7
+ * secrets and UI promises alive behind an unrelated operation, so contention
8
+ * fails immediately and the caller can retry explicitly.
9
+ */
10
+ let holder: symbol | null = null
11
+
12
+ export function acquireVaultHardwareLease(): () => void {
13
+ if (holder) throw new VaultError('ceremony-active', 'Another Vault hardware operation is already active')
14
+ const token = Symbol('vault-hardware-lease')
15
+ holder = token
16
+ let released = false
17
+ return () => {
18
+ if (released) return
19
+ released = true
20
+ if (holder === token) holder = null
21
+ }
22
+ }