@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.
- package/CHANGELOG.md +311 -0
- package/README.md +52 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/config.tsx +21 -18
- package/core/context/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +413 -23
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +3368 -952
- package/core/index.ts +107 -14
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- 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/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- 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/services/capWalletArgs.ts +8 -9
- package/core/services/externalOrigin.ts +39 -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 +19 -24
- package/core/storage/StorageExpoSQLite.ts +382 -56
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +0 -54
- package/core/storage/methods/listOutputsSql.ts +7 -3
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +263 -6
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +123 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +240 -0
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +25 -24
- 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 +43 -2
- package/ui/components/pay/RecipientField.tsx +49 -4
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/UniversalSend.tsx +534 -30
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- 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 +101 -17
- package/ui/components/wallet/AmountInput.tsx +77 -25
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- package/ui/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +303 -0
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +50 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +130 -10
- package/ui/screens/SettingsScreen.tsx +18 -9
- 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 +42 -20
- package/ui/screens/WalletHomeScreen.tsx +417 -86
- 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 +79 -0
- 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,43 +1,85 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Software YubiKey for development and tests.
|
|
3
3
|
*
|
|
4
|
-
* Implements VaultDriver against
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* real platforms
|
|
10
|
-
* without hardware.
|
|
4
|
+
* Implements VaultDriver against in-memory P-256 keypairs — ONE RECORD PER
|
|
5
|
+
* SERIAL, so a test (or the DEV present-key selector) can stand in for a
|
|
6
|
+
* multi-key vault by switching serials with insertKey(). Emulates the
|
|
7
|
+
* behaviours the real ceremony must survive: PIN retries and lockout per key,
|
|
8
|
+
* touch timeouts, key removal mid-operation, and DER signatures exactly like
|
|
9
|
+
* both real platforms (not low-S normalised).
|
|
11
10
|
*
|
|
12
11
|
* DEV/test only. Never bundled into a path a production user reaches.
|
|
13
12
|
*/
|
|
14
13
|
import { p256 } from '@noble/curves/nist.js'
|
|
15
14
|
import { Utils } from '@bsv/sdk'
|
|
16
15
|
import { VaultDriver, KeyEvent } from './driver'
|
|
17
|
-
import { softwareEcdh } from './sealing'
|
|
18
16
|
import { VaultError } from './types'
|
|
19
17
|
|
|
20
18
|
type TouchBehavior = 'instant' | 'timeout'
|
|
21
19
|
|
|
22
20
|
const DEFAULT_PIN = '123456'
|
|
21
|
+
const DEFAULT_PUK = '12345678'
|
|
22
|
+
const VAULT_SLOT = 0x82
|
|
23
|
+
const PIV_CODE = /^[0-9]{6,8}$/
|
|
24
|
+
|
|
25
|
+
function requirePivCode(value: string, label: 'PIN' | 'PUK'): void {
|
|
26
|
+
if (!PIV_CODE.test(value)) throw new VaultError('template-invalid', `PIV ${label} must be 6 to 8 ASCII digits`)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface MockKeyRecord {
|
|
30
|
+
priv: Uint8Array | null
|
|
31
|
+
pub: string | null
|
|
32
|
+
pin: string
|
|
33
|
+
pinRetries: number
|
|
34
|
+
pinVerified: boolean
|
|
35
|
+
puk: string
|
|
36
|
+
pukRetries: number
|
|
37
|
+
managementProtected: boolean
|
|
38
|
+
/** Explicit DEV/test simulation of the native manufacturer chain gate. */
|
|
39
|
+
manufacturerAttested: boolean
|
|
40
|
+
otherPivSlotOccupied: boolean
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const freshRecord = (): MockKeyRecord => ({
|
|
44
|
+
priv: null,
|
|
45
|
+
pub: null,
|
|
46
|
+
pin: DEFAULT_PIN,
|
|
47
|
+
pinRetries: 3,
|
|
48
|
+
pinVerified: false,
|
|
49
|
+
puk: DEFAULT_PUK,
|
|
50
|
+
pukRetries: 3,
|
|
51
|
+
managementProtected: false,
|
|
52
|
+
manufacturerAttested: true,
|
|
53
|
+
otherPivSlotOccupied: false
|
|
54
|
+
})
|
|
23
55
|
|
|
24
56
|
export class MockYubiKey implements VaultDriver {
|
|
25
57
|
private listeners = new Set<(e: KeyEvent) => void>()
|
|
26
58
|
private present = false
|
|
27
59
|
private serial = 'MOCK-1'
|
|
28
|
-
private
|
|
29
|
-
private pinRetries = 3
|
|
30
|
-
private pinVerified = false
|
|
60
|
+
private keys = new Map<string, MockKeyRecord>()
|
|
31
61
|
private touch: TouchBehavior = 'instant'
|
|
32
|
-
private
|
|
33
|
-
|
|
62
|
+
private lastStartMessage: string | undefined
|
|
63
|
+
|
|
64
|
+
/** The current serial's record, created on first use. */
|
|
65
|
+
private record(): MockKeyRecord {
|
|
66
|
+
let r = this.keys.get(this.serial)
|
|
67
|
+
if (!r) {
|
|
68
|
+
r = freshRecord()
|
|
69
|
+
this.keys.set(this.serial, r)
|
|
70
|
+
}
|
|
71
|
+
return r
|
|
72
|
+
}
|
|
34
73
|
|
|
35
74
|
// ---- test controls ---------------------------------------------------
|
|
75
|
+
/** Present the key with this serial (creating its record on first use). A
|
|
76
|
+
* swap ends the previous session, so PIN verification resets; the record's
|
|
77
|
+
* own PIN and lockout state persist like a real card's would. */
|
|
36
78
|
insertKey(serial = 'MOCK-1'): void {
|
|
79
|
+
if (this.present) this.record().pinVerified = false
|
|
37
80
|
this.serial = serial
|
|
38
81
|
this.present = true
|
|
39
|
-
this.
|
|
40
|
-
this.pinVerified = false
|
|
82
|
+
this.record().pinVerified = false
|
|
41
83
|
this.emit({ type: 'attached', serial, transport: 'mock' })
|
|
42
84
|
}
|
|
43
85
|
|
|
@@ -45,7 +87,7 @@ export class MockYubiKey implements VaultDriver {
|
|
|
45
87
|
if (!this.present) return
|
|
46
88
|
const serial = this.serial
|
|
47
89
|
this.present = false
|
|
48
|
-
this.pinVerified = false
|
|
90
|
+
this.record().pinVerified = false
|
|
49
91
|
this.emit({ type: 'detached', serial, transport: 'mock' })
|
|
50
92
|
}
|
|
51
93
|
|
|
@@ -53,8 +95,9 @@ export class MockYubiKey implements VaultDriver {
|
|
|
53
95
|
this.touch = b
|
|
54
96
|
}
|
|
55
97
|
|
|
98
|
+
/** Set the CURRENT serial's PIN. */
|
|
56
99
|
setPin(pin: string): void {
|
|
57
|
-
this.pin = pin
|
|
100
|
+
this.record().pin = pin
|
|
58
101
|
}
|
|
59
102
|
|
|
60
103
|
/** Simulate the NFC session dying before any key connected — the system
|
|
@@ -65,12 +108,29 @@ export class MockYubiKey implements VaultDriver {
|
|
|
65
108
|
this.emit({ type: 'session-failed', code, transport: 'mock' })
|
|
66
109
|
}
|
|
67
110
|
|
|
68
|
-
/** Simulate a slot that already holds a key (e.g. an
|
|
69
|
-
* identity in retired slot 82)
|
|
70
|
-
*
|
|
111
|
+
/** Simulate a slot that already holds a key on the current serial (e.g. an
|
|
112
|
+
* age-plugin-yubikey identity in retired slot 82). generateVaultKey replaces
|
|
113
|
+
* it — spec D6 never adopts an existing key. */
|
|
71
114
|
occupySlot(): void {
|
|
72
|
-
|
|
73
|
-
|
|
115
|
+
const r = this.record()
|
|
116
|
+
r.priv = p256.utils.randomSecretKey()
|
|
117
|
+
r.pub = Utils.toHex(Array.from(p256.getPublicKey(r.priv, false)))
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Simulate an unrelated certificate/key in any other user PIV slot. */
|
|
121
|
+
occupyOtherPivSlot(): void {
|
|
122
|
+
this.record().otherPivSlotOccupied = true
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** DEV/test only: simulate a missing, overwritten, or unknown factory F9
|
|
126
|
+
* certificate. Production never gets this software driver. */
|
|
127
|
+
setManufacturerAttested(attested: boolean): void {
|
|
128
|
+
this.record().manufacturerAttested = attested
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The last NFC alert text passed to start(), for tests. */
|
|
132
|
+
get startMessage(): string | undefined {
|
|
133
|
+
return this.lastStartMessage
|
|
74
134
|
}
|
|
75
135
|
|
|
76
136
|
// ---- VaultDriver -----------------------------------------------------
|
|
@@ -81,7 +141,8 @@ export class MockYubiKey implements VaultDriver {
|
|
|
81
141
|
/** The mock behaves like a persistent reader (insert/remove under test). */
|
|
82
142
|
sessionBased = false
|
|
83
143
|
|
|
84
|
-
start(): void {
|
|
144
|
+
start(message?: string): void {
|
|
145
|
+
this.lastStartMessage = message
|
|
85
146
|
// Session-based flows (NFC) call start() to open a scan session and wait
|
|
86
147
|
// for the tap to connect. Simulate that: if a key is "held", emit attached
|
|
87
148
|
// now. Persistent flows never rely on this (they see the key via getKeyInfo).
|
|
@@ -92,12 +153,9 @@ export class MockYubiKey implements VaultDriver {
|
|
|
92
153
|
|
|
93
154
|
stop(): void {
|
|
94
155
|
// Matches the real adapter's contract (driver.ts adaptNative.stop): do NOT
|
|
95
|
-
// clear listeners. App subscribers (WalletContext, and
|
|
96
|
-
//
|
|
97
|
-
// transport's stop/start cycles.
|
|
98
|
-
// ceremony that calls stop() and then start() again on the SAME run (e.g.
|
|
99
|
-
// reopening a fresh NFC session after a dropped tap) — its own attach
|
|
100
|
-
// listener, registered once at the top of that run, would be gone.
|
|
156
|
+
// clear listeners. App subscribers (WalletContext, and the ceremony's own
|
|
157
|
+
// mid-flight NFC retry/batch loop) stay subscribed across a session-based
|
|
158
|
+
// transport's stop/start cycles.
|
|
101
159
|
}
|
|
102
160
|
|
|
103
161
|
onKeyEvent(cb: (e: KeyEvent) => void): () => void {
|
|
@@ -107,68 +165,163 @@ export class MockYubiKey implements VaultDriver {
|
|
|
107
165
|
|
|
108
166
|
async getKeyInfo(): Promise<{ serial: string; firmwareVersion: string; pinRetries: number }> {
|
|
109
167
|
this.requirePresent()
|
|
110
|
-
return { serial: this.serial, firmwareVersion: '5.7.1', pinRetries: this.pinRetries }
|
|
168
|
+
return { serial: this.serial, firmwareVersion: '5.7.1', pinRetries: this.record().pinRetries }
|
|
111
169
|
}
|
|
112
170
|
|
|
113
|
-
async verifyPin(pin: string): Promise<{ ok: boolean; retriesLeft: number }> {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
171
|
+
async verifyPin(expectedSerial: string, pin: string): Promise<{ ok: boolean; retriesLeft: number }> {
|
|
172
|
+
requirePivCode(pin, 'PIN')
|
|
173
|
+
this.requireExpectedSerial(expectedSerial)
|
|
174
|
+
const r = this.record()
|
|
175
|
+
if (r.pinRetries <= 0) throw new VaultError('pin-locked', 'PIN is blocked')
|
|
176
|
+
if (pin === r.pin) {
|
|
177
|
+
r.pinRetries = 3
|
|
178
|
+
r.pinVerified = true
|
|
119
179
|
return { ok: true, retriesLeft: 3 }
|
|
120
180
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
return { ok: false, retriesLeft:
|
|
181
|
+
r.pinRetries -= 1
|
|
182
|
+
r.pinVerified = false
|
|
183
|
+
return { ok: false, retriesLeft: r.pinRetries }
|
|
124
184
|
}
|
|
125
185
|
|
|
126
|
-
async changePin(
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
186
|
+
async changePin(
|
|
187
|
+
expectedSerial: string,
|
|
188
|
+
oldPin: string,
|
|
189
|
+
newPin: string
|
|
190
|
+
): Promise<{ ok: boolean; retriesLeft: number }> {
|
|
191
|
+
requirePivCode(oldPin, 'PIN')
|
|
192
|
+
requirePivCode(newPin, 'PIN')
|
|
193
|
+
this.requireExpectedSerial(expectedSerial)
|
|
194
|
+
const r = this.record()
|
|
195
|
+
if (r.pinRetries <= 0) throw new VaultError('pin-locked', 'PIN is blocked')
|
|
196
|
+
if (oldPin !== r.pin) {
|
|
197
|
+
r.pinRetries -= 1
|
|
198
|
+
throw new VaultError('pin-invalid', 'Wrong PIN', r.pinRetries)
|
|
132
199
|
}
|
|
133
|
-
|
|
134
|
-
|
|
200
|
+
r.pin = newPin
|
|
201
|
+
r.pinRetries = 3
|
|
135
202
|
return { ok: true, retriesLeft: 3 }
|
|
136
203
|
}
|
|
137
204
|
|
|
138
|
-
async
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
205
|
+
async changePuk(
|
|
206
|
+
expectedSerial: string,
|
|
207
|
+
oldPuk: string,
|
|
208
|
+
newPuk: string
|
|
209
|
+
): Promise<{ ok: boolean; retriesLeft: number }> {
|
|
210
|
+
requirePivCode(oldPuk, 'PUK')
|
|
211
|
+
requirePivCode(newPuk, 'PUK')
|
|
212
|
+
this.requireExpectedSerial(expectedSerial)
|
|
213
|
+
const r = this.record()
|
|
214
|
+
if (r.pukRetries <= 0) throw new VaultError('puk-locked', 'PUK is blocked')
|
|
215
|
+
if (oldPuk !== r.puk) {
|
|
216
|
+
r.pukRetries -= 1
|
|
217
|
+
throw new VaultError('puk-invalid', 'Wrong PUK', r.pukRetries)
|
|
218
|
+
}
|
|
219
|
+
r.puk = newPuk
|
|
220
|
+
r.pukRetries = 3
|
|
221
|
+
return { ok: true, retriesLeft: 3 }
|
|
143
222
|
}
|
|
144
223
|
|
|
145
|
-
async
|
|
146
|
-
|
|
147
|
-
|
|
224
|
+
async preflightDedicatedPiv(
|
|
225
|
+
expectedSerial: string,
|
|
226
|
+
allowOccupiedVaultSlot = false
|
|
227
|
+
): Promise<{
|
|
228
|
+
ok: true
|
|
229
|
+
inspection: 'metadata'
|
|
230
|
+
manufacturerAttestation: 'verified'
|
|
231
|
+
}> {
|
|
232
|
+
this.requireExpectedSerial(expectedSerial)
|
|
233
|
+
const r = this.record()
|
|
234
|
+
if (!r.manufacturerAttested) {
|
|
235
|
+
throw new VaultError('attestation-invalid', 'Factory manufacturer attestation is not trusted')
|
|
236
|
+
}
|
|
237
|
+
if (r.managementProtected) throw new VaultError('mgmt-key-custom', 'Default management key rejected')
|
|
238
|
+
if ((!allowOccupiedVaultSlot && r.priv) || r.otherPivSlotOccupied) {
|
|
239
|
+
throw new VaultError('slot-occupied', 'The PIV application already contains a user key')
|
|
240
|
+
}
|
|
241
|
+
return { ok: true, inspection: 'metadata', manufacturerAttestation: 'verified' }
|
|
148
242
|
}
|
|
149
243
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
*/
|
|
160
|
-
async ecdh(_slot: number, pin: string, peerPublicKey: string): Promise<{ secret: string }> {
|
|
161
|
-
this.requirePresent()
|
|
162
|
-
if (!this.pinVerified) {
|
|
163
|
-
if (!pin) throw new VaultError('pin-required', 'PIN required before ECDH')
|
|
164
|
-
const res = await this.verifyPin(pin)
|
|
165
|
-
if (!res.ok) throw new VaultError('pin-invalid', 'Wrong PIN', res.retriesLeft)
|
|
244
|
+
async generateVaultKey(expectedSerial: string): Promise<{
|
|
245
|
+
publicKey: string
|
|
246
|
+
manufacturerAttestation: 'verified'
|
|
247
|
+
}> {
|
|
248
|
+
this.requireExpectedSerial(expectedSerial)
|
|
249
|
+
const r = this.record()
|
|
250
|
+
if (r.managementProtected) throw new VaultError('mgmt-key-custom', 'Management key is protected')
|
|
251
|
+
if (!r.manufacturerAttested) {
|
|
252
|
+
throw new VaultError('attestation-invalid', 'Generated key manufacturer attestation failed')
|
|
166
253
|
}
|
|
167
|
-
|
|
168
|
-
|
|
254
|
+
r.priv = p256.utils.randomSecretKey()
|
|
255
|
+
r.pub = Utils.toHex(Array.from(p256.getPublicKey(r.priv, false)))
|
|
256
|
+
return { publicKey: r.pub, manufacturerAttestation: 'verified' }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async protectManagementKey(expectedSerial: string): Promise<{ ok: true }> {
|
|
260
|
+
this.requireExpectedSerial(expectedSerial)
|
|
261
|
+
const r = this.record()
|
|
262
|
+
if (r.managementProtected) throw new VaultError('mgmt-key-custom', 'Management key is already protected')
|
|
263
|
+
r.managementProtected = true
|
|
264
|
+
return { ok: true }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async resetPivApplication(expectedSerial: string): Promise<{ ok: true }> {
|
|
268
|
+
this.requireExpectedSerial(expectedSerial)
|
|
269
|
+
// The real card blocks the PIN and PUK before RESET, so nothing here is
|
|
270
|
+
// conditional on knowing either code — that is the whole point of reset.
|
|
271
|
+
// A PIV application reset wipes every slot's keys/certs (0x82 included)
|
|
272
|
+
// and restores the default PIN, PUK, management key and retry counters —
|
|
273
|
+
// but it never touches slot F9's factory manufacturer attestation, which
|
|
274
|
+
// is provisioned at manufacture time and lives outside the resettable PIV
|
|
275
|
+
// application state on the real card. A counterfeit or tampered key's bad
|
|
276
|
+
// attestation must survive a reset unchanged: reset cannot repair it, and
|
|
277
|
+
// must not be modelled as laundering it back to trusted.
|
|
278
|
+
const { manufacturerAttested } = this.record()
|
|
279
|
+
this.keys.set(expectedSerial, { ...freshRecord(), manufacturerAttested })
|
|
280
|
+
return { ok: true }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** DEV/test control: drive a card away from factory state, the way a
|
|
284
|
+
* YubiKey that has been used for something else arrives. */
|
|
285
|
+
personalise(pin: string, puk: string): void {
|
|
286
|
+
requirePivCode(pin, 'PIN')
|
|
287
|
+
requirePivCode(puk, 'PUK')
|
|
288
|
+
const r = this.record()
|
|
289
|
+
r.pin = pin
|
|
290
|
+
r.puk = puk
|
|
291
|
+
r.managementProtected = true
|
|
292
|
+
}
|
|
169
293
|
|
|
170
|
-
|
|
171
|
-
|
|
294
|
+
/** DEV/test control: is this card in just-installed state? */
|
|
295
|
+
isFactory(serial = this.serial): boolean {
|
|
296
|
+
const r = this.keys.get(serial)
|
|
297
|
+
if (!r) return false
|
|
298
|
+
return (
|
|
299
|
+
r.pin === DEFAULT_PIN &&
|
|
300
|
+
r.puk === DEFAULT_PUK &&
|
|
301
|
+
r.pinRetries === 3 &&
|
|
302
|
+
r.pukRetries === 3 &&
|
|
303
|
+
!r.managementProtected &&
|
|
304
|
+
r.priv === null
|
|
305
|
+
)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async readVaultPublicKey(expectedSerial: string): Promise<{ publicKey: string } | null> {
|
|
309
|
+
this.requireExpectedSerial(expectedSerial)
|
|
310
|
+
const r = this.record()
|
|
311
|
+
return r.pub ? { publicKey: r.pub } : null
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The card's own occupancy answer for slot 0x82.
|
|
315
|
+
*
|
|
316
|
+
* Separate from `readVaultPublicKey` because the real drivers answer it by a
|
|
317
|
+
* different route — iOS attests the slot, since it cannot read a retired
|
|
318
|
+
* slot's certificate and would report every 0x82 as keyless otherwise. The
|
|
319
|
+
* software card has no such asymmetry, so here the two agree; the split
|
|
320
|
+
* exists so a caller that needs occupancy is asking the question both
|
|
321
|
+
* platforms can actually answer. */
|
|
322
|
+
async isVaultSlotOccupied(expectedSerial: string): Promise<{ occupied: boolean }> {
|
|
323
|
+
this.requireExpectedSerial(expectedSerial)
|
|
324
|
+
return { occupied: this.record().pub !== null }
|
|
172
325
|
}
|
|
173
326
|
|
|
174
327
|
/** Software stand-in for the card's GENERAL AUTHENTICATE.
|
|
@@ -176,24 +329,26 @@ export class MockYubiKey implements VaultDriver {
|
|
|
176
329
|
* Emits DER, exactly like both real platforms, so a DER-parsing bug cannot
|
|
177
330
|
* hide behind the mock. Enforces the same 32-byte digest rule the native
|
|
178
331
|
* modules do — on iOS an unrecognised algorithm constant silently signs 32
|
|
179
|
-
* ZERO bytes, and on Android an over-long payload is silently truncated
|
|
180
|
-
* this check is load-bearing, not decorative.
|
|
332
|
+
* ZERO bytes, and on Android an over-long payload is silently truncated.
|
|
181
333
|
*
|
|
182
|
-
* `lowS: false` is passed explicitly:
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
* a non-canonical signature; that failure would first appear against real
|
|
187
|
-
* hardware, exactly the scenario this mock exists to prevent.
|
|
334
|
+
* `lowS: false` is passed explicitly: real YubiKey PIV hardware does not
|
|
335
|
+
* normalise — roughly half of real signatures are high-S — and the R1C
|
|
336
|
+
* script accepts both (spec §2.5). A mock that only emitted low-S could not
|
|
337
|
+
* catch downstream code that mishandles a non-canonical signature.
|
|
188
338
|
*/
|
|
189
|
-
async signEcdsa(
|
|
190
|
-
this.
|
|
191
|
-
|
|
339
|
+
async signEcdsa(expectedSerial: string, pin: string, digest: string): Promise<{ signature: string }> {
|
|
340
|
+
this.requireExpectedSerial(expectedSerial)
|
|
341
|
+
const r = this.record()
|
|
342
|
+
if (!r.pinVerified) {
|
|
192
343
|
if (!pin) throw new VaultError('pin-required', 'PIN required before signing')
|
|
193
|
-
|
|
194
|
-
|
|
344
|
+
requirePivCode(pin, 'PIN')
|
|
345
|
+
const res = await this.verifyPin(expectedSerial, pin)
|
|
346
|
+
if (!res.ok) {
|
|
347
|
+
if (res.retriesLeft <= 0) throw new VaultError('pin-locked', 'PIN is blocked', 0)
|
|
348
|
+
throw new VaultError('pin-invalid', 'Wrong PIN', res.retriesLeft)
|
|
349
|
+
}
|
|
195
350
|
}
|
|
196
|
-
if (!
|
|
351
|
+
if (!r.priv) throw new VaultError('no-key', 'No key in slot')
|
|
197
352
|
|
|
198
353
|
const bytes = Utils.toArray(digest, 'hex')
|
|
199
354
|
if (bytes.length !== 32) {
|
|
@@ -201,7 +356,7 @@ export class MockYubiKey implements VaultDriver {
|
|
|
201
356
|
}
|
|
202
357
|
if (this.touch === 'timeout') throw new VaultError('touch-timeout', 'Touch not detected')
|
|
203
358
|
|
|
204
|
-
const raw = p256.sign(Uint8Array.from(bytes),
|
|
359
|
+
const raw = p256.sign(Uint8Array.from(bytes), r.priv, { prehash: false, lowS: false })
|
|
205
360
|
const der = p256.Signature.fromBytes(raw).toBytes('der')
|
|
206
361
|
return { signature: Utils.toHex(Array.from(der)) }
|
|
207
362
|
}
|
|
@@ -211,6 +366,19 @@ export class MockYubiKey implements VaultDriver {
|
|
|
211
366
|
if (!this.present) throw new VaultError('no-key', 'No YubiKey present')
|
|
212
367
|
}
|
|
213
368
|
|
|
369
|
+
private requireExpectedSerial(expectedSerial: string): void {
|
|
370
|
+
if (!/^[A-Za-z0-9._:-]{1,64}$/.test(expectedSerial)) {
|
|
371
|
+
throw new VaultError('template-invalid', 'Invalid expected YubiKey serial')
|
|
372
|
+
}
|
|
373
|
+
this.requirePresent()
|
|
374
|
+
if (this.serial !== expectedSerial) {
|
|
375
|
+
throw new VaultError('serial-mismatch', `Presented key ${this.serial}, expected ${expectedSerial}`, undefined, {
|
|
376
|
+
tapped: this.serial,
|
|
377
|
+
chosen: expectedSerial
|
|
378
|
+
})
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
214
382
|
private emit(e: KeyEvent): void {
|
|
215
383
|
this.listeners.forEach(cb => cb(e))
|
|
216
384
|
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resetting a YubiKey's PIV application back to factory state.
|
|
3
|
+
*
|
|
4
|
+
* Kept out of VaultKeyService.ts on purpose: this is a destructive maintenance
|
|
5
|
+
* operation with its own failure modes, not part of the enrollment state
|
|
6
|
+
* machine. It runs in its own card session — never folded into an enrollment
|
|
7
|
+
* tap — so a dropped session can never leave the enrollment quarantine
|
|
8
|
+
* machinery in a state it was not designed for.
|
|
9
|
+
*
|
|
10
|
+
* SAFETY. A PIV reset destroys the P-256 key in Vault slot 0x82. If the token
|
|
11
|
+
* is already an enrolled vault key, that removes one of the k-of-n signers and
|
|
12
|
+
* can make vault funds permanently unspendable. The enrolled-serial refusal
|
|
13
|
+
* below runs before the card is touched AND again inside the session, and is
|
|
14
|
+
* deliberately not overridable by any caller flag — unlike
|
|
15
|
+
* `replaceOccupiedVaultSlot`, which consents to replacing a slot that is by
|
|
16
|
+
* definition not yet part of the vault.
|
|
17
|
+
*
|
|
18
|
+
* "Enrolled" is read wider than `getMeta` reads it, on purpose:
|
|
19
|
+
*
|
|
20
|
+
* - a key in `pendingRemoval` is NOT in `meta.keys` (isVaultMeta enforces
|
|
21
|
+
* their disjointness), but it is still recoverable — `cancelUnbroadcastKeyRemoval`
|
|
22
|
+
* splices it back into the active list — so wiping it would leave the vault
|
|
23
|
+
* listing an active signer whose card holds no key;
|
|
24
|
+
* - metadata is namespaced per wallet+chain, but a YubiKey is one physical
|
|
25
|
+
* object. The card enrolled in the mainnet vault is the same card the
|
|
26
|
+
* testnet enrollment wizard sees as unknown, so the refusal set comes from
|
|
27
|
+
* `vaultStore.enrolledSerialsAcrossChains`, not `getMeta`.
|
|
28
|
+
*
|
|
29
|
+
* What that still cannot see is a vault belonging to a DIFFERENT wallet
|
|
30
|
+
* identity on this device: SecureStore cannot be enumerated, so proving that
|
|
31
|
+
* negative needs a device-wide serial index this module does not have. Against
|
|
32
|
+
* that residual there is one last, purely local signal — a key sitting in slot
|
|
33
|
+
* 0x82 means this card is a vault key for SOME vault — so an occupied slot is
|
|
34
|
+
* refused unless the caller passes `acknowledgeUnrecognizedVaultKey`. That one
|
|
35
|
+
* IS overridable, because a card left over from a vault the user has already
|
|
36
|
+
* abandoned is the whole reason this service exists; the enrolled-serial
|
|
37
|
+
* refusal above is not.
|
|
38
|
+
*
|
|
39
|
+
* That occupancy question goes to `isVaultSlotOccupied`, which both platforms
|
|
40
|
+
* answer from the card (iOS attests the slot; Android reads its metadata) and
|
|
41
|
+
* which fails closed — only an explicit reference-not-found reports the slot
|
|
42
|
+
* empty. It is deliberately NOT `readVaultPublicKey() !== null`: that returns
|
|
43
|
+
* a public key, and iOS cannot read a retired slot's certificate at all, so it
|
|
44
|
+
* reports null for every 0x82 and this refusal would never fire there.
|
|
45
|
+
*/
|
|
46
|
+
import { getVaultDriver } from './driver'
|
|
47
|
+
import { withKeySession } from './session'
|
|
48
|
+
import { VaultError } from './types'
|
|
49
|
+
import { isVaultSerial, vaultStore, type VaultScopeToken } from './vaultStore'
|
|
50
|
+
|
|
51
|
+
export type PivResetPhase = 'waiting' | 'resetting'
|
|
52
|
+
|
|
53
|
+
export async function resetPivApplication(args: {
|
|
54
|
+
/** The reset tap must present exactly this key. */
|
|
55
|
+
serial: string
|
|
56
|
+
/** Serials the caller holds beyond the stored meta — a wizard's pending
|
|
57
|
+
* records. Refused alongside meta. */
|
|
58
|
+
refuseSerials?: readonly string[]
|
|
59
|
+
/** Explicit acknowledgement that this destroys every credential on the
|
|
60
|
+
* token, not only Vault's slot. */
|
|
61
|
+
acknowledgeDestroysAllCredentials: true
|
|
62
|
+
/** Consent to wiping a card whose Vault slot already holds a key that belongs
|
|
63
|
+
* to no vault this device can see — an abandoned vault, or one enrolled under
|
|
64
|
+
* another wallet identity. Never a way past the enrolled-serial refusal. */
|
|
65
|
+
acknowledgeUnrecognizedVaultKey?: true
|
|
66
|
+
scopeToken?: VaultScopeToken
|
|
67
|
+
nfcMessage?: string
|
|
68
|
+
onPhase?: (p: PivResetPhase) => void
|
|
69
|
+
}): Promise<void> {
|
|
70
|
+
const driver = getVaultDriver()
|
|
71
|
+
if (!driver) throw new VaultError('driver-unavailable')
|
|
72
|
+
if (args.acknowledgeDestroysAllCredentials !== true) {
|
|
73
|
+
throw new VaultError('template-invalid', 'Confirm that resetting destroys every credential on this YubiKey')
|
|
74
|
+
}
|
|
75
|
+
if (!isVaultSerial(args.serial)) {
|
|
76
|
+
throw new VaultError('template-invalid', 'Invalid YubiKey serial')
|
|
77
|
+
}
|
|
78
|
+
const scopeToken = args.scopeToken ?? vaultStore.captureScopeToken()
|
|
79
|
+
|
|
80
|
+
const refuse = async () => {
|
|
81
|
+
// Across every chain, and including a key mid-removal. See the header.
|
|
82
|
+
const enrolled = new Set<string>([
|
|
83
|
+
...(await vaultStore.enrolledSerialsAcrossChains(scopeToken)),
|
|
84
|
+
...(args.refuseSerials ?? [])
|
|
85
|
+
])
|
|
86
|
+
if (enrolled.has(args.serial)) {
|
|
87
|
+
// The message IS the serial, matching enrollKey's convention.
|
|
88
|
+
throw new VaultError('key-already-enrolled', args.serial, undefined, { serial: args.serial })
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Guard 1: before any card contact.
|
|
93
|
+
await refuse()
|
|
94
|
+
vaultStore.assertScopeToken(scopeToken)
|
|
95
|
+
|
|
96
|
+
await withKeySession(
|
|
97
|
+
driver,
|
|
98
|
+
async () => {
|
|
99
|
+
vaultStore.assertScopeToken(scopeToken)
|
|
100
|
+
const info = await driver.getKeyInfo()
|
|
101
|
+
if (info.serial !== args.serial) {
|
|
102
|
+
throw new VaultError('serial-mismatch', 'A different YubiKey was presented', undefined, {
|
|
103
|
+
tapped: info.serial,
|
|
104
|
+
chosen: args.serial
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
// Guard 2: re-read inside the session. Meta can change between the
|
|
108
|
+
// first check and the tap, and this is the last chance before an
|
|
109
|
+
// irreversible destruction.
|
|
110
|
+
await refuse()
|
|
111
|
+
vaultStore.assertScopeToken(scopeToken)
|
|
112
|
+
|
|
113
|
+
// Guard 3: the card's own answer, for the vaults no namespace on this
|
|
114
|
+
// device can show us. Reused code, not new copy: 'slot-occupied' is
|
|
115
|
+
// already enrollment's "slot 0x82 is not empty".
|
|
116
|
+
//
|
|
117
|
+
// `isVaultSlotOccupied`, never `readVaultPublicKey`: the latter returns a
|
|
118
|
+
// public KEY, and iOS cannot read a retired slot's certificate, so it
|
|
119
|
+
// answers null for every 0x82 — occupied or not. Asked that way this
|
|
120
|
+
// guard was a no-op on iOS and the whole consent below it unreachable
|
|
121
|
+
// there. Occupancy fails closed on both platforms: anything short of the
|
|
122
|
+
// card saying "no key here" counts as occupied and takes the consent.
|
|
123
|
+
if (args.acknowledgeUnrecognizedVaultKey !== true && (await driver.isVaultSlotOccupied(args.serial)).occupied) {
|
|
124
|
+
throw new VaultError(
|
|
125
|
+
'slot-occupied',
|
|
126
|
+
'This YubiKey already holds a vault key that belongs to no vault on this device',
|
|
127
|
+
undefined,
|
|
128
|
+
{ serial: args.serial }
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
vaultStore.assertScopeToken(scopeToken)
|
|
132
|
+
|
|
133
|
+
args.onPhase?.('resetting')
|
|
134
|
+
await driver.resetPivApplication(args.serial)
|
|
135
|
+
|
|
136
|
+
// The reset destroyed whatever partial state these described. Leaving
|
|
137
|
+
// them would refuse this key forever.
|
|
138
|
+
vaultStore.assertScopeToken(scopeToken)
|
|
139
|
+
await vaultStore.discardEnrollmentDraft(args.serial, scopeToken)
|
|
140
|
+
await vaultStore.discardEnrollmentQuarantine(args.serial, scopeToken)
|
|
141
|
+
},
|
|
142
|
+
() => args.onPhase?.('waiting'),
|
|
143
|
+
{ nfcMessage: args.nfcMessage }
|
|
144
|
+
)
|
|
145
|
+
}
|