@bsv/expo-wallet-toolbox 0.3.1 → 0.5.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.
Files changed (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,312 +1,973 @@
1
1
  /**
2
- * VaultKeyService — enrollment, recovery, and teardown of the vault key.
2
+ * VaultKeyService — enrolling YubiKeys into the vault's key list, and tearing
3
+ * the list down.
3
4
  *
4
- * The vault key V is derived from the SAME mnemonic as the main wallet,
5
- * domain-separated by a non-empty vault passphrase (BIP39 toSeed). The user
6
- * therefore backs up ONE phrase, not two. See vaultDerivation.ts.
5
+ * Each YubiKey IS a vault key (spec D2/D3): PIV slot 0x82 holds a P-256 key
6
+ * generated ON the card, whose compressed public key is all the phone ever
7
+ * records. There is no seed, no seal, no passphrase and no recovery phrase
8
+ * anywhere in this design. Recovery combines any enrolled YubiKey with the
9
+ * self-describing metadata authenticated against a spendable R1C output.
10
+ * Nothing here derives, wraps or zeroizes anything.
7
11
  *
8
- * The YubiKey is now an UNWRAP ORACLE, not a signing device: its PIV slot
9
- * 0x82 holds a P-256 key used only for on-token ECDH (see sealing.ts).
10
- * Enrollment's job is to derive the 64-byte vault seed, seal it to that
11
- * card's public key, and store the result — a SealedBlob plus a bare
12
- * `nextKeyIndex` counter (vaultStore's v4 meta). Nothing about the vault is
13
- * ever public at rest: there is no xpub, no r1PublicKey, nothing that lets
14
- * anyone reach a vault address without either the physical card or the
15
- * mnemonic + passphrase.
12
+ * enrollKey runs ONE card session for ONE key and returns a public record
13
+ * without persisting it; the wizard collects 2..5 such records and commits
14
+ * them atomically with finalizeEnrollment (spec §3.3: no local Vault authority
15
+ * is stored until Finish). addVaultKey appends one record to an enrolled vault (§3.4).
16
16
  *
17
- * Because deposit addresses are BIP32 children of the PRIVATE vault HD node
18
- * — there is no public xpub to derive them from anymore — a tap is now
19
- * needed to hand out a fresh deposit address too. Deposits and withdrawals
20
- * both go through the same unseal; neither is free of the YubiKey. (An
21
- * earlier design cached 64 key hashes ahead of time so deposits never
22
- * touched the card; that cache and its refill ceremony are gone along with
23
- * the xpub that made it possible.)
17
+ * Enrollment never overwrites an occupied slot. A signing probe detects a bare
18
+ * key even on iOS, where YubiKit 4.4 cannot read retired-slot metadata. Recovery
19
+ * uses adoptVaultKey: it proves possession with a fresh challenge and compares
20
+ * the resulting signature to metadata authenticated against a real R1C lock.
24
21
  *
25
- * Recovery paths, and there are exactly two:
26
- * 1. YubiKey unseal (the ceremony's on-token ECDH) — recovers the seed
27
- * directly, nothing to type
28
- * 2. main mnemonic + passphrase — deriveVaultSeed/deriveVaultHD, offline
29
- * There is no third path.
30
- *
31
- * SECURITY: never log V, the seed, the mnemonic, or the passphrase.
22
+ * SECURITY: never log the PIN. Public keys and serials are public data.
32
23
  */
33
- import { HD } from '@bsv/sdk'
34
24
  import { getVaultDriver } from './driver'
25
+ import { compressPubkey, type VaultInstructionsV6 } from './r1comb'
26
+ import { randomBytes } from './random'
35
27
  import { withKeySession } from './session'
36
- import { vaultStore, VaultMetaV4 } from './vaultStore'
37
- import { VaultError, SealedBlob } from './types'
38
- import { deriveVaultSeed, deriveVaultHD, randomDepositStartIndex } from './vaultDerivation'
39
- import { checkVaultPassphrase } from './vaultPassphrase'
40
- import { sealVaultKey } from './sealing'
41
-
42
- /** An enrollment that has touched the key but not yet disk. */
43
- export interface PendingEnrollment {
44
- meta: VaultMetaV4
45
- seal: SealedBlob
46
- }
28
+ import { VaultError } from './types'
29
+ import {
30
+ isVaultKeyRecord,
31
+ isVaultMeta,
32
+ isVaultSerial,
33
+ vaultStore,
34
+ VaultEnrollmentDraftEntry,
35
+ VaultKeyRecord,
36
+ VaultMeta,
37
+ VaultScopeToken
38
+ } from './vaultStore'
39
+ import { Utils } from '@bsv/sdk'
40
+ import { p256 } from '@noble/curves/nist.js'
47
41
 
48
42
  export const VAULT_SLOT = 0x82
43
+
44
+ /** Spec D3: at least two keys, so one lost YubiKey does not lose the money;
45
+ * at most five (R1C_MAX_KEYS — the lock carries one commitment per key). */
46
+ export const VAULT_MIN_KEYS = 2
47
+ export const VAULT_MAX_KEYS = 5
48
+
49
49
  const DEFAULT_PIV_PIN = '123456'
50
+ const DEFAULT_PIV_PUK = '12345678'
51
+ const PIV_CODE = /^[0-9]{6,8}$/
52
+
53
+ export type EnrollPhase =
54
+ | 'connecting'
55
+ | 'pin-check'
56
+ | 'checking-slot'
57
+ | 'personalizing'
58
+ | 'generating'
59
+ | 'challenging'
60
+ | 'done'
61
+ export type AdoptPhase = 'connecting' | 'pin-check' | 'challenging' | 'done'
62
+
63
+ /** Enrollment requires both native, offline manufacturer attestation and a
64
+ * fresh possession challenge after the management key is protected. */
65
+ export const VAULT_ENROLLMENT_ASSURANCE = 'manufacturer-attested-possession-challenge' as const
66
+
67
+ export type EnrollmentPartialStage =
68
+ | 'pin-change-uncertain'
69
+ | 'pin-changed'
70
+ | 'puk-change-uncertain'
71
+ | 'puk-changed'
72
+ | 'generation-uncertain'
73
+ | 'key-generated'
74
+ | 'key-protected'
75
+
76
+ /**
77
+ * Personalization mutated (or may have mutated) the token before a later step
78
+ * failed. Confirmed stages let the wizard retain the user's chosen replacement
79
+ * credentials for an explicit retry. An `*-uncertain` stage must never cause
80
+ * the UI to assume which credential is current or spend retries testing that
81
+ * assumption. Secrets are never attached to the error. A generated record is
82
+ * never enrolled implicitly.
83
+ */
84
+ export class VaultEnrollmentPartialError extends VaultError {
85
+ readonly stage: EnrollmentPartialStage
86
+ readonly record?: VaultKeyRecord
87
+ readonly recoverySaved: boolean
88
+
89
+ constructor(stage: EnrollmentPartialStage, cause: unknown, record?: VaultKeyRecord, recoverySaved = false) {
90
+ super('enrollment-partial', 'YubiKey personalization did not complete', undefined, {
91
+ stage,
92
+ recoverySaved: recoverySaved ? 1 : 0,
93
+ ...(record ? { serial: record.serial, pubkey: record.pubkey } : {})
94
+ })
95
+ this.name = 'VaultEnrollmentPartialError'
96
+ this.stage = stage
97
+ this.record = record
98
+ this.recoverySaved = recoverySaved
99
+ ;(this as Error & { cause?: unknown }).cause = cause
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Does this firmware answer GET METADATA (PIV INS 0xF7)?
105
+ *
106
+ * That command is the only non-inferential way to ask whether a PIV slot holds
107
+ * a key, and it landed in firmware 5.3. Below it every remaining answer is
108
+ * inferred from a status word, and 5.7.4 proved those move: an empty retired
109
+ * slot that once answered ATTEST with 0x6A88 now answers 0x6A80. Enrollment
110
+ * generates a key it must afterwards be able to prove was the only one, so it
111
+ * refuses to guess rather than silently overwriting something.
112
+ *
113
+ * `firmwareVersion` is "major.minor.micro", straight from getKeyInfo.
114
+ */
115
+ function supportsSlotMetadata(firmwareVersion: string): boolean {
116
+ const [major, minor] = firmwareVersion.split('.').map(part => Number.parseInt(part, 10))
117
+ if (!Number.isFinite(major) || !Number.isFinite(minor)) return false
118
+ return major > 5 || (major === 5 && minor >= 3)
119
+ }
120
+
121
+ function requirePivCode(value: string, label: 'PIN' | 'PUK'): void {
122
+ if (!PIV_CODE.test(value)) {
123
+ throw new VaultError('template-invalid', `PIV ${label} must be 6 to 8 ASCII digits`)
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Attach the tapped serial to an error leaving the card session.
129
+ *
130
+ * The UI's reset offer must bind to the exact key that failed, and a separate
131
+ * reset tap has no other way to learn which one that was. Native-origin errors
132
+ * cannot carry it themselves: vaultErrorFromNative parses only the code, the
133
+ * message and `retries=`, never `details`.
134
+ *
135
+ * Only a plain VaultError is rebuilt. Anything else passes through untouched:
136
+ * a foreign throwable keeps its identity, and a VaultError SUBCLASS keeps the
137
+ * fields a plain VaultError cannot hold — VaultEnrollmentPartialError's
138
+ * `stage`, `record` and `recoverySaved` are what the quarantine and draft
139
+ * recovery machinery reads, so rebuilding one would silently disarm it. An
140
+ * existing `details.serial` is never overwritten.
141
+ */
142
+ function withSerial(error: unknown, serial: string): unknown {
143
+ if (!(error instanceof VaultError)) return error
144
+ if (error.constructor !== VaultError) return error
145
+ if (error.details?.serial !== undefined) return error
146
+ return new VaultError(error.code, error.message, error.retriesLeft, { ...error.details, serial })
147
+ }
148
+
149
+ /**
150
+ * Name the tapped card on a partial-enrollment failure that carries no record.
151
+ *
152
+ * The counterpart to `withSerial` for the one class it deliberately refuses to
153
+ * touch. A partial only gets `details.serial` from its `record`, and every
154
+ * stage BEFORE key generation has no record — which is exactly the set that
155
+ * persists a quarantine. Unnamed, the wizard's `resetSerial` stays undefined
156
+ * and no reset is offered; but a quarantined serial short-circuits every later
157
+ * enrollment tap, and a reset is the only thing that clears one. So without
158
+ * this the card is both unenrollable and unresettable in-app, under copy
159
+ * telling the user to reset it.
160
+ *
161
+ * `pin-change-uncertain` is named too, deliberately, even though it is the one
162
+ * stage where the card may still be factory. The quarantine is written BEFORE
163
+ * the changePin APDU, so nothing may have happened — but it is written all the
164
+ * same, and nothing else erases it. Withholding the offer there would brick
165
+ * exactly the card that was never modified. Resetting a still-factory PIV
166
+ * application costs nothing the user has not already agreed to: preflight
167
+ * refused every occupied user slot before this point, so there is nothing else
168
+ * on it. The wizard keeps the hedged `vault_enrollment_state_uncertain` copy
169
+ * for this stage rather than the reset-required one, so the offer is made
170
+ * without claiming the card was changed.
171
+ *
172
+ * Mutated in place rather than rebuilt: `details` is a plain field, and
173
+ * constructing a fresh VaultEnrollmentPartialError would have to re-thread
174
+ * `stage`, `record`, `recoverySaved` and `cause` — the failure mode withSerial
175
+ * exists to avoid. Applied once around the whole card session so a throw site
176
+ * added later cannot forget it. An existing `details.serial` is never
177
+ * overwritten.
178
+ */
179
+ function withPartialSerial(error: unknown, serial: string | undefined): unknown {
180
+ if (serial === undefined) return error
181
+ if (!(error instanceof VaultEnrollmentPartialError)) return error
182
+ if (error.details?.serial !== undefined) return error
183
+ error.details = { ...error.details, serial }
184
+ return error
185
+ }
186
+
187
+ function validatePukChange(change: { oldPuk: string; newPuk: string }, pin: string): void {
188
+ requirePivCode(change.oldPuk, 'PUK')
189
+ requirePivCode(change.newPuk, 'PUK')
190
+ if (change.newPuk === DEFAULT_PIV_PUK || change.newPuk === pin || change.newPuk === change.oldPuk) {
191
+ throw new VaultError('template-invalid', 'Choose a new non-default PUK distinct from the PIN and old PUK')
192
+ }
193
+ }
194
+
195
+ function enrollmentNickname(value: unknown, ordinal: number): string {
196
+ if (value !== undefined && typeof value !== 'string') {
197
+ throw new VaultError('template-invalid', 'Invalid vault key nickname')
198
+ }
199
+ const clean = typeof value === 'string' ? value.trim() : ''
200
+ const nickname = clean || `Key ${ordinal}`
201
+ if (nickname.length > 64 || /[\u0000-\u001f\u007f]/.test(nickname)) {
202
+ throw new VaultError('template-invalid', 'Invalid vault key nickname')
203
+ }
204
+ return nickname
205
+ }
206
+
207
+ function signatureProvesKey(pubkey: string, digest: Uint8Array, signature: string): boolean {
208
+ try {
209
+ const der = p256.Signature.fromBytes(Uint8Array.from(Utils.toArray(signature, 'hex')), 'der')
210
+ return p256.verify(der.toBytes(), digest, Uint8Array.from(Utils.toArray(pubkey, 'hex')), {
211
+ prehash: false,
212
+ lowS: false
213
+ })
214
+ } catch {
215
+ return false
216
+ }
217
+ }
218
+
219
+ function isDefiniteCredentialRejection(error: unknown): boolean {
220
+ return (
221
+ error instanceof VaultError &&
222
+ (error.code === 'pin-invalid' ||
223
+ error.code === 'pin-locked' ||
224
+ error.code === 'puk-invalid' ||
225
+ error.code === 'puk-locked' ||
226
+ error.code === 'template-invalid')
227
+ )
228
+ }
229
+
230
+ function requireVerifiedPin(result: { ok: boolean; retriesLeft: number }, detail = 'PIN not accepted'): void {
231
+ if (result.ok) return
232
+ if (result.retriesLeft <= 0) throw new VaultError('pin-locked', 'PIN is blocked', 0)
233
+ throw new VaultError('pin-invalid', detail, result.retriesLeft)
234
+ }
235
+
236
+ /**
237
+ * Refuse to generate over an occupied Vault slot.
238
+ *
239
+ * Asks the card through `isVaultSlotOccupied`, which both natives answer with
240
+ * GET METADATA. This replaced a random-digest `signEcdsa` probe that treated a
241
+ * `no-key` rejection as proof of emptiness — and `no-key` is derived from status
242
+ * word 0x6A88, which firmware 5.7.4+ no longer returns for an empty retired
243
+ * slot (it answers 0x6A80). The probe was also fail-OPEN in one direction:
244
+ * native reports `no-key` when the card has simply LEFT THE FIELD, which the
245
+ * old code read as "the slot is empty, generate away".
246
+ *
247
+ * The PIN is no longer needed here — occupancy needs no VERIFY, and enrollKey
248
+ * has already verified the PIN by this point.
249
+ */
250
+ async function requireEmptyVaultSlot(serial: string, allowReplacement: boolean): Promise<void> {
251
+ // Explicit consent to destroy whatever occupies slot 0x82. Asking anyway only
252
+ // created a way for an ambiguous answer to block a replacement the user had
253
+ // already agreed to.
254
+ if (allowReplacement) return
255
+ const driver = getVaultDriver()
256
+ if (!driver) throw new VaultError('driver-unavailable')
257
+ // A readable certificate is occupancy even when nothing signs: the public key
258
+ // it exposes is what recovery binds to. GET METADATA answers about the KEY, so
259
+ // it would call such a slot empty — this check is not redundant with the one
260
+ // below, and only ever adds occupancy.
261
+ if (await driver.readVaultPublicKey(serial)) {
262
+ throw withSerial(new VaultError('slot-occupied', 'Vault slot already contains a key'), serial)
263
+ }
264
+ const { occupied } = await driver.isVaultSlotOccupied(serial)
265
+ if (occupied) {
266
+ throw withSerial(new VaultError('slot-occupied', 'Vault slot is not provably empty'), serial)
267
+ }
268
+ }
50
269
 
51
- export async function enrollVault(args: {
52
- nickname: string
53
- /** The MAIN wallet mnemonic. Wallets restored from backup shares do not have
54
- * one and cannot enroll — callers must gate on this before calling. */
55
- mnemonic: string
56
- /** Non-empty vault passphrase. Must pass checkVaultPassphrase. */
57
- passphrase: string
58
- /**
59
- * Enroll against the key ALREADY in the PIV slot instead of refusing it.
60
- *
61
- * This is how one YubiKey serves the same vault on several devices. The slot
62
- * key is the ECDH unwrap oracle (see this file's header), i.e. the wrap
63
- * TARGET a seal is built against — so adopting it seals THIS device's own
64
- * copy of the vault seed to the card the user already carries, and the one
65
- * physical tap then opens either device's blob.
66
- *
67
- * Generating instead is the destructive move: it would overwrite the slot's
68
- * private key and strand the FIRST device's seal, which was wrapped to the
69
- * key being replaced — that device would be left with a blob no tap can
70
- * open, recoverable only via mnemonic + passphrase. Adoption generates
71
- * nothing.
72
- *
73
- * The seed is re-derived here, never copied between devices, so both reach
74
- * the SAME vault key the same two ways: the physical card (its ECDH unwraps
75
- * whichever seal that device wrote) or the mnemonic + passphrase
76
- * (deriveVaultSeed, offline). Every output the first device created stays
77
- * spendable.
78
- *
79
- * Only ever set from an explicit user choice: 0x82 is a *retired* PIV slot,
80
- * so the key sitting there may belong to something else entirely (an
81
- * age-plugin-yubikey identity, say), and adopting it silently would quietly
82
- * couple that key to the vault. An empty slot with this set generates
83
- * normally — the flag permits adoption, it does not require it.
84
- */
85
- adoptExisting?: boolean
86
- onPhase: (p: 'connecting' | 'pin-check' | 'generating' | 'adopting' | 'done') => void
270
+ /**
271
+ * Enrol ONE YubiKey: one card session (one NFC tap), one fresh key, one
272
+ * public record back. Persists only scoped, non-authoritative recovery state
273
+ * until the caller commits the resulting record to Vault metadata.
274
+ *
275
+ * `pendingSerials` are the serials enrolled earlier in this wizard run (the
276
+ * wizard also passes meta.keys' serials, and may keep doing so). The
277
+ * serials already in meta.keys are read HERE, from the store, so the refusal
278
+ * does not depend on the caller's copy of the key list being loaded yet: the
279
+ * service is the thing that stands between an enrolled card and
280
+ * generateVaultKey. The check runs FIRST inside the session, before the PIN
281
+ * is spent and, above all, before generateVaultKey replaces whatever the
282
+ * slot holds: re-tapping an enrolled card must cost nothing (spec §3.3
283
+ * step 2).
284
+ *
285
+ * All user input (PIN, replacement PIN) is gathered BEFORE the tap: on NFC the
286
+ * scan sheet is a system modal that covers the app.
287
+ */
288
+ export async function enrollKey(args: {
289
+ /** Serials already enrolled OR pending in this wizard run. */
290
+ pendingSerials: string[]
291
+ nickname?: string
292
+ onPhase: (p: EnrollPhase) => void
87
293
  getPin: () => Promise<string>
88
294
  /** Called when the key still has the factory-default PIV PIN; must return a
89
- * new PIN the user chose. If omitted, enrollment proceeds on the default PIN
90
- * (dev/test convenience). */
295
+ * new PIN the user chose. Enrollment rejects omission. */
91
296
  requestPinChange?: (retries: number) => Promise<{ oldPin: string; newPin: string }>
92
- }): Promise<{ pending: PendingEnrollment }> {
297
+ /** Always rotate the PUK during enrollment. Input is collected before NFC. */
298
+ requestPukChange: () => Promise<{ oldPuk: string; newPuk: string }>
299
+ /** Explicit acknowledgement that this token's whole PIV application is
300
+ * dedicated/factory-reset. Enrollment rotates global PIV credentials, which
301
+ * affect every slot, so this is enforced again below the UI boundary. */
302
+ acknowledgeDedicatedPivApplication: true
303
+ /** Localised iOS NFC alert text for this tap (spec §4.2 step 6, enrollment
304
+ * wording). Additive to the interface contract; Android ignores it and an
305
+ * omitted value selects the native default wording. */
306
+ nfcMessage?: string
307
+ /** Bind a multi-key wizard to the wallet+chain scope it opened under. */
308
+ scopeToken?: VaultScopeToken
309
+ /** Explicit consent to destroy and replace an existing key in Vault's fixed
310
+ * slot 0x82. Other occupied PIV slots remain a hard failure. */
311
+ replaceOccupiedVaultSlot?: boolean
312
+ }): Promise<VaultKeyRecord> {
93
313
  const driver = getVaultDriver()
94
314
  if (!driver) throw new VaultError('driver-unavailable')
315
+ const scopeToken = args.scopeToken ?? vaultStore.captureScopeToken()
316
+ if (args.acknowledgeDedicatedPivApplication !== true) {
317
+ throw new VaultError(
318
+ 'template-invalid',
319
+ 'Confirm this YubiKey PIV application is factory-reset and dedicated to Vault'
320
+ )
321
+ }
95
322
 
96
- // Validate the passphrase BEFORE any key contact, so a rejected passphrase
97
- // never costs the user an NFC tap. An empty one would make V identical to
98
- // the main wallet's master key.
99
- const policy = checkVaultPassphrase(args.passphrase)
100
- if (!policy.ok) throw new VaultError('bad-passphrase', policy.reason)
323
+ // The enrolled key list, read once from device-only secure storage before any user input or
324
+ // key contact. Refused alongside pendingSerials below — meta ∪ pending —
325
+ // so an enrolled card is refused even when the caller's own copy of meta
326
+ // has not loaded (the wizard's key list arrives asynchronously).
327
+ const meta = await vaultStore.getMeta(scopeToken)
328
+ const quarantines = await vaultStore.getEnrollmentQuarantines(scopeToken)
329
+ const refused = new Set<string>([...(meta?.keys.map(k => k.serial) ?? []), ...args.pendingSerials])
330
+ const k = args.pendingSerials.length + 1
331
+ const nickname = enrollmentNickname(args.nickname, k)
332
+ const enrolledAt = Date.now()
333
+ if (!Number.isSafeInteger(enrolledAt) || enrolledAt <= 0) {
334
+ throw new VaultError('template-invalid', 'Invalid enrollment time')
335
+ }
101
336
 
102
337
  // ── ALL user input up front, BEFORE any key contact ──
103
- // On NFC the scan sheet is a modal that covers the app, so every prompt (the
104
- // PIN, and a replacement PIN if the key is on the factory default) must be
105
- // gathered before the tap; the whole enrollment then runs in one tap.
106
338
  args.onPhase('pin-check')
107
339
  const pin0 = await args.getPin()
340
+ requirePivCode(pin0, 'PIN')
108
341
  let pin = pin0
109
342
  let pinChange: { oldPin: string; newPin: string } | null = null
110
- if (pin0 === DEFAULT_PIV_PIN && args.requestPinChange) {
343
+ if (pin0 === DEFAULT_PIV_PIN) {
344
+ if (!args.requestPinChange) {
345
+ throw new VaultError('template-invalid', 'The factory PIV PIN must be changed before enrollment')
346
+ }
111
347
  // Factory-default detection is exactly "the PIN the user entered is the
112
- // default" — no side probe against '123456' (fix #5).
348
+ // default" — no side probe against '123456' that would burn a retry.
113
349
  pinChange = await args.requestPinChange(3)
350
+ requirePivCode(pinChange.oldPin, 'PIN')
351
+ requirePivCode(pinChange.newPin, 'PIN')
352
+ if (pinChange.oldPin !== pin0 || pinChange.newPin === DEFAULT_PIV_PIN || pinChange.newPin === pinChange.oldPin) {
353
+ throw new VaultError('template-invalid', 'Choose a new non-default PIN and provide the current PIN exactly')
354
+ }
114
355
  pin = pinChange.newPin
115
356
  }
357
+ const pukChange = await args.requestPukChange()
358
+ validatePukChange(pukChange, pin)
359
+ // Do not even open discovery if the wizard outlived its wallet or chain.
360
+ vaultStore.assertScopeToken(scopeToken)
116
361
 
117
362
  // ── Token phase: one session / one NFC tap ──
118
- const { info, publicKey, adopted } = await withKeySession(
363
+ /** The serial this session's card reported, for the `withPartialSerial` tag
364
+ * on the way out. Written once, from the card, before anything is presented
365
+ * to it — so a partial raised anywhere below can name the card it belongs to. */
366
+ let tappedSerial: string | undefined
367
+ const record = await withKeySession(
119
368
  driver,
120
369
  async () => {
370
+ vaultStore.assertScopeToken(scopeToken)
121
371
  const info = await driver.getKeyInfo()
372
+ if (!isVaultSerial(info.serial)) {
373
+ throw new VaultError('template-invalid', 'YubiKey returned an invalid serial number')
374
+ }
375
+ tappedSerial = info.serial
376
+ if (refused.has(info.serial)) {
377
+ // The message IS the serial: the wizard resolves it to a nickname.
378
+ throw new VaultError('key-already-enrolled', info.serial, undefined, { serial: info.serial })
379
+ }
380
+ const quarantine = quarantines.find(item => item.serial === info.serial)
381
+ if (quarantine) {
382
+ throw new VaultEnrollmentPartialError(
383
+ quarantine.stage,
384
+ new VaultError(
385
+ 'template-invalid',
386
+ 'This token has an unfinished global PIV credential change; reset or recover its dedicated PIV application'
387
+ ),
388
+ undefined,
389
+ true
390
+ )
391
+ }
122
392
  // A blocked PIN can't be enrolled — surface it before burning anything.
123
- if (info.pinRetries === 0) throw new VaultError('pin-locked', 'PIN is blocked')
124
- // Never silently overwrite an occupied slot: generating into a used PIV
125
- // slot destroys the existing key, and retired slots 82-95 are what
126
- // age-plugin-yubikey uses. Refuse and let the user decide — the wizard
127
- // turns this refusal into the adopt-or-cancel choice that comes back as
128
- // `adoptExisting`.
129
- const occupant = await driver.readVaultPublicKey(VAULT_SLOT)
130
- if (occupant && !args.adoptExisting) {
131
- throw new VaultError('slot-occupied', `PIV slot ${VAULT_SLOT.toString(16)} already holds a key`)
393
+ if (info.pinRetries === 0) throw withSerial(new VaultError('pin-locked', 'PIN is blocked'), info.serial)
394
+ // Refuse a key too old to prove its slots empty, with its own message
395
+ // rather than the slot-occupied one a failed occupancy read would give.
396
+ if (!supportsSlotMetadata(info.firmwareVersion)) {
397
+ throw withSerial(
398
+ new VaultError('unsupported-platform', 'This YubiKey needs firmware 5.3 or later'),
399
+ info.serial
400
+ )
401
+ }
402
+ // PIN/PUK and management credentials are global to the whole PIV
403
+ // application, not slot 0x82. Native must cryptographically verify the
404
+ // factory F9 chain, authenticate the default management key, and reject
405
+ // every occupied user slot it can reliably inspect before mutation. The
406
+ // explicit dedicated-token acknowledgement still matters because a
407
+ // genuine factory-attested token can contain unrelated user credentials.
408
+ //
409
+ // This runs BEFORE verifyPin deliberately. It is read-only, issues no
410
+ // VERIFY on either platform, and refuses every personalised PIV
411
+ // application — so a used token is identified without spending one of
412
+ // three PIN retries on the factory PIN the UI supplies on the user's
413
+ // behalf.
414
+ let preflight: Awaited<ReturnType<typeof driver.preflightDedicatedPiv>>
415
+ try {
416
+ preflight = await driver.preflightDedicatedPiv(info.serial, args.replaceOccupiedVaultSlot === true)
417
+ } catch (e) {
418
+ throw withSerial(e, info.serial)
419
+ }
420
+ if (
421
+ preflight.ok !== true ||
422
+ preflight.manufacturerAttestation !== 'verified' ||
423
+ (preflight.inspection !== 'metadata' && preflight.inspection !== 'attestation')
424
+ ) {
425
+ throw withSerial(
426
+ new VaultError('attestation-invalid', 'Native manufacturer attestation was not verified'),
427
+ info.serial
428
+ )
429
+ }
430
+ // Verify the entered PIN before doing any card mutation. The signing
431
+ // probe below is the iOS-safe occupancy check for retired slot 0x82.
432
+ try {
433
+ const verified = await driver.verifyPin(info.serial, pin0)
434
+ requireVerifiedPin(verified)
435
+ } catch (e) {
436
+ throw withSerial(e, info.serial)
437
+ }
438
+ args.onPhase('checking-slot')
439
+ await requireEmptyVaultSlot(info.serial, args.replaceOccupiedVaultSlot === true)
440
+ // Everything above is read-only. This is the last guard before the
441
+ // first irreversible token mutation.
442
+ vaultStore.assertScopeToken(scopeToken)
443
+ args.onPhase('personalizing')
444
+ if (pinChange) {
445
+ // Write intent before the irreversible APDU. If the process dies while
446
+ // changePin is executing, the next launch must quarantine this serial
447
+ // instead of guessing which PIN is current and spending retries.
448
+ await vaultStore.preserveEnrollmentQuarantine(info.serial, 'pin-change-uncertain', scopeToken)
449
+ vaultStore.assertScopeToken(scopeToken)
450
+ try {
451
+ await driver.changePin(info.serial, pinChange.oldPin, pinChange.newPin)
452
+ } catch (e) {
453
+ if (isDefiniteCredentialRejection(e)) {
454
+ try {
455
+ await vaultStore.transitionEnrollmentQuarantine(info.serial, 'pin-change-uncertain', null, scopeToken)
456
+ } catch (storageError) {
457
+ throw new VaultEnrollmentPartialError('pin-change-uncertain', storageError, undefined, true)
458
+ }
459
+ // Symmetric with the changePuk twin below: a definite credential
460
+ // rejection leaves the card unchanged, so it reaches the UI as a
461
+ // plain pin-invalid/pin-locked and must name the key it came from.
462
+ throw withSerial(e, info.serial)
463
+ }
464
+ throw new VaultEnrollmentPartialError('pin-change-uncertain', e, undefined, true)
465
+ }
466
+ try {
467
+ await vaultStore.transitionEnrollmentQuarantine(
468
+ info.serial,
469
+ 'pin-change-uncertain',
470
+ 'pin-changed',
471
+ scopeToken
472
+ )
473
+ } catch (e) {
474
+ throw new VaultEnrollmentPartialError('pin-changed', e, undefined, true)
475
+ }
476
+ try {
477
+ const changed = await driver.verifyPin(info.serial, pin)
478
+ requireVerifiedPin(changed, 'New PIN was not accepted')
479
+ vaultStore.assertScopeToken(scopeToken)
480
+ } catch (e) {
481
+ throw new VaultEnrollmentPartialError('pin-changed', e, undefined, true)
482
+ }
483
+ }
484
+ try {
485
+ if (pinChange) {
486
+ await vaultStore.transitionEnrollmentQuarantine(
487
+ info.serial,
488
+ 'pin-changed',
489
+ 'puk-change-uncertain',
490
+ scopeToken
491
+ )
492
+ } else {
493
+ await vaultStore.preserveEnrollmentQuarantine(info.serial, 'puk-change-uncertain', scopeToken)
494
+ }
495
+ } catch (e) {
496
+ if (pinChange) throw new VaultEnrollmentPartialError('pin-changed', e, undefined, true)
497
+ throw e
498
+ }
499
+ vaultStore.assertScopeToken(scopeToken)
500
+ try {
501
+ await driver.changePuk(info.serial, pukChange.oldPuk, pukChange.newPuk)
502
+ } catch (e) {
503
+ // A definite wrong-PUK response means the PUK stayed old, but a PIN
504
+ // change earlier in this same attempt is already confirmed. Preserve
505
+ // that partial state instead of sending the wizard back to the factory
506
+ // PIN. A transport error makes the old/new PUK outcome ambiguous; the
507
+ // UI must quarantine this token rather than guessing and consuming PUK
508
+ // retries.
509
+ if (isDefiniteCredentialRejection(e)) {
510
+ try {
511
+ await vaultStore.transitionEnrollmentQuarantine(
512
+ info.serial,
513
+ 'puk-change-uncertain',
514
+ pinChange ? 'pin-changed' : null,
515
+ scopeToken
516
+ )
517
+ } catch (storageError) {
518
+ throw new VaultEnrollmentPartialError(
519
+ pinChange ? 'pin-changed' : 'puk-change-uncertain',
520
+ storageError,
521
+ undefined,
522
+ true
523
+ )
524
+ }
525
+ if (pinChange) throw new VaultEnrollmentPartialError('pin-changed', e, undefined, true)
526
+ throw withSerial(e, info.serial)
527
+ }
528
+ throw new VaultEnrollmentPartialError('puk-change-uncertain', e, undefined, true)
529
+ }
530
+ try {
531
+ await vaultStore.transitionEnrollmentQuarantine(info.serial, 'puk-change-uncertain', 'puk-changed', scopeToken)
532
+ } catch (e) {
533
+ throw new VaultEnrollmentPartialError('puk-changed', e, undefined, true)
132
534
  }
133
- if (pinChange) await driver.changePin(pinChange.oldPin, pinChange.newPin)
134
- const verified = await driver.verifyPin(pin)
135
- if (!verified.ok) throw new VaultError('pin-invalid', 'PIN not accepted', verified.retriesLeft)
136
- // Adoption still verifies the PIN above: it proves the holder can
137
- // actually sign with the key they are about to lock funds to.
138
- if (occupant) {
139
- args.onPhase('adopting')
140
- return { info, publicKey: occupant.publicKey, adopted: true }
535
+ try {
536
+ vaultStore.assertScopeToken(scopeToken)
537
+ } catch (e) {
538
+ // PIN/PUK personalization is confirmed, but no slot key exists yet.
539
+ throw new VaultEnrollmentPartialError('puk-changed', e, undefined, true)
141
540
  }
142
541
  args.onPhase('generating')
143
- const { publicKey } = await driver.generateVaultKey(VAULT_SLOT)
144
- return { info, publicKey, adopted: false }
542
+ // As with PIN/PUK changes, durable intent precedes generation. A killed
543
+ // process cannot otherwise distinguish an empty slot from one whose
544
+ // GENERATE ASYMMETRIC KEYPAIR command landed without returning.
545
+ try {
546
+ await vaultStore.transitionEnrollmentQuarantine(info.serial, 'puk-changed', 'generation-uncertain', scopeToken)
547
+ } catch (e) {
548
+ throw new VaultEnrollmentPartialError('puk-changed', e, undefined, true)
549
+ }
550
+ vaultStore.assertScopeToken(scopeToken)
551
+ // Generation is authorized by the still-default management key. The key
552
+ // is not returned as enrolled until that credential has been replaced by
553
+ // native CSPRNG material that never crosses the JS bridge.
554
+ let publicKey: string
555
+ try {
556
+ const generatedResult = await driver.generateVaultKey(info.serial)
557
+ if (generatedResult.manufacturerAttestation !== 'verified') {
558
+ throw new VaultError('attestation-invalid', 'Generated key attestation was not verified')
559
+ }
560
+ publicKey = generatedResult.publicKey
561
+ } catch (e) {
562
+ throw new VaultEnrollmentPartialError('generation-uncertain', e, undefined, true)
563
+ }
564
+ let pubkey: string
565
+ try {
566
+ pubkey = compressPubkey(publicKey)
567
+ } catch (e) {
568
+ // The card may already contain a generated key even though its returned
569
+ // public encoding was unusable. Never present this as a clean failure
570
+ // that invites generation over the same slot.
571
+ throw new VaultEnrollmentPartialError('generation-uncertain', e, undefined, true)
572
+ }
573
+ const generated: VaultKeyRecord = {
574
+ serial: info.serial,
575
+ slot: VAULT_SLOT,
576
+ pubkey,
577
+ nickname,
578
+ enrolledAt
579
+ }
580
+ if (!isVaultKeyRecord(generated)) {
581
+ throw new VaultEnrollmentPartialError(
582
+ 'generation-uncertain',
583
+ new VaultError('template-invalid', 'YubiKey returned invalid enrollment metadata'),
584
+ undefined,
585
+ true
586
+ )
587
+ }
588
+ try {
589
+ await vaultStore.preserveEnrollmentDraft({ record: generated, assurance: 'management-uncertain' }, scopeToken)
590
+ } catch (e) {
591
+ // The public recovery handle could not be made durable after the key
592
+ // was generated. Surface the record and stop before relying on it.
593
+ throw new VaultEnrollmentPartialError('key-generated', e, generated)
594
+ }
595
+ try {
596
+ vaultStore.assertScopeToken(scopeToken)
597
+ } catch (e) {
598
+ throw new VaultEnrollmentPartialError('key-generated', e, generated, true)
599
+ }
600
+ try {
601
+ await driver.protectManagementKey(info.serial)
602
+ } catch (e) {
603
+ // The slot now holds this exact public key, but the card's management
604
+ // state is ambiguous. Preserve an explicit recovery handle; never
605
+ // silently add it and never generate over it on retry.
606
+ throw new VaultEnrollmentPartialError('key-generated', e, generated, true)
607
+ }
608
+ try {
609
+ await vaultStore.preserveEnrollmentDraft({ record: generated, assurance: 'challenge-required' }, scopeToken)
610
+ } catch (e) {
611
+ throw new VaultEnrollmentPartialError('key-protected', e, generated, true)
612
+ }
613
+ // Native generation has already verified the pinned Yubico chain, exact
614
+ // slot key, serial, and PIN/touch policy. This independent fresh challenge
615
+ // proves the protected key remains usable before the record leaves the
616
+ // service.
617
+ args.onPhase('challenging')
618
+ const challenge = Uint8Array.from(randomBytes(32))
619
+ try {
620
+ vaultStore.assertScopeToken(scopeToken)
621
+ const { signature } = await driver.signEcdsa(info.serial, pin, Utils.toHex(challenge))
622
+ if (!signatureProvesKey(pubkey, challenge, signature)) {
623
+ throw new VaultError('wrong-key', 'Generated YubiKey did not prove possession of its private key')
624
+ }
625
+ await vaultStore.preserveEnrollmentDraft({ record: generated, assurance: 'ready' }, scopeToken)
626
+ vaultStore.assertScopeToken(scopeToken)
627
+ } catch (e) {
628
+ throw new VaultEnrollmentPartialError('key-protected', e, generated, true)
629
+ }
630
+ return generated
145
631
  },
146
- () => args.onPhase('connecting')
632
+ () => args.onPhase('connecting'),
633
+ { nfcMessage: args.nfcMessage }
634
+ ).catch(e => {
635
+ // One tag for the whole session, rather than one per throw site: the
636
+ // pre-generation stages have no record to name the card with, and they are
637
+ // precisely the ones that leave a quarantine behind.
638
+ throw withPartialSerial(e, tappedSerial)
639
+ })
640
+ try {
641
+ // A scope switch can land while withKeySession is closing native
642
+ // discovery after the challenge. Preserve the exact public record so the
643
+ // now-occupied protected slot can be adopted instead of stranded.
644
+ vaultStore.assertScopeToken(scopeToken)
645
+ } catch (e) {
646
+ throw new VaultEnrollmentPartialError('key-protected', e, record, true)
647
+ }
648
+ args.onPhase('done')
649
+ return record
650
+ }
651
+
652
+ /** Resume a durable, non-authoritative enrollment recovery handle. A record
653
+ * whose management-key rotation is uncertain is deliberately not recoverable:
654
+ * default-MGM rejection is indistinguishable from a transport failure in the
655
+ * installed SDK wrappers, so treating it as proof could enroll an overwritable
656
+ * key. A protected record may repeat only the non-mutating possession
657
+ * challenge; a ready record can return to the wizard after an app restart. */
658
+ export async function resumeEnrollmentDraft(args: {
659
+ entry: VaultEnrollmentDraftEntry
660
+ onPhase: (p: AdoptPhase) => void
661
+ getPin: () => Promise<string>
662
+ nfcMessage?: string
663
+ scopeToken?: VaultScopeToken
664
+ }): Promise<VaultKeyRecord> {
665
+ if (!isVaultKeyRecord(args.entry.record)) {
666
+ throw new VaultError('template-invalid', 'Invalid enrollment recovery handle')
667
+ }
668
+ const driver = getVaultDriver()
669
+ if (!driver) throw new VaultError('driver-unavailable')
670
+ const scopeToken = args.scopeToken ?? vaultStore.captureScopeToken()
671
+ const stored = (await vaultStore.getEnrollmentDrafts(scopeToken)).find(
672
+ entry =>
673
+ entry.record.serial === args.entry.record.serial &&
674
+ entry.record.pubkey === args.entry.record.pubkey &&
675
+ JSON.stringify(entry.record) === JSON.stringify(args.entry.record)
147
676
  )
677
+ if (!stored) throw new VaultError('not-enrolled', 'Enrollment recovery handle is no longer present')
678
+ if (stored.assurance === 'management-uncertain') {
679
+ throw new VaultEnrollmentPartialError(
680
+ 'key-generated',
681
+ new VaultError(
682
+ 'mgmt-key-custom',
683
+ 'Management-key rotation is uncertain; reset the dedicated PIV application before reusing this token'
684
+ ),
685
+ stored.record
686
+ )
687
+ }
688
+ if (stored.assurance === 'ready') {
689
+ vaultStore.assertScopeToken(scopeToken)
690
+ args.onPhase('done')
691
+ return { ...stored.record }
692
+ }
148
693
 
149
- // The vault seed comes from the user's EXISTING wallet mnemonic plus their
150
- // passphrase — no second phrase, nothing new to write down. It never leaves
151
- // this function: only the SEALED blob is persisted. The `finally` below
152
- // zeroes it on every exit, including a sealVaultKey throw on malformed card
153
- // key material — the seed must never survive this function on ANY path.
154
- const seed = deriveVaultSeed(args.mnemonic, args.passphrase)
155
- let meta: VaultMetaV4
156
- let seal: SealedBlob
694
+ args.onPhase('pin-check')
695
+ const pin = await args.getPin()
696
+ requirePivCode(pin, 'PIN')
157
697
  try {
158
- try {
159
- seal = sealVaultKey(seed, publicKey, { slot: VAULT_SLOT, serial: info.serial })
160
- } catch {
161
- // sealVaultKey's ECDH throws a raw @noble/curves error (no .code) on a
162
- // malformed SEC1 point — a card bug or a foreign PIV slot's key.
163
- // Recode it so callers get a stable, coded failure; never forward the
164
- // underlying message, which could echo the bad key material back out.
165
- throw new VaultError('template-invalid', 'YubiKey returned invalid key material')
166
- }
167
- // Sealing is done with the seed — zero it now rather than waiting for
168
- // the outer `finally`, which stays as a backstop for every other exit.
169
- seed.fill(0)
170
- meta = {
171
- v: 4,
172
- enrolledAt: Date.now(),
173
- yubiSerial: info.serial,
174
- nickname: args.nickname,
175
- slot: VAULT_SLOT,
176
- // An adopted key is already in use by another device whose deposit
177
- // counter this one cannot see, so starting at zero would reissue that
178
- // device's addresses. See randomDepositStartIndex.
179
- nextKeyIndex: adopted ? randomDepositStartIndex() : 0
698
+ vaultStore.assertScopeToken(scopeToken)
699
+ await withKeySession(
700
+ driver,
701
+ async () => {
702
+ vaultStore.assertScopeToken(scopeToken)
703
+ const info = await driver.getKeyInfo()
704
+ if (!isVaultSerial(info.serial)) throw new VaultError('template-invalid', 'YubiKey returned an invalid serial')
705
+ if (info.serial !== stored.record.serial) {
706
+ throw new VaultError(
707
+ 'serial-mismatch',
708
+ 'The presented YubiKey does not match the recovery handle',
709
+ undefined,
710
+ {
711
+ tapped: info.serial,
712
+ chosen: stored.record.serial
713
+ }
714
+ )
715
+ }
716
+ if (info.pinRetries === 0) throw new VaultError('pin-locked', 'PIN is blocked')
717
+ requireVerifiedPin(await driver.verifyPin(stored.record.serial, pin))
718
+ args.onPhase('challenging')
719
+ const readable = await driver.readVaultPublicKey(stored.record.serial)
720
+ if (readable && compressPubkey(readable.publicKey) !== stored.record.pubkey) {
721
+ throw new VaultError('wrong-key', 'The YubiKey slot does not match the enrollment recovery handle')
722
+ }
723
+ const challenge = Uint8Array.from(randomBytes(32))
724
+ const { signature } = await driver.signEcdsa(stored.record.serial, pin, Utils.toHex(challenge))
725
+ if (!signatureProvesKey(stored.record.pubkey, challenge, signature)) {
726
+ throw new VaultError('wrong-key', 'YubiKey failed the enrollment recovery challenge')
727
+ }
728
+ vaultStore.assertScopeToken(scopeToken)
729
+ },
730
+ () => args.onPhase('connecting'),
731
+ { nfcMessage: args.nfcMessage }
732
+ )
733
+ await vaultStore.preserveEnrollmentDraft({ record: stored.record, assurance: 'ready' }, scopeToken)
734
+ vaultStore.assertScopeToken(scopeToken)
735
+ } catch (e) {
736
+ if (e instanceof VaultError && e.code === 'scope-changed') {
737
+ throw new VaultEnrollmentPartialError('key-protected', e, stored.record, true)
180
738
  }
181
- } finally {
182
- seed.fill(0)
739
+ throw e
183
740
  }
741
+ args.onPhase('done')
742
+ return { ...stored.record }
743
+ }
744
+
745
+ /**
746
+ * Prove that a restored or partially enrolled record is backed by the private
747
+ * key in the presented token. No token state is changed and the slot is never
748
+ * generated over. The random challenge prevents replay of an old signature.
749
+ */
750
+ export async function adoptVaultKey(args: {
751
+ record: VaultKeyRecord
752
+ onPhase: (p: AdoptPhase) => void
753
+ getPin: () => Promise<string>
754
+ nfcMessage?: string
755
+ scopeToken?: VaultScopeToken
756
+ }): Promise<VaultKeyRecord> {
757
+ if (!isVaultKeyRecord(args.record)) throw new VaultError('template-invalid', 'Invalid recovered vault key record')
758
+ const driver = getVaultDriver()
759
+ if (!driver) throw new VaultError('driver-unavailable')
760
+ const scopeToken = args.scopeToken ?? vaultStore.captureScopeToken()
761
+
762
+ args.onPhase('pin-check')
763
+ const pin = await args.getPin()
764
+ requirePivCode(pin, 'PIN')
765
+ const challenge = randomBytes(32)
766
+ const digest = Utils.toHex(challenge)
767
+
768
+ vaultStore.assertScopeToken(scopeToken)
769
+ await withKeySession(
770
+ driver,
771
+ async () => {
772
+ vaultStore.assertScopeToken(scopeToken)
773
+ const info = await driver.getKeyInfo()
774
+ if (info.serial !== args.record.serial) {
775
+ throw new VaultError(
776
+ 'serial-mismatch',
777
+ 'The presented YubiKey does not match the recovered record',
778
+ undefined,
779
+ {
780
+ tapped: info.serial,
781
+ chosen: args.record.serial
782
+ }
783
+ )
784
+ }
785
+ if (info.pinRetries === 0) throw new VaultError('pin-locked', 'PIN is blocked')
786
+ const verified = await driver.verifyPin(args.record.serial, pin)
787
+ requireVerifiedPin(verified)
788
+
789
+ args.onPhase('challenging')
790
+ const readable = await driver.readVaultPublicKey(args.record.serial)
791
+ if (readable && compressPubkey(readable.publicKey) !== args.record.pubkey) {
792
+ throw new VaultError('wrong-key', 'The YubiKey slot public key does not match the recovered vault key')
793
+ }
794
+ const { signature } = await driver.signEcdsa(args.record.serial, pin, digest)
795
+ if (!signatureProvesKey(args.record.pubkey, Uint8Array.from(challenge), signature)) {
796
+ throw new VaultError('wrong-key', 'YubiKey failed the recovered-key possession challenge')
797
+ }
798
+ vaultStore.assertScopeToken(scopeToken)
799
+ },
800
+ () => args.onPhase('connecting'),
801
+ { nfcMessage: args.nfcMessage }
802
+ )
184
803
 
804
+ await vaultStore.markKeyAdopted(args.record, scopeToken)
185
805
  args.onPhase('done')
186
- return { pending: { meta, seal } }
806
+ return { ...args.record }
187
807
  }
188
808
 
189
- /** Commit an enrollment produced by enrollVault. Only here does anything reach
190
- * disk. The seal is written first: if the process dies between the two
191
- * writes, `isEnrolled()` (which requires BOTH) still reads false either way,
192
- * so a half-committed enrollment never looks complete. */
193
- export async function finalizeEnrollment(pending: PendingEnrollment): Promise<void> {
194
- await vaultStore.setSeal(pending.seal)
195
- await vaultStore.setMeta(pending.meta)
809
+ export interface VerifiedVaultRecoveryOutput {
810
+ /** Decoded only after baked-salt and exact-lock verification by transfers. */
811
+ instructions: VaultInstructionsV6
812
+ /** Transaction containing this currently spendable output. */
813
+ txid: string
196
814
  }
197
815
 
198
816
  /**
199
- * Recover the vault HD node from the MAIN wallet mnemonic plus the vault
200
- * passphrase — the second of the two recovery paths (see this file's header).
201
- *
202
- * BIP39 passphrases have no checksum, so a mistyped one silently derives a
203
- * different, valid, EMPTY vault node rather than throwing. There used to be a
204
- * stored xpub here to catch that early; v4 meta stores no key material at
205
- * all, so that check now happens where it can actually verify something —
206
- * the spend path's pkh match (transfers.ts) — rather than here.
817
+ * Reconstruct one current enrollment from authoritative spendable R1C outputs.
818
+ * The transfer layer owns pagination and lock verification; this function owns
819
+ * conflict detection and version selection. It never accepts a mixture of
820
+ * enrollment ids or two different key sets at the same revision.
207
821
  */
208
- export async function recoverVaultHD(mnemonic: string, passphrase: string): Promise<HD> {
209
- return deriveVaultHD(mnemonic, passphrase) // throws on empty/invalid
822
+ export function metaFromVerifiedOutputs(outputs: readonly VerifiedVaultRecoveryOutput[]): VaultMeta {
823
+ if (outputs.length === 0) throw new VaultError('vault-empty', 'No verified vault outputs to recover')
824
+ if (outputs.some(o => !/^[0-9a-f]{64}$/.test(o.txid))) {
825
+ throw new VaultError('template-invalid', 'Recovered vault output has an invalid transaction id')
826
+ }
827
+ const vaultId = outputs[0].instructions.vaultId
828
+ const createdAt = outputs[0].instructions.createdAt
829
+ if (outputs.some(o => o.instructions.vaultId !== vaultId || o.instructions.createdAt !== createdAt)) {
830
+ throw new VaultError('template-invalid', 'Conflicting vault enrollments are currently spendable')
831
+ }
832
+
833
+ const revision = Math.max(...outputs.map(o => o.instructions.revision))
834
+ const current = outputs.filter(o => o.instructions.revision === revision)
835
+ const fingerprint = JSON.stringify(current[0].instructions.keys)
836
+ if (current.some(o => JSON.stringify(o.instructions.keys) !== fingerprint)) {
837
+ throw new VaultError('template-invalid', 'Conflicting vault key sets share the latest revision')
838
+ }
839
+ const keys = current[0].instructions.keys.map(k => ({ ...k }))
840
+ const currentPubkeys = new Set(keys.map(k => k.pubkey))
841
+ const removed = new Map<string, { key: VaultKeyRecord; index: number }>()
842
+ for (const { instructions } of outputs) {
843
+ if (instructions.revision >= revision) continue
844
+ instructions.keys.forEach((key, index) => {
845
+ if (!currentPubkeys.has(key.pubkey)) removed.set(key.pubkey, { key: { ...key }, index })
846
+ })
847
+ }
848
+ if (removed.size > 1) {
849
+ throw new VaultError('template-invalid', 'Multiple incomplete key removals are present')
850
+ }
851
+
852
+ const meta: VaultMeta = { v: 6, vaultId, revision, createdAt, keys }
853
+ const tombstone = [...removed.values()][0]
854
+ if (tombstone) {
855
+ meta.pendingRemoval = {
856
+ key: tombstone.key,
857
+ keyIndex: Math.min(tombstone.index, keys.length),
858
+ startedAt: Date.now(),
859
+ revision,
860
+ state: 'broadcast'
861
+ }
862
+ }
863
+ if (!isVaultMeta(meta)) throw new VaultError('template-invalid', 'Recovered vault metadata is invalid')
864
+ return meta
210
865
  }
211
866
 
212
- /** Re-enroll an existing vault to a fresh YubiKey, e.g. after a lost key.
213
- *
214
- * The seal always wraps the 64-byte seed, so reseal re-derives the seed from
215
- * the mnemonic + passphrase itself (rather than taking an already-derived HD
216
- * node) and seals it fresh to the new card's public key. Preserves
217
- * nextKeyIndex so deposit indices are never reissued, and zeroizes the seed
218
- * as soon as sealing succeeds, with `finally` as a backstop for every other
219
- * exit — exactly like enrollVault.
220
- *
221
- * `verifyHD`, if given, gates the whole operation: BIP39 passphrases carry no
222
- * checksum, so a mistyped one derives a different, valid, EMPTY vault node
223
- * with no error of its own. Without a check, that typo would overwrite the
224
- * ONLY seal that opens the real vault with one nobody can ever unwrap back to
225
- * the real funds — the old physical key is gone (that is the point of
226
- * resealing) and the new seal is wrong. The check therefore runs as early as
227
- * the tap flow allows: seed and HD are derived first (no card needed for
228
- * that), verified BEFORE `driver.getKeyInfo()` — i.e. before the tap begins
229
- * at all — so a failed verification never burns a PIN attempt, never risks
230
- * the slot-occupied refusal, and above all never reaches `generateVaultKey`
231
- * (which would irreversibly overwrite the slot) or the `vaultStore` writes.
232
- * A caller that omits `verifyHD` keeps today's behavior: it is on the caller
233
- * to verify the passphrase itself before calling this, whenever the vault
234
- * may hold funds (the recover UI wires this in a later task).
235
- *
236
- * Outputs created under the OLD key stay spendable, and this is the whole
237
- * point of the K1-only custody model: there is ONE vault key reached two
238
- * ways, so the replacement card unwraps the SAME seed the old one did and
239
- * every existing output's child key derives from it exactly as before. No
240
- * sweep is required after replacing a YubiKey. (The old physical card stops
241
- * working nonetheless — the ceremony's serial check in
242
- * armViaReader/openTapSession, ceremony.ts, refuses any card whose serial
243
- * does not match the newly-stored yubiSerial.)
244
- *
245
- * What protects against resealing to a node that is NOT this vault's is
246
- * `verifyHD` above, plus the per-input pkh comparison in transfers.ts's
247
- * prepareSpends: each output's locking script is rebuilt from the key
248
- * actually in hand and compared against the real script out of the listed
249
- * BEEF, so a wrong key or a mistyped passphrase fails loudly before anything
250
- * is reserved or signed.
251
- */
252
- export async function resealToNewKey(
253
- mnemonic: string,
254
- passphrase: string,
255
- nickname: string,
256
- getPin: () => Promise<string>,
257
- verifyHD?: (hd: HD) => Promise<boolean>
867
+ async function requireReadyEnrollmentDrafts(
868
+ records: readonly VaultKeyRecord[],
869
+ scopeToken: VaultScopeToken
258
870
  ): Promise<void> {
259
- const driver = getVaultDriver()
260
- if (!driver) throw new VaultError('driver-unavailable')
871
+ const drafts = await vaultStore.getEnrollmentDrafts(scopeToken)
872
+ for (const record of records) {
873
+ const ready = drafts.some(
874
+ draft =>
875
+ draft.assurance === 'ready' &&
876
+ draft.record.serial === record.serial &&
877
+ draft.record.slot === record.slot &&
878
+ draft.record.pubkey === record.pubkey &&
879
+ draft.record.enrolledAt === record.enrolledAt
880
+ )
881
+ if (!ready) {
882
+ throw new VaultError(
883
+ 'key-not-adopted',
884
+ `Key ${record.serial} has not completed its protected live enrollment challenge`
885
+ )
886
+ }
887
+ }
888
+ }
261
889
 
262
- const seed = deriveVaultSeed(mnemonic, passphrase)
890
+ /** Commit an enrollment: the wizard's 2..5 records become meta v6, atomically
891
+ * (one scoped secure-storage write). The bounds are defensive — the wizard cannot
892
+ * reach Finish with fewer than two keys and disables Add at five.
893
+ *
894
+ * Refuses while a vault is already enrolled: Finish must never silently
895
+ * replace the key list that guards existing deposits (disableVault, offered
896
+ * only at zero balance, is the way to start over; addVaultKey is the way to
897
+ * grow the list). The refusal reuses `key-already-enrolled` — the closest
898
+ * existing code, whose copy the wizard already renders with the serial it
899
+ * carries — rather than minting a new VaultErrorCode that would need its own
900
+ * copy in every locale. */
901
+ export async function finalizeEnrollment(records: VaultKeyRecord[], scopeToken?: VaultScopeToken): Promise<void> {
902
+ if (records.length < VAULT_MIN_KEYS) {
903
+ throw new VaultError('not-enough-keys', `A vault needs at least ${VAULT_MIN_KEYS} keys; ${records.length} given`)
904
+ }
905
+ if (records.length > VAULT_MAX_KEYS) {
906
+ throw new VaultError('too-many-keys', `A vault holds at most ${VAULT_MAX_KEYS} keys; ${records.length} given`)
907
+ }
908
+ const serials = records.map(r => r.serial)
909
+ const dupeSerial = serials.find((s, i) => serials.indexOf(s) !== i)
910
+ if (dupeSerial !== undefined) {
911
+ throw new VaultError('key-already-enrolled', 'Duplicate serial in the enrollment', undefined, {
912
+ serial: dupeSerial
913
+ })
914
+ }
915
+ const token = scopeToken ?? vaultStore.captureScopeToken()
916
+ const existing = await vaultStore.getMeta(token)
917
+ if (existing?.keys.length) {
918
+ throw new VaultError(
919
+ 'key-already-enrolled',
920
+ 'A vault is already enrolled on this device; disable it before enrolling again',
921
+ undefined,
922
+ { serial: existing.keys[0].serial }
923
+ )
924
+ }
925
+ await requireReadyEnrollmentDrafts(records, token)
926
+ await vaultStore.createEnrollment(
927
+ {
928
+ v: 6,
929
+ vaultId: Utils.toHex(randomBytes(32)),
930
+ revision: 1,
931
+ createdAt: Date.now(),
932
+ keys: records
933
+ },
934
+ token
935
+ )
936
+ // Drafts are public recovery handles, not authority. A cleanup failure must
937
+ // not report enrollment failure after the authoritative write committed.
263
938
  try {
264
- // Fail closed BEFORE any card interaction: see this function's doc
265
- // comment for why this has to be the earliest possible point.
266
- if (verifyHD && !(await verifyHD(HD.fromSeed(seed)))) {
267
- throw new VaultError('bad-passphrase', 'Passphrase does not match this vault')
268
- }
939
+ await vaultStore.consumeEnrollmentDrafts(serials, token)
940
+ } catch (error) {
941
+ if (error instanceof VaultError && error.code === 'scope-changed') throw error
942
+ }
943
+ }
269
944
 
270
- const info = await driver.getKeyInfo()
271
- if (info.pinRetries === 0) throw new VaultError('pin-locked', 'PIN is blocked')
272
- if (await driver.readVaultPublicKey(VAULT_SLOT)) {
273
- throw new VaultError('slot-occupied', `PIV slot ${VAULT_SLOT.toString(16)} already holds a key`)
274
- }
275
- const pin = await getPin()
276
- const verified = await driver.verifyPin(pin)
277
- if (!verified.ok) throw new VaultError('pin-invalid', 'PIN not accepted', verified.retriesLeft)
278
- const { publicKey } = await driver.generateVaultKey(VAULT_SLOT)
279
-
280
- let seal: SealedBlob
281
- try {
282
- seal = sealVaultKey(seed, publicKey, { slot: VAULT_SLOT, serial: info.serial })
283
- } catch {
284
- // See enrollVault's identical wrap: never forward the raw error text.
285
- throw new VaultError('template-invalid', 'YubiKey returned invalid key material')
286
- }
287
- // Sealing is done with the seed — zero it now; `finally` is a backstop.
288
- seed.fill(0)
289
-
290
- // Preserve nextKeyIndex across the re-enrollment so deposit indices are
291
- // never reissued to a second address.
292
- const prev = await vaultStore.getMeta()
293
- const meta: VaultMetaV4 = {
294
- v: 4,
295
- enrolledAt: Date.now(),
296
- yubiSerial: info.serial,
297
- nickname,
298
- slot: VAULT_SLOT,
299
- nextKeyIndex: prev?.nextKeyIndex ?? 0
300
- }
301
- await vaultStore.setSeal(seal)
302
- await vaultStore.setMeta(meta)
303
- } finally {
304
- seed.fill(0)
945
+ /** Append one key to an enrolled vault (spec §3.4 "Add key"). vaultStore
946
+ * enforces the duplicate-serial and five-key rules. */
947
+ export async function addVaultKey(record: VaultKeyRecord, scopeToken?: VaultScopeToken): Promise<VaultMeta> {
948
+ if (!isVaultKeyRecord(record)) throw new VaultError('template-invalid', 'Invalid vault key record')
949
+ const token = scopeToken ?? vaultStore.captureScopeToken()
950
+ const existing = await vaultStore.getMeta(token)
951
+ if (!existing) throw new VaultError('not-enrolled', 'Vault is not set up')
952
+ if (existing.keys.length >= VAULT_MAX_KEYS) {
953
+ throw new VaultError('too-many-keys', `The vault already has ${VAULT_MAX_KEYS} keys`)
954
+ }
955
+ if (existing.keys.some(key => key.serial === record.serial || key.pubkey === record.pubkey)) {
956
+ throw new VaultError('key-already-enrolled', record.serial, undefined, { serial: record.serial })
957
+ }
958
+ await requireReadyEnrollmentDrafts([record], token)
959
+ const meta = await vaultStore.addKey(record, token)
960
+ try {
961
+ await vaultStore.consumeEnrollmentDrafts([record.serial], token)
962
+ } catch (error) {
963
+ if (error instanceof VaultError && error.code === 'scope-changed') throw error
305
964
  }
965
+ return meta
306
966
  }
307
967
 
308
- /** Remove all vault state. Callers must sweep funds to the default basket
309
- * BEFORE calling this — see transfers.sweepVaultWithHD. */
310
- export async function disableVault(): Promise<void> {
311
- await vaultStore.clear()
968
+ /** Forget the key list. Only offered when the vault balance is zero (spec
969
+ * §3.4); the keys themselves stay on the YubiKeys. */
970
+ export async function disableVault(scopeToken?: VaultScopeToken): Promise<void> {
971
+ const token = scopeToken ?? vaultStore.captureScopeToken()
972
+ await vaultStore.clear(token)
312
973
  }