@bsv/expo-wallet-toolbox 0.24.3 → 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.
@@ -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> {