@bsv/expo-wallet-toolbox 0.24.3 → 0.25.1

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.
@@ -0,0 +1,133 @@
1
+ /**
2
+ * One request pacer for every WhatsOnChain call in the app.
3
+ *
4
+ * WhatsOnChain answers more than 3 requests per second from one client with no
5
+ * API key with HTTP 429. Before this module, each feature paced itself or not at
6
+ * all: the Vault chain scan sent 3 history requests per index back to back, so
7
+ * an empty gap of 20 indices was 60 requests with no pause, and a sweep,
8
+ * a proof refresh or a broadcast at the same time added to the same quota.
9
+ *
10
+ * Every WhatsOnChain request now takes a slot from a lane before it is sent. A
11
+ * lane is one API origin, for requests with no key. The slot is reserved
12
+ * synchronously, before any await, so callers that start at the same moment
13
+ * queue behind each other instead of passing together. The first request on an
14
+ * idle lane goes at once.
15
+ *
16
+ * A request that carries a `woc-api-key` header uses a lane of its own: it
17
+ * counts against the key's quota, not the anonymous one. That lane has the same
18
+ * spacing by default, because the tier of a key is not known here; a host with
19
+ * a paid key can lower `keyedIntervalMs`. A 429 on any lane pushes that lane's
20
+ * next slot out by `pauseMs`.
21
+ */
22
+
23
+ /** Spacing of requests with no key: 2.5 per second, under the limit of 3 with room for network jitter. */
24
+ export const WOC_ANON_INTERVAL_MS = 400
25
+ /** Extra pause on a lane after WhatsOnChain answers 429. */
26
+ export const WOC_RATE_LIMIT_PAUSE_MS = 1500
27
+ /** The header WhatsOnChain reads an API key from. */
28
+ export const WOC_KEY_HEADER = 'woc-api-key'
29
+
30
+ export interface WocLimiterOptions {
31
+ /** Spacing of requests with no key. */
32
+ intervalMs: number
33
+ /** Spacing of requests with a key. */
34
+ keyedIntervalMs: number
35
+ /** Extra pause after a 429. */
36
+ pauseMs: number
37
+ now: () => number
38
+ sleep: (ms: number) => Promise<void>
39
+ }
40
+
41
+ const defaults = (): WocLimiterOptions => ({
42
+ intervalMs: WOC_ANON_INTERVAL_MS,
43
+ keyedIntervalMs: WOC_ANON_INTERVAL_MS,
44
+ pauseMs: WOC_RATE_LIMIT_PAUSE_MS,
45
+ now: () => Date.now(),
46
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms))
47
+ })
48
+
49
+ let options: WocLimiterOptions = defaults()
50
+ /** Lane name to the earliest time its next request may go. */
51
+ const nextSlot = new Map<string, number>()
52
+
53
+ /** Change the limiter's spacing or clock (tests, or a host with a paid key). Clears every lane. */
54
+ export function configureWocLimiter(over: Partial<WocLimiterOptions>): void {
55
+ options = { ...options, ...over }
56
+ nextSlot.clear()
57
+ }
58
+
59
+ /** Back to the default spacing and clock, with every lane idle. */
60
+ export function resetWocLimiter(): void {
61
+ options = defaults()
62
+ nextSlot.clear()
63
+ }
64
+
65
+ function originOf(url: string): string {
66
+ const match = /^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i.exec(url)
67
+ return match ? match[0].toLowerCase() : url
68
+ }
69
+
70
+ function hasKey(headers: HeadersInit | undefined): boolean {
71
+ if (!headers) return false
72
+ if (Array.isArray(headers)) return headers.some(([name, value]) => name.toLowerCase() === WOC_KEY_HEADER && !!value)
73
+ if (typeof (headers as Headers).get === 'function') return !!(headers as Headers).get(WOC_KEY_HEADER)
74
+ return Object.entries(headers as Record<string, string>).some(
75
+ ([name, value]) => name.toLowerCase() === WOC_KEY_HEADER && !!value
76
+ )
77
+ }
78
+
79
+ function laneFor(url: string, keyed: boolean): string {
80
+ return `${originOf(url)}|${keyed ? 'key' : 'anon'}`
81
+ }
82
+
83
+ /**
84
+ * Reserve this request's slot and return how long to wait for it (0 on an
85
+ * idle lane). The reservation is synchronous, so the order of calls is the
86
+ * order of requests.
87
+ */
88
+ export function reserveWocSlot(url: string, keyed = false): number {
89
+ const lane = laneFor(url, keyed)
90
+ const now = options.now()
91
+ const at = Math.max(now, nextSlot.get(lane) ?? 0)
92
+ nextSlot.set(lane, at + (keyed ? options.keyedIntervalMs : options.intervalMs))
93
+ return at - now
94
+ }
95
+
96
+ /** Wait the time that `reserveWocSlot` returned. Resolves at once for 0. */
97
+ export function waitWocSlot(ms: number): Promise<void> {
98
+ return ms > 0 ? options.sleep(ms) : Promise.resolve()
99
+ }
100
+
101
+ /** Reserve this request's slot and wait for it. */
102
+ export function wocSlot(url: string, keyed = false): Promise<void> {
103
+ return waitWocSlot(reserveWocSlot(url, keyed))
104
+ }
105
+
106
+ /** Record a 429 on a lane: its next slot moves out by `pauseMs`. */
107
+ export function wocRateLimited(url: string, keyed = false): void {
108
+ const lane = laneFor(url, keyed)
109
+ const until = options.now() + options.pauseMs
110
+ nextSlot.set(lane, Math.max(nextSlot.get(lane) ?? 0, until))
111
+ }
112
+
113
+ type FetchLike = (url: string, init?: RequestInit) => Promise<Response>
114
+
115
+ /**
116
+ * `fetch` for WhatsOnChain, paced by the shared limiter. A GET or HEAD that
117
+ * gets 429 is sent once more, after the lane's pause; the second answer is
118
+ * returned as it is, so a caller still sees a 429 that lasts.
119
+ */
120
+ export async function wocLimitedFetch(url: string, init?: RequestInit, fetchImpl?: FetchLike): Promise<Response> {
121
+ const doFetch: FetchLike = fetchImpl ?? ((u, i) => (i ? fetch(u, i) : fetch(u)))
122
+ const keyed = hasKey(init?.headers)
123
+ const method = (init?.method ?? 'GET').toUpperCase()
124
+ const retryable = method === 'GET' || method === 'HEAD'
125
+ for (let attempt = 0; ; attempt++) {
126
+ const wait = reserveWocSlot(url, keyed)
127
+ if (wait > 0) await waitWocSlot(wait)
128
+ const response = await doFetch(url, init)
129
+ if (response.status !== 429) return response
130
+ wocRateLimited(url, keyed)
131
+ if (!retryable || attempt >= 1) return response
132
+ }
133
+ }
@@ -24,6 +24,7 @@
24
24
  */
25
25
  import { Beef, Utils } from '@bsv/sdk'
26
26
  import { MAX_HEX_RESPONSE_CHARS, wocRequestInit, type WocConfig } from './rails/address'
27
+ import { wocLimitedFetch } from '../net/wocLimiter'
27
28
 
28
29
  /** Injectable for tests; production uses global fetch. */
29
30
  export type FetchLike = (
@@ -45,7 +46,8 @@ export async function refetchAtomicBeef(args: {
45
46
  fetchImpl?: FetchLike
46
47
  }): Promise<number[] | undefined> {
47
48
  const { woc, txid } = args
48
- const doFetch = args.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)
49
+ // An injected fetch is used as it is; the default goes through the shared WhatsOnChain limiter.
50
+ const doFetch = args.fetchImpl ?? (wocLimitedFetch as unknown as FetchLike)
49
51
 
50
52
  let bytes: number[]
51
53
  try {
@@ -26,6 +26,7 @@ import { abbreviateKey, addressLabel, FROM_ADDRESS_LABEL_PREFIX, TO_ADDRESS_LABE
26
26
  import { addressNetwork, isValidBsvAddress } from './index'
27
27
 
28
28
  import { BRC29_PROTOCOL_ID } from '../../peerpay/brc29'
29
+ import { wocLimitedFetch } from '../../net/wocLimiter'
29
30
  export { BRC29_PROTOCOL_ID } from '../../peerpay/brc29'
30
31
 
31
32
  /** Whether the address rail can carry a particular payment, and why not when it cannot. */
@@ -183,8 +184,7 @@ export function wocRequestInit(woc: WocConfig): { headers: Record<string, string
183
184
 
184
185
  /** A WhatsOnChain GET that turns a 429 into WocRateLimited. Shared with pay/rails/sweep.ts. */
185
186
  export async function wocFetch(woc: WocConfig, url: string): Promise<Response> {
186
- const init = wocRequestInit(woc)
187
- const response = init ? await fetch(url, init) : await fetch(url)
187
+ const response = await wocLimitedFetch(url, wocRequestInit(woc))
188
188
  if (response.status === 429) throw new WocRateLimited()
189
189
  return response
190
190
  }
@@ -19,26 +19,44 @@ export interface ParsedShare {
19
19
  y: string
20
20
  threshold: number
21
21
  integrity: string
22
+ /** Random per print, identical on every page of one print. Absent on old 4-part pages. */
23
+ printId?: string
24
+ }
25
+
26
+ /** Crockford base32 without I, L, O, U. */
27
+ export const PRINT_ID_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
28
+ export const PRINT_ID_LENGTH = 6
29
+
30
+ /** True when the value is exactly PRINT_ID_LENGTH characters from PRINT_ID_ALPHABET. */
31
+ export function isPrintId(value: string): boolean {
32
+ if (typeof value !== 'string' || value.length !== PRINT_ID_LENGTH) return false
33
+ for (const ch of value) if (!PRINT_ID_ALPHABET.includes(ch)) return false
34
+ return true
22
35
  }
23
36
 
24
37
  /**
25
- * Parse and validate a single backup share string.
38
+ * Parse and validate a single backup share string: `x.y.threshold.integrity`
39
+ * (old, 4 parts) or `x.y.threshold.integrity.printId` (5 parts). `raw` is
40
+ * always the 4-part canonical string without the print ID, so
41
+ * PrivateKey.fromBackupShares keeps working unchanged.
26
42
  * @returns Parsed share or null if invalid format
27
43
  */
28
44
  export function parseShare(shareString: string): ParsedShare | null {
29
45
  const parts = shareString.trim().split('.')
30
- if (parts.length !== 4) return null
46
+ if (parts.length !== 4 && parts.length !== 5) return null
31
47
 
32
- const [x, y, thresholdStr, integrity] = parts
48
+ const [x, y, thresholdStr, integrity, printId] = parts
49
+ if (parts.length === 5 && !isPrintId(printId)) return null
33
50
  const threshold = Number(thresholdStr)
34
51
 
35
52
  if (!x || !y || isNaN(threshold) || threshold < 2 || !integrity) return null
36
53
 
37
- return { raw: shareString.trim(), x, y, threshold, integrity }
54
+ const raw = parts.slice(0, 4).join('.')
55
+ return parts.length === 5 ? { raw, x, y, threshold, integrity, printId } : { raw, x, y, threshold, integrity }
38
56
  }
39
57
 
40
58
  /** Why a newly scanned share cannot join the shares collected so far. */
41
- export type ShareCompatibilityIssue = 'threshold-mismatch' | 'integrity-mismatch' | 'duplicate'
59
+ export type ShareCompatibilityIssue = 'threshold-mismatch' | 'integrity-mismatch' | 'duplicate' | 'print-mismatch'
42
60
 
43
61
  /**
44
62
  * Validate that a new share is compatible with previously collected shares.
@@ -61,6 +79,11 @@ export function checkShareCompatibility(
61
79
  return 'integrity-mismatch'
62
80
  }
63
81
 
82
+ // One print never mixes IDs, and never mixes an ID with no ID.
83
+ if (newShare.printId !== first.printId) {
84
+ return 'print-mismatch'
85
+ }
86
+
64
87
  // Check for duplicate (same x.y point)
65
88
  const isDuplicate = existing.some(s => s.x === newShare.x && s.y === newShare.y)
66
89
  if (isDuplicate) {
@@ -73,7 +96,8 @@ export function checkShareCompatibility(
73
96
  const COMPATIBILITY_MESSAGES: Record<ShareCompatibilityIssue, string> = {
74
97
  'threshold-mismatch': 'Threshold does not match previous shares',
75
98
  'integrity-mismatch': 'Integrity hash does not match — shares are from different keys',
76
- duplicate: 'This share has already been scanned'
99
+ duplicate: 'This share has already been scanned',
100
+ 'print-mismatch': 'These slices are from different prints and do not combine'
77
101
  }
78
102
 
79
103
  /**
@@ -2,10 +2,11 @@
2
2
  * Backup shares — Shamir 2-of-3 recovery paper.
3
3
  *
4
4
  * The secret being split is the MNEMONIC ENTROPY, per BRC-157, not the primary
5
- * key at m/0'/0'. That derivation is hardened and one-way, so shares of it can
6
- * restore spending authority but can never rebuild the phrase — and the vault
7
- * key needs the phrase. Splitting the entropy makes paper and phrase two
8
- * encodings of one secret.
5
+ * key at m/0'/0'. That derivation is hardened and one-way, so shares of the
6
+ * primary key restore spending authority and the wallet half of the Vault
7
+ * secret, but never the phrase. The Vault refuses to be set up on a wallet that
8
+ * has no phrase (`requireMnemonicWallet`). Splitting the entropy makes paper
9
+ * and phrase two encodings of one secret.
9
10
  *
10
11
  * The split payload is always exactly 32 bytes:
11
12
  *
@@ -28,9 +29,10 @@
28
29
  * of the modules the sdk-free guard test proves never loads `@bsv/sdk`.
29
30
  */
30
31
 
31
- import { PrivateKey, Hash } from '@bsv/sdk'
32
+ import { PrivateKey, Hash, Random } from '@bsv/sdk'
32
33
 
33
34
  export * from './shareParsing'
35
+ import { isPrintId, parseShare, PRINT_ID_ALPHABET, PRINT_ID_LENGTH } from './shareParsing'
34
36
  import type { ParsedShare } from './shareParsing'
35
37
 
36
38
  // ── Payload framing ──────────────────────────────────────────────────────────
@@ -102,6 +104,33 @@ export function generateLegacyKeyShares(
102
104
  return new PrivateKey(privateKeyBytes).toBackupShares(threshold, totalShares)
103
105
  }
104
106
 
107
+ // ── Print ID ─────────────────────────────────────────────────────────────────
108
+
109
+ /**
110
+ * A fresh random print ID: PRINT_ID_LENGTH characters from PRINT_ID_ALPHABET.
111
+ * Draws 32 random bytes and maps each with `byte % 32`. The alphabet has 32
112
+ * characters and 256 is a multiple of 32, so the mapping has no bias.
113
+ */
114
+ export function generatePrintId(): string {
115
+ const bytes = Random(32)
116
+ let id = ''
117
+ for (let i = 0; i < PRINT_ID_LENGTH; i++) id += PRINT_ID_ALPHABET[bytes[i] % 32]
118
+ return id
119
+ }
120
+
121
+ /**
122
+ * Add the print ID to a 4-part share: `${share}.${printId}`.
123
+ * @throws If the share is not a plain 4-part share or the ID is not valid
124
+ */
125
+ export function attachPrintId(share: string, printId: string): string {
126
+ if (!isPrintId(printId)) throw new Error('attachPrintId: invalid print ID')
127
+ const parsed = parseShare(share)
128
+ if (parsed === null || parsed.printId !== undefined || parsed.raw !== share) {
129
+ throw new Error('attachPrintId: expected a 4-part share')
130
+ }
131
+ return `${share}.${printId}`
132
+ }
133
+
105
134
  // ── Share validation ─────────────────────────────────────────────────────────
106
135
  // ParsedShare, parseShare, ShareCompatibilityIssue, checkShareCompatibility and
107
136
  // validateShareCompatibility live in shareParsing.ts and are re-exported above.
@@ -1,6 +1,7 @@
1
1
  import { Beef, Transaction } from '@bsv/sdk'
2
2
  import type { NetworkProfile, WocEndpoints } from '../networks'
3
3
  import { trimTrailingSlashes } from '../net/trimTrailingSlashes'
4
+ import { reserveWocSlot, waitWocSlot, wocRateLimited } from '../net/wocLimiter'
4
5
  import type { PostBeefResult, PostTxResultForTxid } from '../toolboxTypes'
5
6
 
6
7
  const BROADCAST_TIMEOUT_MS = 30_000
@@ -483,6 +484,10 @@ export function createWocBroadcastService(woc: WocEndpoints, apiKey?: string) {
483
484
  Accept: 'text/plain'
484
485
  }
485
486
  if (apiKey) headers['woc-api-key'] = apiKey
487
+ // The limiter wait comes before the deadline starts, so time in the
488
+ // queue never counts against this request's timeout.
489
+ const wait = reserveWocSlot(baseUrl, !!apiKey)
490
+ if (wait > 0) await waitWocSlot(wait)
486
491
  const response = await fetchWithBodyDeadline(
487
492
  `${baseUrl}/tx/raw`,
488
493
  {
@@ -492,6 +497,7 @@ export function createWocBroadcastService(woc: WocEndpoints, apiKey?: string) {
492
497
  },
493
498
  timeoutMs
494
499
  )
500
+ if (response.status === 429) wocRateLimited(baseUrl, !!apiKey)
495
501
  const body = await response.text()
496
502
  console.log(`[${name}] POST /tx/raw ${response.status}`, loggableSnippet(body))
497
503
  const txResult: PostTxResultForTxid = {
@@ -1,5 +1,6 @@
1
1
  import AsyncStorage from '@react-native-async-storage/async-storage'
2
2
  import type { BsvExchangeRate } from '../toolboxTypes'
3
+ import { reserveWocSlot, waitWocSlot, wocRateLimited } from '../net/wocLimiter'
3
4
 
4
5
  // Shared with context/ExchangeRateContext.tsx so a single cache serves both the
5
6
  // fiat-display UI and the wallet-build seed. Same key + same { usdPerBsv } shape.
@@ -8,6 +9,7 @@ import type { BsvExchangeRate } from '../toolboxTypes'
8
9
  export const CACHE_KEY = 'cached_exchange_rate'
9
10
  export const FALLBACK_RATE = 16.75
10
11
  const REFRESH_TIMEOUT_MS = 4000
12
+ const EXCHANGE_RATE_URL = 'https://api.whatsonchain.com/v1/bsv/main/exchangerate'
11
13
 
12
14
  /**
13
15
  * `getExchangeRate()`'s own return, plus a handle on the SAME background
@@ -31,12 +33,17 @@ export interface ExchangeRateSeed extends BsvExchangeRate {
31
33
  */
32
34
  function refreshExchangeRateCache(): Promise<number | undefined> {
33
35
  return (async () => {
36
+ // The limiter wait comes before the timeout starts, so time in the queue
37
+ // never counts against the request.
38
+ const wait = reserveWocSlot(EXCHANGE_RATE_URL)
39
+ if (wait > 0) await waitWocSlot(wait)
34
40
  const controller = new AbortController()
35
41
  const timeout = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS)
36
42
  try {
37
- const res = await fetch('https://api.whatsonchain.com/v1/bsv/main/exchangerate', {
43
+ const res = await fetch(EXCHANGE_RATE_URL, {
38
44
  signal: controller.signal
39
45
  })
46
+ if (res.status === 429) wocRateLimited(EXCHANGE_RATE_URL)
40
47
  const data = await res.json()
41
48
  const usdPerBsv = Number(data?.rate)
42
49
  if (Number.isFinite(usdPerBsv) && usdPerBsv > 0) {
@@ -32,8 +32,10 @@ import {
32
32
  } from './metaAuthority'
33
33
  import { compressPubkey, type VaultInstructionKey, type VaultInstructions } from './r1comb'
34
34
  import { randomBytes } from './random'
35
+ import { requireFundsGate, type VaultResetClearance } from './resetClearance'
35
36
  import { withKeySession, VaultSessionGuard } from './session'
36
37
  import { VaultError } from './types'
38
+ import { requireMnemonicWallet } from './walletKind'
37
39
  import {
38
40
  isVaultKeyRecord,
39
41
  isVaultMeta,
@@ -61,10 +63,10 @@ export interface VaultWalletAuthority {
61
63
  }
62
64
 
63
65
  /** Re-verify `existing`'s own wallet-root tag before trusting it as the
64
- * basis for a freshly, validly tagged `next` (addKey only APPENDS to
65
- * `meta.keys`, so a forged `existing` would otherwise "launder" straight
66
- * through the moment the legitimate user adds one more, genuinely their
67
- * own, key — see vaultStore.addKey's laundering caveat).
66
+ * basis for a freshly, validly tagged `next` (stageKey builds `next` from
67
+ * `existing`, so a forged `existing` would otherwise "launder" straight
68
+ * through the moment the legitimate user stages one more, genuinely their
69
+ * own, key — see vaultStore.stageKey's laundering caveat).
68
70
  *
69
71
  * Unlike transfers.ts's requireAuthenticatedMeta, this has no on-chain
70
72
  * fallback: VaultKeyService has no chain-scanning capability, and inventing
@@ -385,12 +387,19 @@ export async function enrollKey(args: {
385
387
  /** Explicit consent to destroy and replace an existing key in Vault's fixed
386
388
  * slot 0x82. Other occupied PIV slots remain a hard failure. */
387
389
  replaceOccupiedVaultSlot?: boolean
390
+ /** Required with `replaceOccupiedVaultSlot`: the result of `checkVaultCardFunds` for the card that will be
391
+ * tapped (a complete chain scan found no vault record that names it). Same meaning as in resetPivApplication. */
392
+ fundsClearance?: VaultResetClearance
393
+ /** Required with `replaceOccupiedVaultSlot` when there is no clearance: the owner's affirmation that any
394
+ * earlier funds this key opens are lost for good. Same meaning as in resetPivApplication. */
395
+ acknowledgeFundsLoss?: true
388
396
  /** XR-001: the admin-scoped wallet capability used to tag this run's
389
397
  * `ready` draft the instant it is written, so a later SecureStore-only
390
398
  * attacker cannot forge an equivalent one. */
391
399
  wallet: HmacCapableWallet
392
400
  adminOriginator: string
393
401
  }): Promise<VaultKeyRecord> {
402
+ await requireMnemonicWallet()
394
403
  const driver = getVaultDriver()
395
404
  if (!driver) throw new VaultError('driver-unavailable')
396
405
  const scopeToken = args.scopeToken ?? vaultStore.captureScopeToken()
@@ -400,6 +409,9 @@ export async function enrollKey(args: {
400
409
  'Confirm this YubiKey PIV application is factory-reset and dedicated to Vault'
401
410
  )
402
411
  }
412
+ // reset-new-phone: replacing the key in an occupied Vault slot destroys it, so it needs the same gate as a
413
+ // PIV reset. Before any card contact the serial is not known yet; it is checked again below.
414
+ if (args.replaceOccupiedVaultSlot === true) requireFundsGate(args, scopeToken, undefined)
403
415
 
404
416
  // The enrolled key list, read once from device-only secure storage before any user input or
405
417
  // key contact. Refused alongside pendingSerials below — across every chain
@@ -466,6 +478,7 @@ export async function enrollKey(args: {
466
478
  // The message IS the serial: the wizard resolves it to a nickname.
467
479
  throw new VaultError('key-already-enrolled', info.serial, undefined, { serial: info.serial })
468
480
  }
481
+ if (args.replaceOccupiedVaultSlot === true) requireFundsGate(args, scopeToken, info.serial)
469
482
  const quarantine = quarantines.find(item => item.serial === info.serial)
470
483
  if (quarantine) {
471
484
  throw new VaultEnrollmentPartialError(
@@ -759,6 +772,7 @@ export async function resumeEnrollmentDraft(args: {
759
772
  wallet: HmacCapableWallet
760
773
  adminOriginator: string
761
774
  }): Promise<VaultKeyRecord> {
775
+ await requireMnemonicWallet()
762
776
  if (!isVaultKeyRecord(args.entry.record)) {
763
777
  throw new VaultError('template-invalid', 'Invalid enrollment recovery handle')
764
778
  }
@@ -867,6 +881,9 @@ export async function adoptVaultKey(args: {
867
881
  getPin: () => Promise<string>
868
882
  nfcMessage?: string
869
883
  scopeToken?: VaultScopeToken
884
+ /** With the wallet authority the proof is written durably (and tagged).
885
+ * Without it, the proof lasts for this session only. */
886
+ authority?: VaultWalletAuthority
870
887
  }): Promise<VaultKeyRecord> {
871
888
  if (!isVaultKeyRecord(args.record)) throw new VaultError('template-invalid', 'Invalid recovered vault key record')
872
889
  const driver = getVaultDriver()
@@ -915,7 +932,29 @@ export async function adoptVaultKey(args: {
915
932
  { nfcMessage: args.nfcMessage }
916
933
  )
917
934
 
918
- await vaultStore.markKeyAdopted(args.record, scopeToken)
935
+ // The fresh tag covers the whole stored meta, so a durable write is only
936
+ // allowed over a meta whose own tag verifies (see markKeyAdopted). Any
937
+ // other meta gets a session proof: nothing is written and nothing is blessed.
938
+ const authority = args.authority
939
+ const scope = vaultStore.getScope()
940
+ let durable: { authority: VaultWalletAuthority; snapshot: VaultMeta } | undefined
941
+ if (authority && scope) {
942
+ const snapshot = await vaultStore.getMeta(scopeToken)
943
+ if (snapshot) {
944
+ const tag = await vaultStore.getMetaTag(scopeToken)
945
+ if (await verifyVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, snapshot, scope, tag)) {
946
+ durable = { authority, snapshot }
947
+ }
948
+ }
949
+ }
950
+ await vaultStore.markKeyAdopted(
951
+ args.record,
952
+ scopeToken,
953
+ durable && scope
954
+ ? next => computeVaultMetaAuthorityTag(durable.authority.wallet, durable.authority.adminOriginator, next, scope)
955
+ : undefined,
956
+ durable?.snapshot
957
+ )
919
958
  args.onPhase('done')
920
959
  return { ...args.record }
921
960
  }
@@ -990,7 +1029,9 @@ export interface VerifiedVaultRecoveryOutput {
990
1029
  * Reconstruct one current enrollment from authoritative spendable R1C outputs.
991
1030
  * The transfer layer owns pagination and lock verification; this function owns
992
1031
  * conflict detection and version selection. It never accepts a mixture of
993
- * enrollment ids or two different key sets at the same revision. A mixed
1032
+ * enrollment ids or two different key sets at the same revision, and it never
1033
+ * infers a pendingRemoval (callers pre-filter by lineage and variant, see
1034
+ * chainRecovery.ts). A mixed
994
1035
  * v6+v7 output set reduces to one VaultMeta the same way a same-version
995
1036
  * mixture does — version is not part of the conflict/version-selection
996
1037
  * identity here, only vaultId/createdAt/revision/keys are.
@@ -1013,29 +1054,9 @@ export function metaFromVerifiedOutputs(outputs: readonly VerifiedVaultRecoveryO
1013
1054
  throw new VaultError('template-invalid', 'Conflicting vault key sets share the latest revision')
1014
1055
  }
1015
1056
  const keys = current[0].instructions.keys.map(k => ({ ...k }))
1016
- const currentPubkeys = new Set(keys.map(k => k.pubkey))
1017
- const removed = new Map<string, { key: VaultKeyRecord; index: number }>()
1018
- for (const { instructions } of outputs) {
1019
- if (instructions.revision >= revision) continue
1020
- instructions.keys.forEach((key, index) => {
1021
- if (!currentPubkeys.has(key.pubkey)) removed.set(key.pubkey, { key: { ...key }, index })
1022
- })
1023
- }
1024
- if (removed.size > 1) {
1025
- throw new VaultError('template-invalid', 'Multiple incomplete key removals are present')
1026
- }
1027
-
1057
+ // A scan never infers a removal from older outputs (decoy-wedge): anyone can
1058
+ // plant a copy of an old record. A real removal lives in local meta only.
1028
1059
  const meta: VaultMeta = { v: 6, vaultId, revision, createdAt, keys }
1029
- const tombstone = [...removed.values()][0]
1030
- if (tombstone) {
1031
- meta.pendingRemoval = {
1032
- key: tombstone.key,
1033
- keyIndex: Math.min(tombstone.index, keys.length),
1034
- startedAt: Date.now(),
1035
- revision,
1036
- state: 'broadcast'
1037
- }
1038
- }
1039
1060
  if (!isVaultMeta(meta)) throw new VaultError('template-invalid', 'Recovered vault metadata is invalid')
1040
1061
  return meta
1041
1062
  }
@@ -1100,6 +1121,7 @@ export async function finalizeEnrollment(
1100
1121
  scopeToken: VaultScopeToken | undefined,
1101
1122
  authority: VaultWalletAuthority
1102
1123
  ): Promise<void> {
1124
+ await requireMnemonicWallet()
1103
1125
  if (records.length < VAULT_MIN_KEYS) {
1104
1126
  throw new VaultError('not-enough-keys', `A vault needs at least ${VAULT_MIN_KEYS} keys; ${records.length} given`)
1105
1127
  }
@@ -1155,8 +1177,12 @@ export async function finalizeEnrollment(
1155
1177
  }
1156
1178
  }
1157
1179
 
1158
- /** Append one key to an enrolled vault (spec §3.4 "Add key"). vaultStore
1159
- * enforces the duplicate-serial and VAULT_MAX_ACTIVE_KEYS rules. */
1180
+ /** Stage one key for an enrolled vault (spec §3.4 "Add key"; hardening:
1181
+ * add-key, late-key). The key goes into `meta.staged`; `keys` and `revision`
1182
+ * do not change, so no lock commits it. It becomes part of the key list only
1183
+ * when a re-lock signed by an existing key activates it (relockVault with
1184
+ * `activateStagedKey`, or activateStagedKeyWithoutOutputs when nothing is
1185
+ * funded). No tap is asked here. */
1160
1186
  export async function addVaultKey(
1161
1187
  record: VaultKeyRecord,
1162
1188
  scopeToken: VaultScopeToken | undefined,
@@ -1166,12 +1192,17 @@ export async function addVaultKey(
1166
1192
  const token = scopeToken ?? vaultStore.captureScopeToken()
1167
1193
  const existing = await vaultStore.getMeta(token)
1168
1194
  if (!existing) throw new VaultError('not-enrolled', 'Vault is not set up')
1169
- if (existing.keys.length >= VAULT_MAX_ACTIVE_KEYS) {
1170
- throw new VaultError('too-many-keys', `The vault already has ${VAULT_MAX_ACTIVE_KEYS} keys`)
1195
+ // Five keys plus the staged one is the most a vault holds (a lock commits
1196
+ // at most VAULT_MAX_KEYS).
1197
+ if (existing.keys.length + 1 > VAULT_MAX_ACTIVE_KEYS) {
1198
+ throw new VaultError('too-many-keys', `The vault already has ${existing.keys.length} keys`)
1171
1199
  }
1172
1200
  if (existing.keys.some(key => key.serial === record.serial || key.pubkey === record.pubkey)) {
1173
1201
  throw new VaultError('key-already-enrolled', record.serial, undefined, { serial: record.serial })
1174
1202
  }
1203
+ if (existing.staged) {
1204
+ throw new VaultError('relock-required', 'Finish adding the previous key first')
1205
+ }
1175
1206
  // XR-002: verify `existing`'s own tag BEFORE trusting it as the basis for
1176
1207
  // a freshly tagged `next` — see requireTaggedMeta's laundering caveat.
1177
1208
  await requireTaggedMeta(authority, existing, token)
@@ -1180,7 +1211,7 @@ export async function addVaultKey(
1180
1211
  await requireReadyEnrollmentDrafts([record], token, authority)
1181
1212
  const scope = vaultStore.getScope()
1182
1213
  if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
1183
- const meta = await vaultStore.addKey(
1214
+ const meta = await vaultStore.stageKey(
1184
1215
  record,
1185
1216
  token,
1186
1217
  next => computeVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, next, scope),
@@ -1196,6 +1227,30 @@ export async function addVaultKey(
1196
1227
  return meta
1197
1228
  }
1198
1229
 
1230
+ /** Drop the staged key (add-key, late-key). It only lowers authority, so no
1231
+ * tap is asked. The serial leaves the device-wide registry unless another
1232
+ * chain of this identity still holds it. */
1233
+ export async function discardStagedVaultKey(
1234
+ scopeToken: VaultScopeToken | undefined,
1235
+ authority: VaultWalletAuthority
1236
+ ): Promise<VaultMeta> {
1237
+ const token = scopeToken ?? vaultStore.captureScopeToken()
1238
+ const existing = await vaultStore.getMeta(token)
1239
+ if (!existing) throw new VaultError('not-enrolled', 'Vault is not set up')
1240
+ if (!existing.staged) throw new VaultError('not-enrolled', 'No key is waiting to be added')
1241
+ await requireTaggedMeta(authority, existing, token)
1242
+ const scope = vaultStore.getScope()
1243
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
1244
+ const serial = existing.staged.serial
1245
+ const meta = await vaultStore.discardStagedKey(
1246
+ token,
1247
+ next => computeVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, next, scope),
1248
+ existing
1249
+ )
1250
+ await forgetSerialsNoLongerEnrolledForIdentity([serial], () => vaultStore.enrolledSerialsAcrossChains(token))
1251
+ return meta
1252
+ }
1253
+
1199
1254
  /** Forget the key list. Only offered when the vault balance is zero (spec
1200
1255
  * §3.4); the keys themselves stay on the YubiKeys. */
1201
1256
  export async function disableVault(scopeToken?: VaultScopeToken): Promise<void> {