@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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.
- package/CHANGELOG.md +547 -0
- package/README.md +19 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/amountFormatHelpers.ts +238 -34
- package/core/backup/RemoteSyncReader.ts +2 -5
- package/core/backup/codec.ts +2 -2
- package/core/backup/push.ts +1 -1
- package/core/config.tsx +16 -1
- package/core/contacts/contactActivity.ts +153 -0
- package/core/contacts/contactCache.ts +41 -0
- package/core/contacts/contactsStore.ts +183 -0
- package/core/context/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +464 -30
- package/core/demo/demoAssets.ts +60 -0
- package/core/demo/demoLedger.ts +240 -0
- package/core/demo/demoMandalaRuntime.ts +96 -0
- package/core/demo/demoMode.ts +38 -0
- package/core/demo/demoWallet.ts +25 -0
- package/core/demo/index.ts +26 -0
- package/core/demo/useDemo.ts +59 -0
- package/core/headers/OfflineFirstChaintracks.ts +52 -14
- package/core/headers/headerStore.ts +7 -10
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +4562 -986
- package/core/identity/contactLink.ts +36 -0
- package/core/identity/handleRegistry/client.ts +285 -0
- package/core/identity/handleRegistry/profileCert.ts +254 -0
- package/core/identity/handleRegistry/registration.ts +559 -0
- package/core/identity/handleRegistry/resolver.ts +247 -0
- package/core/identity/handleRegistry/rules.ts +104 -0
- package/core/index.ts +116 -15
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- package/core/localpay/pendingAborts.ts +5 -1
- package/core/localpay/settlementAck.ts +149 -0
- package/core/localpay/types.ts +14 -1
- package/core/localpay/verify.ts +118 -69
- package/core/mandala/abortGuard.ts +134 -0
- package/core/mandala/basketMigration.ts +166 -0
- package/core/mandala/bundle.ts +244 -0
- package/core/mandala/createRuntime.ts +2437 -0
- package/core/mandala/drain.ts +670 -0
- package/core/mandala/permissionModule.ts +642 -0
- package/core/mandala/resendTransfer.ts +175 -0
- package/core/mandala/runtime.ts +357 -0
- package/core/mandala/settlementStore.ts +412 -0
- package/core/mandala/types.ts +290 -0
- package/core/monitor/MonitorSupervisor.ts +121 -0
- package/core/monitor/TaskBackupPush.ts +1 -1
- package/core/monitor/TaskCreditInbox.ts +1 -1
- package/core/monitor/TaskDrainOutbox.ts +1 -1
- package/core/monitor/TaskSendOffline.ts +1 -1
- package/core/net/online.ts +49 -0
- package/core/numberFormat.ts +19 -0
- package/core/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- package/core/offline/plan.ts +1 -1
- package/core/offline/tokenFrames.ts +197 -0
- package/core/parsePeerPayURI.ts +70 -17
- package/core/pay/rails/address.ts +51 -3
- package/core/pay/rails/handle.ts +88 -9
- package/core/pay/rails/index.ts +16 -6
- package/core/pay/rails/nearby.ts +114 -4
- package/core/pay/recordProof.ts +2 -6
- package/core/services/arcadeBroadcastProvider.ts +1 -4
- package/core/services/capWalletArgs.ts +8 -9
- package/core/services/exchangeRate.ts +1 -1
- package/core/services/externalOrigin.ts +42 -0
- package/core/services/vault/VaultKeyService.ts +912 -251
- package/core/services/vault/ceremony.ts +435 -367
- package/core/services/vault/ceremonyHost.ts +27 -21
- package/core/services/vault/devMock.ts +30 -7
- package/core/services/vault/driver.ts +95 -41
- package/core/services/vault/guard.ts +514 -56
- package/core/services/vault/hardwareLease.ts +22 -0
- package/core/services/vault/mockYubiKey.ts +258 -90
- package/core/services/vault/pivReset.ts +145 -0
- package/core/services/vault/r1comb.ts +976 -0
- package/core/services/vault/session.ts +93 -26
- package/core/services/vault/transfers.ts +2617 -747
- package/core/services/vault/types.ts +100 -43
- package/core/services/vault/vaultStore.ts +991 -74
- package/core/services/walletConnectionValidation.ts +293 -0
- package/core/services/walletServiceConfig.ts +31 -20
- package/core/storage/StorageExpoSQLite.ts +420 -87
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +3 -54
- package/core/storage/methods/listActionsSql.ts +8 -5
- package/core/storage/methods/listOutputsSql.ts +9 -5
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +265 -9
- package/core/storage/methods/reviewStatusSql.ts +7 -2
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +152 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +182 -1
- package/core/toolboxTypes.ts +40 -0
- package/core/userAvatar.ts +79 -0
- package/core/walletMonitor.ts +8 -3
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +31 -30
- package/ui/activityFilter.ts +115 -0
- package/ui/components/QRScanner.tsx +1 -1
- package/ui/components/pay/AdmissionNotice.tsx +99 -0
- package/ui/components/pay/AssetPicker.tsx +184 -0
- package/ui/components/pay/AvailableBalance.tsx +33 -2
- package/ui/components/pay/HandleReceive.tsx +213 -50
- package/ui/components/pay/NearbyFlow.tsx +616 -69
- package/ui/components/pay/PayForm.tsx +73 -8
- package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
- package/ui/components/pay/RecipientField.tsx +132 -73
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/StepBar.tsx +32 -0
- package/ui/components/pay/UniversalSend.tsx +1118 -86
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PencilEditField.tsx +109 -0
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- package/ui/components/ui/SlideOverFromRight.tsx +86 -0
- package/ui/components/vault/EnrollWizard.tsx +1432 -488
- package/ui/components/vault/KeyChooser.tsx +96 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
- package/ui/components/vault/vaultErrorCopy.ts +145 -0
- package/ui/components/wallet/ActivityRow.tsx +283 -97
- package/ui/components/wallet/AmountInput.tsx +92 -28
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- package/ui/components/wallet/ContactActivityList.tsx +149 -0
- package/ui/components/wallet/ContactSigil.tsx +49 -0
- package/ui/components/wallet/EditPictureSheet.tsx +99 -0
- package/ui/components/wallet/FitAmount.tsx +148 -0
- package/ui/components/wallet/IconPickerSheet.tsx +168 -0
- package/ui/components/wallet/IdentifierRow.tsx +69 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
- package/ui/components/wallet/ProfileButton.tsx +62 -0
- package/ui/components/wallet/UserAvatar.tsx +85 -0
- package/ui/components/wallet/avatarIcons.ts +122 -0
- package/ui/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useContactsStore.ts +10 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +320 -0
- package/ui/hooks/useOnline.ts +65 -20
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +75 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/ContactScreen.tsx +289 -0
- package/ui/screens/ContactsScreen.tsx +373 -0
- package/ui/screens/IdentifierScreen.tsx +234 -0
- package/ui/screens/NewContactScreen.tsx +362 -0
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +145 -12
- package/ui/screens/ProfileScreen.tsx +783 -0
- package/ui/screens/SettingsScreen.tsx +18 -9
- package/ui/screens/TransactionDetailScreen.tsx +419 -0
- package/ui/screens/TrustScreen.tsx +1 -1
- package/ui/screens/VaultScreen.tsx +925 -171
- package/ui/screens/VaultTransferScreen.tsx +376 -123
- package/ui/screens/WalletCheckScreen.tsx +10 -1
- package/ui/screens/WalletConfigScreen.tsx +80 -16
- package/ui/screens/WalletHomeScreen.tsx +915 -139
- package/ui/screens/homeBadges.ts +9 -1
- package/ui/screens/tokenRowTitle.ts +68 -0
- package/ui/tokenFormat.ts +108 -0
- package/ui/tokenSeen.ts +75 -0
- package/ui/tokenStatus.ts +100 -0
- package/ui/txStatus.ts +43 -5
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/services/vault/k1.ts +0 -75
- package/core/services/vault/sealing.ts +0 -84
- package/core/services/vault/vaultDerivation.ts +0 -152
- package/core/services/vault/vaultPassphrase.ts +0 -287
- package/ui/components/vault/PassphraseField.tsx +0 -306
- package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
- package/ui/screens/VaultRecoverScreen.tsx +0 -226
|
@@ -1,312 +1,973 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* VaultKeyService —
|
|
2
|
+
* VaultKeyService — enrolling YubiKeys into the vault's key list, and tearing
|
|
3
|
+
* the list down.
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
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
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
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
|
-
*
|
|
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 {
|
|
37
|
-
import {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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.
|
|
90
|
-
* (dev/test convenience). */
|
|
295
|
+
* new PIN the user chose. Enrollment rejects omission. */
|
|
91
296
|
requestPinChange?: (retries: number) => Promise<{ oldPin: string; newPin: string }>
|
|
92
|
-
|
|
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
|
-
//
|
|
97
|
-
//
|
|
98
|
-
// the
|
|
99
|
-
|
|
100
|
-
|
|
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
|
|
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'
|
|
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
|
-
|
|
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
|
-
//
|
|
125
|
-
//
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
-
|
|
144
|
-
|
|
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
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
-
|
|
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 {
|
|
806
|
+
return { ...args.record }
|
|
187
807
|
}
|
|
188
808
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
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
|
-
*
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
*
|
|
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
|
|
209
|
-
|
|
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
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
|
260
|
-
|
|
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
|
-
|
|
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
|
-
|
|
265
|
-
|
|
266
|
-
if (
|
|
267
|
-
|
|
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
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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
|
-
/**
|
|
309
|
-
*
|
|
310
|
-
export async function disableVault(): Promise<void> {
|
|
311
|
-
|
|
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
|
}
|