@bsv/expo-wallet-toolbox 0.24.2 → 0.25.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.
@@ -118,6 +118,35 @@ export interface Session {
118
118
  * instead would break the moment either platform grows a second transport.
119
119
  */
120
120
  os?: SessionOs
121
+ /**
122
+ * The network the payee's wallet is on: an AppChain name ('main', 'test',
123
+ * 'teratest', …), the same names a till's code carries. Undefined from a
124
+ * payee whose build predates the field — unknown, not a mismatch.
125
+ *
126
+ * A string, not AppChain, on purpose: a name this build does not know (a
127
+ * newer network) is kept, so the payer still sees a mismatch rather than
128
+ * paying into it. Without this, a testnet code decodes cleanly on a mainnet
129
+ * phone and the payment fails with nothing on either screen to say why.
130
+ * Read it through `sessionNetworkMismatch`.
131
+ */
132
+ network?: string
133
+ }
134
+
135
+ /** A network name on the wire: short, lowercase, so a QR cannot carry copy into the payer's screen. */
136
+ const NETWORK_RE = /^[a-z0-9-]{1,32}$/
137
+
138
+ /**
139
+ * Whether a scanned session is for another network than this wallet's.
140
+ * Null when they match, or when the payee did not say (an older build): an
141
+ * absent field is never read as a mismatch, or every pre-field payee would
142
+ * be refused.
143
+ */
144
+ export function sessionNetworkMismatch(
145
+ session: Pick<Session, 'network'>,
146
+ mine: string
147
+ ): { theirs: string; mine: string } | null {
148
+ if (session.network === undefined || session.network === mine) return null
149
+ return { theirs: session.network, mine }
121
150
  }
122
151
 
123
152
  export function mintSession(args: {
@@ -141,8 +170,11 @@ export function mintSession(args: {
141
170
  */
142
171
  hints?: number
143
172
  os?: SessionOs
173
+ /** The AppChain this payee's wallet is on. Every minting screen should pass it; see Session.network. */
174
+ network?: string
144
175
  }): Session {
145
176
  if (args.identityKey.length !== 66) throw new CodecError('identityKey must be 66 hex chars')
177
+ if (args.network !== undefined && !NETWORK_RE.test(args.network)) throw new CodecError('bad network')
146
178
  // Validated at the mint too, not only at decode: an invalid figure minted
147
179
  // here would render on the payee's own screen and be echoed to the payer as
148
180
  // an authentic request before any decoder ever saw it.
@@ -193,7 +225,8 @@ export function mintSession(args: {
193
225
  ...(args.asset === undefined ? {} : { asset: assetOf(args.asset) }),
194
226
  derivationPrefix: args.derivationPrefix,
195
227
  derivationSuffix: args.derivationSuffix,
196
- ...(args.os === undefined ? {} : { os: args.os })
228
+ ...(args.os === undefined ? {} : { os: args.os }),
229
+ ...(args.network === undefined ? {} : { network: args.network })
197
230
  }
198
231
  }
199
232
 
@@ -278,7 +311,10 @@ export function encodeSession(s: Session): string {
278
311
  }
279
312
  }),
280
313
  p: s.derivationPrefix,
281
- x: s.derivationSuffix
314
+ x: s.derivationSuffix,
315
+ // Additive, so no version bump: a v2 decoder that predates `n` ignores
316
+ // unknown keys, and one that knows it reads an absent `n` as unknown.
317
+ ...(s.network === undefined ? {} : { n: s.network })
282
318
  })
283
319
  return 'bsvpay1:' + toB64url(new TextEncoder().encode(body))
284
320
  }
@@ -292,7 +328,7 @@ export function decodeSession(text: string): Session {
292
328
  if (e instanceof CodecError) throw e
293
329
  throw new CodecError('malformed session payload')
294
330
  }
295
- const { v, c, s, k, i, a, p, x, o, t } = parsed as Record<string, unknown>
331
+ const { v, c, s, k, i, a, p, x, o, t, n } = parsed as Record<string, unknown>
296
332
  if (v !== SESSION_VERSION) throw new CodecError(`unsupported session version ${String(v)}`)
297
333
  if (typeof i !== 'string' || i.length !== 66) throw new CodecError('bad identityKey')
298
334
  // An ABSENT `a` is an OPEN request: the payer chooses.
@@ -331,6 +367,12 @@ export function decodeSession(text: string): Session {
331
367
  if (psk.length !== 32) throw new CodecError('bad psk length')
332
368
  // Tolerant on purpose: 'o' is advisory, from possibly-newer builds.
333
369
  const os: SessionOs | undefined = o === 'i' ? 'ios' : o === 'a' ? 'android' : undefined
370
+ // Not tolerant like 'o': a malformed name refuses the whole code, never
371
+ // drops to "unknown" — that would let the payment through to the silent
372
+ // failure this field exists to stop. Only a peer that breaks the codec
373
+ // writes one. An unfamiliar but well-formed name is kept, and flagged as a
374
+ // mismatch.
375
+ if (n !== undefined && (typeof n !== 'string' || !NETWORK_RE.test(n))) throw new CodecError('bad network')
334
376
  let asset: SessionAsset | undefined
335
377
  if (t !== undefined) {
336
378
  if (typeof t !== 'object' || t === null) throw new CodecError('bad asset block')
@@ -358,7 +400,8 @@ export function decodeSession(text: string): Session {
358
400
  ...(asset === undefined ? {} : { asset }),
359
401
  derivationPrefix: p,
360
402
  derivationSuffix: x,
361
- ...(os === undefined ? {} : { os })
403
+ ...(os === undefined ? {} : { os }),
404
+ ...(n === undefined ? {} : { network: n as string })
362
405
  }
363
406
  }
364
407
 
@@ -10,7 +10,7 @@
10
10
  * If you find yourself wanting to add a function here, add it to the caller
11
11
  * instead.
12
12
  */
13
- export { decodeSession, encodeSession, mintSession, type Session } from '../../localpay/session'
13
+ export { decodeSession, encodeSession, mintSession, sessionNetworkMismatch, type Session } from '../../localpay/session'
14
14
  export {
15
15
  FRAME_BLOCK_BYTES,
16
16
  SEAL_VERSION,
@@ -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.
@@ -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> {