@bsv/expo-wallet-toolbox 0.9.0 → 0.11.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.
@@ -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
@@ -45,7 +58,7 @@ const MAX_EXTERNAL_ACTION_OFFSET = MAX_ACTION_SCAN
45
58
  */
46
59
  const MAX_EXTERNAL_LIST_OUTPUTS_RESULTS = 200
47
60
  const MAX_EXTERNAL_LIST_OUTPUTS_RESULTS_WITH_TRANSACTIONS = 25
48
- /** Permission-backed reads must never retain the exclusive inventory slot
61
+ /** Permission-backed reads must never retain the exclusive listActions slot
49
62
  * indefinitely while a connected origin leaves a prompt unanswered. */
50
63
  export const EXTERNAL_ACTION_READ_TIMEOUT_MS = 30_000
51
64
  /** Bound queued scans as well as active scans. A connected origin can issue
@@ -162,48 +175,40 @@ function requestsPendingAbortAuthorityProtocol(args: unknown): boolean {
162
175
  return matchesProtocolNamespace(args, PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES)
163
176
  }
164
177
 
165
- /** Operations that can name an existing output or unsigned action without
166
- * going through basket-listing permission checks. */
178
+ /** Operations whose arguments can name an existing output by outpoint, or a
179
+ * held transaction by txid (`options.sendWith`), without going through the
180
+ * permissions manager's basket checks. */
167
181
  const OUTPUT_NAMING = new Set<keyof WalletInterface>([
168
182
  'createAction',
169
183
  'internalizeAction',
170
184
  'relinquishOutput',
171
- 'signAction',
172
- 'abortAction'
185
+ 'signAction'
173
186
  ])
174
187
 
175
188
  /**
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.
189
+ * Point lookups against the wallet's own storage. StorageExpoSQLite implements
190
+ * both (see core/storage/methods/vaultGuardSql.ts); each reads only the rows
191
+ * named and never a locking script.
193
192
  */
194
- export const VAULT_ABORT_REPLAY_MARKER = Symbol('vault-guard-replay-abort')
193
+ export interface VaultGuardLookup {
194
+ /** True when any canonical `txid.vout` is held in an `admin`-prefixed
195
+ * basket, or has no basket but is tagged `vault` or was created by a
196
+ * `vault`/`admin*`-labelled transaction (a relinquished Vault output). */
197
+ anyAdminOutpoint(outpoints: string[]): Promise<boolean>
198
+ /** True when any lowercase txid is labelled `vault` or `admin*`, or creates
199
+ * or spends an output in an `admin`-prefixed basket. */
200
+ anyAdminTransaction(txids: string[]): Promise<boolean>
201
+ }
195
202
 
196
- interface ExtendedWalletAction extends WalletAction {
197
- reference?: string
203
+ export interface GuardVaultAccessOptions {
204
+ /** Required for an external call that names an outpoint or a sendWith txid;
205
+ * without it such a call is refused. Supplied once, where the wallet is
206
+ * built; re-wrapping the same wallet later keeps it. */
207
+ lookup?: VaultGuardLookup
198
208
  }
199
209
 
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>
210
+ interface ExtendedWalletAction extends WalletAction {
211
+ reference?: string
207
212
  }
208
213
 
209
214
  interface GuardRuntime {
@@ -212,6 +217,7 @@ interface GuardRuntime {
212
217
  /** Concurrent byte-identical external listActions reads share one scan.
213
218
  * Entries exist only while the scan is in flight; there is no stale cache. */
214
219
  reads: Map<string, Promise<ListActionsResult>>
220
+ lookup?: VaultGuardLookup
215
221
  }
216
222
 
217
223
  /** One runtime per underlying wallet even if it is wrapped more than once. */
@@ -236,15 +242,11 @@ function runtimeFor(wallet: object): GuardRuntime {
236
242
  return runtime
237
243
  }
238
244
 
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')
245
+ /** Run one external enriched listActions scan at a time, with a bounded queue,
246
+ * so concurrent reads from a connected app cannot pile up history pages in
247
+ * memory. */
248
+ async function withGuardSlot<T>(runtime: GuardRuntime, work: () => Promise<T>): Promise<T> {
249
+ if (runtime.queued >= MAX_GUARDED_QUEUE) throw new Error('Too many guarded wallet operations')
248
250
  runtime.queued++
249
251
  const predecessor = runtime.tail
250
252
  let release!: () => void
@@ -498,32 +500,9 @@ async function listActionsForExternal(
498
500
  }
499
501
  }
500
502
 
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
503
  /** `sendWith` is a broadcast capability for a previously signed noSend action.
525
504
  * Both createAction and signAction accept it, including when the surrounding
526
- * request does not otherwise touch a Vault input/output/reference. */
505
+ * request names no input or output at all. */
527
506
  function requestedSendWithTxids(method: keyof WalletInterface, args: any): string[] | undefined {
528
507
  if (method !== 'createAction' && method !== 'signAction') return []
529
508
  const value = args?.options?.sendWith
@@ -566,26 +545,32 @@ function requestedOutpoints(method: keyof WalletInterface, args: any): string[]
566
545
  return canonical.some(value => value === undefined) ? undefined : (canonical as string[])
567
546
  }
568
547
 
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
548
+ /** Whether an external output-naming call names an admin-state outpoint or a
549
+ * Vault/admin transaction. Unparseable arguments, a missing lookup
550
+ * and a failed lookup all count as yes. */
551
+ async function namesAdminState(runtime: GuardRuntime, method: keyof WalletInterface, args: any): Promise<boolean> {
552
+ const outpoints = requestedOutpoints(method, args)
553
+ const sendWith = requestedSendWithTxids(method, args)
554
+ if (outpoints === undefined || sendWith === undefined) return true
555
+ if (outpoints.length === 0 && sendWith.length === 0) return false
556
+ const lookup = runtime.lookup
557
+ if (!lookup) return true
573
558
  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
- })
559
+ if (outpoints.length > 0 && (await lookup.anyAdminOutpoint(outpoints))) return true
560
+ return sendWith.length > 0 && (await lookup.anyAdminTransaction(sendWith))
581
561
  } catch {
582
- return false
562
+ return true
583
563
  }
584
564
  }
585
565
 
586
566
  /** Wrap every wallet handed to an external caller. */
587
- export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOriginator: string): T {
567
+ export function guardVaultAccess<T extends WalletInterface>(
568
+ wallet: T,
569
+ adminOriginator: string,
570
+ options: GuardVaultAccessOptions = {}
571
+ ): T {
588
572
  const targetWallet = underlyingWallet(wallet as object) as T
573
+ if (options.lookup) runtimeFor(targetWallet as object).lookup = options.lookup
589
574
  let byAuthority = GUARDED_PROXIES.get(targetWallet as object)
590
575
  const existing = byAuthority?.get(adminOriginator)
591
576
  if (existing) return existing as T
@@ -657,70 +642,21 @@ export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOrig
657
642
  if (!PRIVILEGED_CAPABLE.has(method) && !OUTPUT_NAMING.has(method)) return value.bind(target)
658
643
 
659
644
  return async (args: any, originator?: string) => {
645
+ if (originator === adminOriginator) return await bound(args, originator)
660
646
  if (
661
647
  PRIVILEGED_CAPABLE.has(method) &&
662
- originator !== adminOriginator &&
663
- (requestsVaultProtocol(args) ||
648
+ (args?.privileged ||
649
+ requestsVaultProtocol(args) ||
664
650
  requestsReservedRailProtocol(args) ||
665
651
  requestsConnectionAuthorityProtocol(args) ||
666
652
  requestsPendingAbortAuthorityProtocol(args))
667
653
  ) {
668
654
  return deny(String(method), originator)
669
655
  }
670
- if (PRIVILEGED_CAPABLE.has(method) && args?.privileged && originator !== adminOriginator) {
656
+ if (OUTPUT_NAMING.has(method) && (await namesAdminState(runtime, method, args))) {
671
657
  return deny(String(method), originator)
672
658
  }
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)
659
+ return await bound(args, originator)
724
660
  }
725
661
  }
726
662
  })
@@ -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
  // ============================================================================
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Point lookups the external-wallet guard (core/services/vault/guard.ts) runs
3
+ * before it lets a connected app name an existing output or release a held
4
+ * transaction.
5
+ *
6
+ * Each query touches only the rows the caller named, reads basket names,
7
+ * labels and tags, and stops at the first hit. None of them select a locking script,
8
+ * so a Vault output's ~45 KB R1C script never leaves the database.
9
+ *
10
+ * No `userId` filter: a StorageExpoSQLite file belongs to one identity. If a
11
+ * file ever held more than one user, a hit on another user's row would refuse
12
+ * the call, which is the safe direction.
13
+ */
14
+
15
+ /** BRC-100 reserves every basket and label that starts with this for the
16
+ * wallet itself (WalletPermissionsManager's `isAdminBasket`/`isAdminLabel`). */
17
+ export const ADMIN_PREFIX = 'admin'
18
+
19
+ /** The label every Vault deposit, withdrawal and re-lock carries. */
20
+ export const VAULT_ACTION_LABEL = 'vault'
21
+
22
+ /** The tag every Vault output carries, from a deposit, re-lock or chain
23
+ * recovery alike. Chain recovery internalizes without a `vault` label. */
24
+ export const VAULT_OUTPUT_TAG = 'vault'
25
+
26
+ /** Placeholders per statement, kept under the lowest SQLITE_MAX_VARIABLE_NUMBER
27
+ * a shipped SQLite still enforces (999). */
28
+ const MAX_BOUND_VARIABLES = 998
29
+
30
+ const IS_ADMIN_BASKET = `substr("b"."name", 1, ${ADMIN_PREFIX.length}) = '${ADMIN_PREFIX}'`
31
+
32
+ /** The transaction whose id is `transactionIdSql` carries the `vault` label or
33
+ * an `admin*` label. */
34
+ function hasAdminLabel(transactionIdSql: string): string {
35
+ return (
36
+ 'EXISTS (SELECT 1 FROM "tx_labels_map" "m" JOIN "tx_labels" "l" ON "l"."txLabelId" = "m"."txLabelId" ' +
37
+ `WHERE "m"."transactionId" = ${transactionIdSql} AND ("l"."label" = '${VAULT_ACTION_LABEL}' ` +
38
+ `OR substr("l"."label", 1, ${ADMIN_PREFIX.length}) = '${ADMIN_PREFIX}'))`
39
+ )
40
+ }
41
+
42
+ /** The output `o` carries the Vault output tag. */
43
+ const HAS_VAULT_TAG =
44
+ 'EXISTS (SELECT 1 FROM "output_tags_map" "tm" JOIN "output_tags" "tg" ON "tg"."outputTagId" = "tm"."outputTagId" ' +
45
+ `WHERE "tm"."outputId" = "o"."outputId" AND "tg"."tag" = '${VAULT_OUTPUT_TAG}')`
46
+
47
+ /**
48
+ * An output row `o` (with its basket LEFT JOINed as `b`) is admin state when it
49
+ * sits in an `admin`-prefixed basket, or when it has no basket (relinquished,
50
+ * e.g. by "forget unreachable deposits") and is still recognisably a Vault or
51
+ * admin output: tagged `vault`, or created by a `vault`/`admin*`-labelled
52
+ * transaction. The label and tag count only for an unbasketed row, so an
53
+ * app's own basketed outputs never collide with them.
54
+ *
55
+ * `default` is deliberately not included: an app retrying internalizeAction
56
+ * for a payment the wallet already holds as change names a `default` output,
57
+ * and the toolbox treats that retry as a no-op.
58
+ */
59
+ const IS_ADMIN_OUTPUT =
60
+ `((${IS_ADMIN_BASKET}) OR ` +
61
+ `("o"."basketId" IS NULL AND (${HAS_VAULT_TAG} OR ${hasAdminLabel('"o"."transactionId"')})))`
62
+
63
+ const OUTPUT_WITH_BASKET = 'FROM "outputs" "o" LEFT JOIN "output_baskets" "b" ON "b"."basketId" = "o"."basketId" '
64
+
65
+ /**
66
+ * Hit when any named outpoint is admin state (see IS_ADMIN_OUTPUT).
67
+ *
68
+ * One OR-group per outpoint rather than a row-value IN, so the query works on
69
+ * any SQLite build (same shape as `spendingReferencesSql`).
70
+ */
71
+ export function adminOutpointsSql(pairCount: number): string {
72
+ const groups = Array.from({ length: pairCount }, () => '("o"."txid" = ? AND "o"."vout" = ?)').join(' OR ')
73
+ return `SELECT 1 AS hit ${OUTPUT_WITH_BASKET}WHERE (${groups}) AND ${IS_ADMIN_OUTPUT} LIMIT 1`
74
+ }
75
+
76
+ /** Hit when the output with this `outputId` is admin state. */
77
+ export const ADMIN_OUTPUT_BY_ID_SQL = `SELECT 1 AS hit ${OUTPUT_WITH_BASKET}WHERE "o"."outputId" = ? AND ${IS_ADMIN_OUTPUT} LIMIT 1`
78
+
79
+ /**
80
+ * Hit when any named txid is a Vault or admin transaction: labelled `vault` or
81
+ * `admin*`, or creating or spending an output in an admin-prefixed basket.
82
+ *
83
+ * Spending is matched through `outputs.spentBy`, which the toolbox sets when
84
+ * an action reserves its inputs, so a signed-but-held withdrawal is caught
85
+ * before it is broadcast.
86
+ */
87
+ export function adminTransactionsSql(txidCount: number): string {
88
+ const placeholders = Array.from({ length: txidCount }, () => '?').join(', ')
89
+ return (
90
+ 'SELECT 1 AS hit FROM "transactions" "t" ' +
91
+ `WHERE "t"."txid" IN (${placeholders}) AND (` +
92
+ `${hasAdminLabel('"t"."transactionId"')} ` +
93
+ 'OR EXISTS (SELECT 1 FROM "outputs" "o" JOIN "output_baskets" "b" ON "b"."basketId" = "o"."basketId" ' +
94
+ `WHERE "o"."transactionId" = "t"."transactionId" AND ${IS_ADMIN_BASKET}) ` +
95
+ 'OR EXISTS (SELECT 1 FROM "outputs" "o" JOIN "output_baskets" "b" ON "b"."basketId" = "o"."basketId" ' +
96
+ `WHERE "o"."spentBy" = "t"."transactionId" AND ${IS_ADMIN_BASKET})` +
97
+ ') LIMIT 1'
98
+ )
99
+ }
100
+
101
+ /** The slice of an expo-sqlite handle these lookups use. */
102
+ export interface GuardSqlDb {
103
+ getFirstAsync(sql: string, params: (string | number)[]): Promise<unknown>
104
+ }
105
+
106
+ /** `txid.vout` pairs, as the guard canonicalizes them (lowercase txid). */
107
+ export async function anyAdminOutpoint(db: GuardSqlDb, outpoints: string[]): Promise<boolean> {
108
+ const pairs = outpoints.map(outpoint => {
109
+ const dot = outpoint.lastIndexOf('.')
110
+ const txid = outpoint.slice(0, dot).toLowerCase()
111
+ const vout = Number(outpoint.slice(dot + 1))
112
+ if (!/^[0-9a-f]{64}$/.test(txid) || !Number.isSafeInteger(vout) || vout < 0) {
113
+ throw new Error(`Invalid outpoint ${outpoint}`)
114
+ }
115
+ return [txid, vout] as const
116
+ })
117
+ const perStatement = Math.floor(MAX_BOUND_VARIABLES / 2)
118
+ for (let i = 0; i < pairs.length; i += perStatement) {
119
+ const chunk = pairs.slice(i, i + perStatement)
120
+ if (await db.getFirstAsync(adminOutpointsSql(chunk.length), chunk.flat())) return true
121
+ }
122
+ return false
123
+ }
124
+
125
+ export async function anyAdminTransaction(db: GuardSqlDb, txids: string[]): Promise<boolean> {
126
+ const normalized = txids.map(txid => {
127
+ const lower = txid.toLowerCase()
128
+ if (!/^[0-9a-f]{64}$/.test(lower)) throw new Error(`Invalid txid ${txid}`)
129
+ return lower
130
+ })
131
+ for (let i = 0; i < normalized.length; i += MAX_BOUND_VARIABLES) {
132
+ const chunk = normalized.slice(i, i + MAX_BOUND_VARIABLES)
133
+ if (await db.getFirstAsync(adminTransactionsSql(chunk.length), chunk)) return true
134
+ }
135
+ return false
136
+ }
137
+
138
+ export async function isAdminOutput(db: GuardSqlDb, outputId: number): Promise<boolean> {
139
+ return !!(await db.getFirstAsync(ADMIN_OUTPUT_BY_ID_SQL, [outputId]))
140
+ }
@@ -27,7 +27,10 @@ export function bytesForColumn(column: string, value: unknown): Uint8Array | und
27
27
  /** Map an update field to a SQL bind, or omit it from the SET clause. */
28
28
  export function sqlBindValue(table: string, column: string, value: unknown): SqlBindResult {
29
29
  if (value === undefined) {
30
- if (table === 'outputs' && column === 'spentBy') {
30
+ // Both mean "cleared" to their writers: spentBy on a released reservation,
31
+ // basketId on relinquishOutput and on a synced relinquish arriving through
32
+ // EntityOutput.mergeExisting. Skipping either left the old value in place.
33
+ if (table === 'outputs' && (column === 'spentBy' || column === 'basketId')) {
31
34
  return { omit: false, value: null }
32
35
  }
33
36
  return { omit: true }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",