@bsv/expo-wallet-toolbox 0.10.0 → 0.11.2

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.
@@ -1,12 +1,26 @@
1
1
  /**
2
2
  * External-wallet boundary for the Vault.
3
3
  *
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.
4
+ * BRC-100 reserves `admin`-prefixed baskets for the wallet itself, and
5
+ * WalletPermissionsManager already refuses a connected app that names one.
6
+ * Some operations name an existing output by outpoint or a held transaction by
7
+ * txid instead, which the permissions manager does not check against baskets.
8
+ * For those, this guard asks storage about the named rows only
9
+ * (`VaultGuardLookup`), never the wallet's whole history:
10
+ *
11
+ * - createAction inputs, relinquishOutput and internalizeAction outputs are
12
+ * refused when a named outpoint sits in an admin-prefixed basket, or has
13
+ * no basket but is still tagged or labelled as Vault/admin state (a Vault
14
+ * output relinquished by "forget unreachable deposits").
15
+ * StorageExpoSQLite.validateResolvedActionInput repeats the input check
16
+ * inside createAction itself.
17
+ * - createAction/signAction `options.sendWith` is refused when a named txid
18
+ * is a Vault or admin transaction, so a held Vault transaction cannot be
19
+ * broadcast by someone else.
20
+ *
21
+ * The admin originator (this app's own code) passes straight through. R1C
22
+ * locking scripts are not special here: an app may create and spend R1C
23
+ * outputs in its own baskets.
10
24
  */
11
25
  import {
12
26
  LockingScript,
@@ -20,7 +34,6 @@ import {
20
34
  } from '@bsv/sdk'
21
35
  import { bakedCommitments, R1C_LOCK_LEN, R1C_MAX_KEYS } from './r1comb'
22
36
 
23
- const VAULT_BASKET = 'admin vault'
24
37
  const VAULT_LABEL = 'vault'
25
38
  // An R1C locking script is about 45 KB before JS string/object overhead. Keep
26
39
  // only a small enriched page live at once; the scanners below stream rows and
@@ -36,16 +49,17 @@ const MAX_EXTERNAL_ACTION_OFFSET = MAX_ACTION_SCAN
36
49
  * hard ceiling (limit <= 10000) — a normal-sized *request* from an
37
50
  * authenticated paired peer can still force a normal-sized *response* to
38
51
  * 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.
52
+ * (includeTransactions) or a locking script. These stay well below the SDK's
53
+ * 10000 cap but must admit the largest page the SDK's own clients request:
54
+ * ContactsManager.getContacts asks for 1000 rows with locking scripts
55
+ * (MAX_CONTACTS), and its save/remove lookups 100 with entire transactions.
56
+ * Anything tighter refuses IdentityClient.resolveByAttributes and friends in
57
+ * every dApp. The transactions variant is tighter because the response then
58
+ * also carries those rows' BEEF, not just an outpoint + locking script.
45
59
  */
46
- const MAX_EXTERNAL_LIST_OUTPUTS_RESULTS = 200
47
- const MAX_EXTERNAL_LIST_OUTPUTS_RESULTS_WITH_TRANSACTIONS = 25
48
- /** Permission-backed reads must never retain the exclusive inventory slot
60
+ const MAX_EXTERNAL_LIST_OUTPUTS_RESULTS = 1000
61
+ const MAX_EXTERNAL_LIST_OUTPUTS_RESULTS_WITH_TRANSACTIONS = 100
62
+ /** Permission-backed reads must never retain the exclusive listActions slot
49
63
  * indefinitely while a connected origin leaves a prompt unanswered. */
50
64
  export const EXTERNAL_ACTION_READ_TIMEOUT_MS = 30_000
51
65
  /** Bound queued scans as well as active scans. A connected origin can issue
@@ -162,48 +176,40 @@ function requestsPendingAbortAuthorityProtocol(args: unknown): boolean {
162
176
  return matchesProtocolNamespace(args, PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES)
163
177
  }
164
178
 
165
- /** Operations that can name an existing output or unsigned action without
166
- * going through basket-listing permission checks. */
179
+ /** Operations whose arguments can name an existing output by outpoint, or a
180
+ * held transaction by txid (`options.sendWith`), without going through the
181
+ * permissions manager's basket checks. */
167
182
  const OUTPUT_NAMING = new Set<keyof WalletInterface>([
168
183
  'createAction',
169
184
  'internalizeAction',
170
185
  'relinquishOutput',
171
- 'signAction',
172
- 'abortAction'
186
+ 'signAction'
173
187
  ])
174
188
 
175
189
  /**
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.
190
+ * Point lookups against the wallet's own storage. StorageExpoSQLite implements
191
+ * both (see core/storage/methods/vaultGuardSql.ts); each reads only the rows
192
+ * named and never a locking script.
193
193
  */
194
- export const VAULT_ABORT_REPLAY_MARKER = Symbol('vault-guard-replay-abort')
194
+ export interface VaultGuardLookup {
195
+ /** True when any canonical `txid.vout` is held in an `admin`-prefixed
196
+ * basket, or has no basket but is tagged `vault` or was created by a
197
+ * `vault`/`admin*`-labelled transaction (a relinquished Vault output). */
198
+ anyAdminOutpoint(outpoints: string[]): Promise<boolean>
199
+ /** True when any lowercase txid is labelled `vault` or `admin*`, or creates
200
+ * or spends an output in an `admin`-prefixed basket. */
201
+ anyAdminTransaction(txids: string[]): Promise<boolean>
202
+ }
195
203
 
196
- interface ExtendedWalletAction extends WalletAction {
197
- reference?: string
204
+ export interface GuardVaultAccessOptions {
205
+ /** Required for an external call that names an outpoint or a sendWith txid;
206
+ * without it such a call is refused. Supplied once, where the wallet is
207
+ * built; re-wrapping the same wallet later keeps it. */
208
+ lookup?: VaultGuardLookup
198
209
  }
199
210
 
200
- interface VaultInventory {
201
- outpoints: Set<string>
202
- references: Set<string>
203
- /** Signed noSend Vault actions can be released by options.sendWith, so their
204
- * transaction ids are capabilities too, even when no protected outpoint is
205
- * named in the outer request. */
206
- txids: Set<string>
211
+ interface ExtendedWalletAction extends WalletAction {
212
+ reference?: string
207
213
  }
208
214
 
209
215
  interface GuardRuntime {
@@ -212,6 +218,7 @@ interface GuardRuntime {
212
218
  /** Concurrent byte-identical external listActions reads share one scan.
213
219
  * Entries exist only while the scan is in flight; there is no stale cache. */
214
220
  reads: Map<string, Promise<ListActionsResult>>
221
+ lookup?: VaultGuardLookup
215
222
  }
216
223
 
217
224
  /** One runtime per underlying wallet even if it is wrapped more than once. */
@@ -236,15 +243,11 @@ function runtimeFor(wallet: object): GuardRuntime {
236
243
  return runtime
237
244
  }
238
245
 
239
- /** Run one enriched-history operation at a time. The slot covers both the
240
- * inventory scan and the guarded mutation, so a second external request can
241
- * never act on a snapshot made stale by the first one. */
242
- async function withGuardSlot<T>(runtime: GuardRuntime, work: () => Promise<T>, trusted = false): Promise<T> {
243
- // Trusted admin calls may enter behind a full external queue. Once queued,
244
- // continuous attacker traffic is rejected at the bound and cannot jump in
245
- // front of it; this keeps admin repair available without unbounding the
246
- // untrusted queue.
247
- if (!trusted && runtime.queued >= MAX_GUARDED_QUEUE) throw new Error('Too many guarded wallet operations')
246
+ /** Run one external enriched listActions scan at a time, with a bounded queue,
247
+ * so concurrent reads from a connected app cannot pile up history pages in
248
+ * memory. */
249
+ async function withGuardSlot<T>(runtime: GuardRuntime, work: () => Promise<T>): Promise<T> {
250
+ if (runtime.queued >= MAX_GUARDED_QUEUE) throw new Error('Too many guarded wallet operations')
248
251
  runtime.queued++
249
252
  const predecessor = runtime.tail
250
253
  let release!: () => void
@@ -498,32 +501,9 @@ async function listActionsForExternal(
498
501
  }
499
502
  }
500
503
 
501
- /** Authenticated all-action history is also a durable output inventory. The
502
- * exact script check protects a mislabeled R1C output as defense in depth. */
503
- async function loadVaultInventory(
504
- call: (args: ListActionsArgs, originator?: string) => Promise<ListActionsResult>,
505
- adminOriginator: string
506
- ): Promise<VaultInventory> {
507
- const inventory: VaultInventory = { outpoints: new Set(), references: new Set(), txids: new Set() }
508
- await scanAllActions(call, { labels: [] }, adminOriginator, action => {
509
- const sensitive = isSensitiveAction(action)
510
- if (action.reference && sensitive) inventory.references.add(action.reference)
511
- if (action.txid && sensitive) inventory.txids.add(action.txid.toLowerCase())
512
- for (const output of action.outputs ?? []) {
513
- if (action.txid && (output.basket === VAULT_BASKET || isR1CLockingScript(output.lockingScript))) {
514
- inventory.outpoints.add(`${action.txid.toLowerCase()}.${output.outputIndex}`)
515
- }
516
- }
517
- for (const input of action.inputs ?? []) {
518
- if (isR1CLockingScript(input.sourceLockingScript)) inventory.outpoints.add(input.sourceOutpoint.toLowerCase())
519
- }
520
- })
521
- return inventory
522
- }
523
-
524
504
  /** `sendWith` is a broadcast capability for a previously signed noSend action.
525
505
  * Both createAction and signAction accept it, including when the surrounding
526
- * request does not otherwise touch a Vault input/output/reference. */
506
+ * request names no input or output at all. */
527
507
  function requestedSendWithTxids(method: keyof WalletInterface, args: any): string[] | undefined {
528
508
  if (method !== 'createAction' && method !== 'signAction') return []
529
509
  const value = args?.options?.sendWith
@@ -566,26 +546,32 @@ function requestedOutpoints(method: keyof WalletInterface, args: any): string[]
566
546
  return canonical.some(value => value === undefined) ? undefined : (canonical as string[])
567
547
  }
568
548
 
569
- function carriesR1COutput(method: keyof WalletInterface, args: any): boolean {
570
- if (method === 'createAction')
571
- return !!args?.outputs?.some((output: any) => isR1CLockingScript(output?.lockingScript))
572
- if (method !== 'internalizeAction') return false
549
+ /** Whether an external output-naming call names an admin-state outpoint or a
550
+ * Vault/admin transaction. Unparseable arguments, a missing lookup
551
+ * and a failed lookup all count as yes. */
552
+ async function namesAdminState(runtime: GuardRuntime, method: keyof WalletInterface, args: any): Promise<boolean> {
553
+ const outpoints = requestedOutpoints(method, args)
554
+ const sendWith = requestedSendWithTxids(method, args)
555
+ if (outpoints === undefined || sendWith === undefined) return true
556
+ if (outpoints.length === 0 && sendWith.length === 0) return false
557
+ const lookup = runtime.lookup
558
+ if (!lookup) return true
573
559
  try {
574
- const tx = Transaction.fromAtomicBEEF(args?.tx)
575
- return !!args?.outputs?.some((output: any) => {
576
- // Match the SDK's numeric coercion. Alternate spellings such as "00"
577
- // must identify the same output here as they do during internalization.
578
- const index = Number(output?.outputIndex ?? '')
579
- return Number.isSafeInteger(index) && index >= 0 && isR1CLockingScript(tx.outputs[index]?.lockingScript?.toHex())
580
- })
560
+ if (outpoints.length > 0 && (await lookup.anyAdminOutpoint(outpoints))) return true
561
+ return sendWith.length > 0 && (await lookup.anyAdminTransaction(sendWith))
581
562
  } catch {
582
- return false
563
+ return true
583
564
  }
584
565
  }
585
566
 
586
567
  /** Wrap every wallet handed to an external caller. */
587
- export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOriginator: string): T {
568
+ export function guardVaultAccess<T extends WalletInterface>(
569
+ wallet: T,
570
+ adminOriginator: string,
571
+ options: GuardVaultAccessOptions = {}
572
+ ): T {
588
573
  const targetWallet = underlyingWallet(wallet as object) as T
574
+ if (options.lookup) runtimeFor(targetWallet as object).lookup = options.lookup
589
575
  let byAuthority = GUARDED_PROXIES.get(targetWallet as object)
590
576
  const existing = byAuthority?.get(adminOriginator)
591
577
  if (existing) return existing as T
@@ -644,83 +630,36 @@ export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOrig
644
630
  // admin-vault listOutputs one layer further out (see this test's
645
631
  // own file: proofBar.railIsolation.test.ts's I3 listOutputs case)
646
632
  // throws its own specific error, and this bound must never mask it.
647
- let requested: ValidatedListOutputsArgs
648
633
  try {
649
- requested = validateExternalListOutputsArgs(args)
634
+ validateExternalListOutputsArgs(args)
650
635
  } catch {
651
636
  return deny(String(method), originator)
652
637
  }
653
- return await bound(requested, originator)
638
+ // Forward the caller's own args, not the validated form: that swaps
639
+ // `include` for includeTransactions/includeLockingScripts, and the
640
+ // wallet validates again, so passing it on would drop both.
641
+ return await bound(args, originator)
654
642
  }
655
643
  }
656
644
 
657
645
  if (!PRIVILEGED_CAPABLE.has(method) && !OUTPUT_NAMING.has(method)) return value.bind(target)
658
646
 
659
647
  return async (args: any, originator?: string) => {
648
+ if (originator === adminOriginator) return await bound(args, originator)
660
649
  if (
661
650
  PRIVILEGED_CAPABLE.has(method) &&
662
- originator !== adminOriginator &&
663
- (requestsVaultProtocol(args) ||
651
+ (args?.privileged ||
652
+ requestsVaultProtocol(args) ||
664
653
  requestsReservedRailProtocol(args) ||
665
654
  requestsConnectionAuthorityProtocol(args) ||
666
655
  requestsPendingAbortAuthorityProtocol(args))
667
656
  ) {
668
657
  return deny(String(method), originator)
669
658
  }
670
- if (PRIVILEGED_CAPABLE.has(method) && args?.privileged && originator !== adminOriginator) {
659
+ if (OUTPUT_NAMING.has(method) && (await namesAdminState(runtime, method, args))) {
671
660
  return deny(String(method), originator)
672
661
  }
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
685
- // Admin output/action mutations use the same exclusive slot as the
686
- // external inventory scan + use. This closes the same-count/TOCTOU
687
- // race without caching an inventory snapshot. The raw underlying
688
- // wallet remains an internal trust boundary; every externally handed
689
- // proxy shares this runtime through the WeakMap above.
690
- if (originator === adminOriginator && OUTPUT_NAMING.has(method) && !isReplayAbort) {
691
- return await withGuardSlot(runtime, () => bound(callArgs, originator), true)
692
- }
693
- if ((originator !== adminOriginator || isReplayAbort) && OUTPUT_NAMING.has(method)) {
694
- if (runtime.queued >= MAX_GUARDED_QUEUE) return deny(String(method), originator)
695
- return await withGuardSlot(runtime, async () => {
696
- let inventory: VaultInventory
697
- try {
698
- inventory = await loadVaultInventory(
699
- target.listActions.bind(target) as (a: ListActionsArgs, o?: string) => Promise<ListActionsResult>,
700
- adminOriginator
701
- )
702
- } catch {
703
- return deny(String(method), originator)
704
- }
705
- const outpoints = requestedOutpoints(method, callArgs)
706
- if (outpoints === undefined || outpoints.some(outpoint => inventory.outpoints.has(outpoint))) {
707
- return deny(String(method), originator)
708
- }
709
- if (
710
- (method === 'signAction' || method === 'abortAction') &&
711
- inventory.references.has(String(callArgs?.reference ?? ''))
712
- ) {
713
- return deny(String(method), originator)
714
- }
715
- const sendWith = requestedSendWithTxids(method, callArgs)
716
- if (sendWith === undefined || sendWith.some(txid => inventory.txids.has(txid))) {
717
- return deny(String(method), originator)
718
- }
719
- if (carriesR1COutput(method, callArgs)) return deny(String(method), originator)
720
- return await bound(callArgs, originator)
721
- })
722
- }
723
- return await bound(callArgs, originator)
662
+ return await bound(args, originator)
724
663
  }
725
664
  }
726
665
  })
@@ -267,6 +267,9 @@ export interface VaultKeyCoverage {
267
267
  missingKeys: string[]
268
268
  /** Outputs committed to a pubkey no longer in meta — "still open to a removed key". */
269
269
  removedKeyOutputs: number
270
+ /** Outputs no current key (nor one mid-removal) can open — typically a
271
+ * deposit from an earlier setup, whose PIV keys the reset replaced. */
272
+ unreachableOutputs: number
270
273
  }
271
274
 
272
275
  /**
@@ -327,6 +330,8 @@ export interface VaultWallet {
327
330
  decrypt(args: unknown, originator: string): Promise<{ plaintext: number[] }>
328
331
  /** Insert a chain-recovered v7 output into the admin vault basket. */
329
332
  internalizeAction(args: unknown, originator: string): Promise<{ accepted: true }>
333
+ /** Drop an output no current key can open from the admin vault basket. */
334
+ relinquishOutput(args: unknown, originator: string): Promise<{ relinquished: true }>
330
335
  /** Network status lookup (mirrors storage/methods/processOfflineActions.ts'
331
336
  * networkAlreadyHas). NEW-07: no longer consulted by resolveHeldVaultDeposit
332
337
  * — a bare 'mined'/'known' answer from this is an unauthenticated claim,
@@ -3293,16 +3298,18 @@ export async function getVaultKeyCoverage(w: VaultWallet, adminOriginator: strin
3293
3298
  const meta = await vaultStore.getMeta(scopeToken)
3294
3299
  const current = meta?.keys.map(k => k.pubkey) ?? []
3295
3300
  const currentSet = new Set(current)
3301
+ const live = meta ? liveVaultPubkeys(meta) : undefined
3296
3302
  const scan = await reduceVerifiedVaultOutputs(
3297
3303
  w,
3298
3304
  adminOriginator,
3299
- () => ({ stale: 0, removedKeyOutputs: 0, missing: new Set<string>() }),
3305
+ () => ({ stale: 0, removedKeyOutputs: 0, unreachableOutputs: 0, missing: new Set<string>() }),
3300
3306
  (coverage, output) => {
3301
3307
  const set = new Set(output.ci.keys.map(key => key.pubkey))
3302
3308
  const same = set.size === currentSet.size && current.every(pk => set.has(pk))
3303
3309
  if (!same) coverage.stale++
3304
3310
  for (const pk of current) if (!set.has(pk)) coverage.missing.add(pk)
3305
3311
  if (output.ci.keys.some(key => !currentSet.has(key.pubkey))) coverage.removedKeyOutputs++
3312
+ if (live && !opensWithAny(output.ci, live)) coverage.unreachableOutputs++
3306
3313
  },
3307
3314
  scopeToken
3308
3315
  )
@@ -3311,10 +3318,65 @@ export async function getVaultKeyCoverage(w: VaultWallet, adminOriginator: strin
3311
3318
  outputs: scan.outputs,
3312
3319
  stale: scan.state.stale,
3313
3320
  missingKeys: current.filter(pk => scan.state.missing.has(pk)), // meta order, each once
3314
- removedKeyOutputs: scan.state.removedKeyOutputs
3321
+ removedKeyOutputs: scan.state.removedKeyOutputs,
3322
+ unreachableOutputs: scan.state.unreachableOutputs
3315
3323
  }
3316
3324
  }
3317
3325
 
3326
+ /** Pubkeys this vault may still hold: every active key, plus one whose
3327
+ * removal has not finished (it can still open the outputs awaiting re-lock). */
3328
+ export function liveVaultPubkeys(meta: Pick<VaultMeta, 'keys' | 'pendingRemoval'>): Set<string> {
3329
+ const live = new Set(meta.keys.map(k => k.pubkey))
3330
+ if (meta.pendingRemoval) live.add(meta.pendingRemoval.key.pubkey)
3331
+ return live
3332
+ }
3333
+
3334
+ /** Whether any of `live` is among the keys an output's record commits to. */
3335
+ export function opensWithAny(ci: Pick<VaultInstructions, 'keys'>, live: ReadonlySet<string>): boolean {
3336
+ return ci.keys.some(key => live.has(key.pubkey))
3337
+ }
3338
+
3339
+ /**
3340
+ * Relinquish every vault output no live key can open (liveVaultPubkeys) —
3341
+ * the deposits an earlier setup of the same YubiKeys left behind, since each
3342
+ * setup writes fresh PIV keys. Deleting the rows locally is not enough: the
3343
+ * encrypted backup replays them on the next restore. relinquishOutput bumps
3344
+ * the row's updated_at, so the next backup push carries the cleared basket
3345
+ * and a later replay merges it in over the older copy.
3346
+ *
3347
+ * The key list must authenticate first (requireAuthenticatedMeta): a forged
3348
+ * list would make every real deposit look unreachable. Relinquishing only
3349
+ * hides an output from the basket; the coins stay on-chain, and
3350
+ * recoverVaultFromChain skips them for the same reason.
3351
+ */
3352
+ export async function forgetUnreachableVaultOutputs(
3353
+ w: VaultWallet,
3354
+ adminOriginator: string
3355
+ ): Promise<{ forgotten: number }> {
3356
+ const scopeToken = vaultStore.captureScopeToken()
3357
+ return await withVaultMutation(async () => {
3358
+ assertVaultScope(scopeToken)
3359
+ const stored = await vaultStore.getMeta(scopeToken)
3360
+ if (!stored) throw new VaultError('not-enrolled', 'Vault is not set up')
3361
+ const meta = await requireAuthenticatedMeta(w, adminOriginator, scopeToken, stored)
3362
+ const live = liveVaultPubkeys(meta)
3363
+ const { state: unreachable } = await reduceVerifiedVaultOutputs(
3364
+ w,
3365
+ adminOriginator,
3366
+ () => [] as string[],
3367
+ (outpoints, output) => {
3368
+ if (!opensWithAny(output.ci, live)) outpoints.push(output.outpoint)
3369
+ },
3370
+ scopeToken
3371
+ )
3372
+ for (const outpoint of unreachable) {
3373
+ assertVaultScope(scopeToken)
3374
+ await w.relinquishOutput({ basket: VAULT_BASKET, output: outpoint }, adminOriginator)
3375
+ }
3376
+ return { forgotten: unreachable.length }
3377
+ })
3378
+ }
3379
+
3318
3380
  /**
3319
3381
  * How many vault outputs would lose every remaining committed key if `pubkey`
3320
3382
  * were removed (spec §3.4) — the exact predicate Remove must satisfy: an
@@ -79,6 +79,9 @@ export type VaultErrorCode =
79
79
  /** Restored metadata exists, but this serial has not yet passed the fresh
80
80
  * possession challenge on this device. */
81
81
  | 'key-not-adopted'
82
+ /** Restore-with-a-YubiKey: the tapped card holds no key that any vault
83
+ * deposit found on the blockchain is locked to. */
84
+ | 'key-opens-nothing'
82
85
  /** VAULT_MAX_ACTIVE_KEYS keys already enrolled (one more than a lock holds). */
83
86
  | 'too-many-keys'
84
87
  /** The key list holds more keys than a lock can commit (VAULT_MAX_KEYS): a
@@ -66,7 +66,7 @@ import {
66
66
  import { buildOfflineHoldResult, groupOfflineHolds } from '../offline/hold'
67
67
  import { getOnline } from '../net/online'
68
68
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
69
- import { isR1CLockingScript } from '../services/vault/guard'
69
+ import { anyAdminOutpoint, anyAdminTransaction, isAdminOutput } from './methods/vaultGuardSql'
70
70
  import type {
71
71
  AuthId,
72
72
  FindCertificateFieldsArgs,
@@ -154,24 +154,46 @@ export class StorageExpoSQLite extends StorageProvider {
154
154
  }
155
155
 
156
156
  /**
157
- * Final Vault authorization check for explicit transaction inputs.
157
+ * Admin-state check for explicit transaction inputs.
158
158
  *
159
- * The toolbox invokes this only after it has resolved the immutable source
160
- * locking script from authenticated local storage or verified BEEF. This is
161
- * the database-side backstop for history-scan races: even if an R1C output
162
- * appears between an external guard scan and createAction, the reservation
163
- * cannot proceed without the host-derived internal-admin marker.
159
+ * The toolbox calls this after it has resolved each input's source from
160
+ * authenticated local storage (`input.output`) or verified BEEF. A stored
161
+ * output that is admin state — held in an `admin`-prefixed basket (the
162
+ * Vault's `admin vault`), or created by a `vault`/`admin*`-labelled
163
+ * transaction, which still covers a Vault output relinquished by "forget
164
+ * unreachable deposits" — can be named as an input only by the app's own
165
+ * admin originator, which the patched Wallet.createAction records as
166
+ * `__bsvVaultAdminAuthorized`. Running inside createAction, this also covers
167
+ * a caller that reaches the wallet without going through guardVaultAccess.
168
+ *
169
+ * The locking script does not decide: an app may hold and spend R1C outputs
170
+ * of its own.
164
171
  */
165
172
  async validateResolvedActionInput(
166
173
  vargs: { __bsvVaultAdminAuthorized?: boolean },
167
- input: { lockingScript?: { toHex(): string } }
174
+ input: { output?: { outputId?: number } }
168
175
  ): Promise<void> {
169
- const lockingScript = input.lockingScript?.toHex()
170
- if (lockingScript && isR1CLockingScript(lockingScript) && vargs.__bsvVaultAdminAuthorized !== true) {
171
- throw new Error('Vault R1C inputs require internal wallet authorization')
176
+ if (vargs.__bsvVaultAdminAuthorized === true) return
177
+ const outputId = input.output?.outputId
178
+ if (outputId == null) return
179
+ if (await isAdminOutput(this.getDB(), outputId)) {
180
+ throw new Error('Inputs holding admin or Vault state require internal wallet authorization')
172
181
  }
173
182
  }
174
183
 
184
+ /** guardVaultAccess lookup: is any `txid.vout` admin state (admin-prefixed
185
+ * basket, or a Vault/admin transaction's output)? Reads basket names and
186
+ * labels only (see methods/vaultGuardSql.ts). */
187
+ async anyAdminOutpoint(outpoints: string[]): Promise<boolean> {
188
+ return await anyAdminOutpoint(this.getDB(), outpoints)
189
+ }
190
+
191
+ /** guardVaultAccess lookup: is any txid a Vault or admin transaction? Reads
192
+ * labels and basket names only (see methods/vaultGuardSql.ts). */
193
+ async anyAdminTransaction(txids: string[]): Promise<boolean> {
194
+ return await anyAdminTransaction(this.getDB(), txids)
195
+ }
196
+
175
197
  // ============================================================================
176
198
  // Infrastructure methods
177
199
  // ============================================================================