@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.
Files changed (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. 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 an in-memory P-256 keypair, emulating the
5
- * behaviours the real ceremony must survive: PIN retries and lockout, touch
6
- * timeouts, and key removal mid-operation. ecdh mirrors the token's PIV
7
- * KeyAgreement (32-byte x-coordinate) so a seal produced against the mock's
8
- * public key unseals through the mock; signEcdsa emits DER exactly like both
9
- * real platforms. Together they let the whole vault stack run end-to-end
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 pin = DEFAULT_PIN
29
- private pinRetries = 3
30
- private pinVerified = false
60
+ private keys = new Map<string, MockKeyRecord>()
31
61
  private touch: TouchBehavior = 'instant'
32
- private slotPriv: Uint8Array | null = null
33
- private slotPub: string | null = null
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.pinRetries = 3
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 age-plugin-yubikey
69
- * identity in retired slot 82), so readVaultPublicKey reports it occupied
70
- * before any generate. */
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
- this.slotPriv = p256.utils.randomSecretKey()
73
- this.slotPub = Utils.toHex(Array.from(p256.getPublicKey(this.slotPriv, false)))
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 now the ceremony's
96
- // own mid-flight NFC retry loop) stay subscribed across a session-based
97
- // transport's stop/start cycles. Clearing here would silently break any
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
- this.requirePresent()
115
- if (this.pinRetries <= 0) throw new VaultError('pin-locked', 'PIN is blocked')
116
- if (pin === this.pin) {
117
- this.pinRetries = 3
118
- this.pinVerified = true
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
- this.pinRetries -= 1
122
- this.pinVerified = false
123
- return { ok: false, retriesLeft: this.pinRetries }
181
+ r.pinRetries -= 1
182
+ r.pinVerified = false
183
+ return { ok: false, retriesLeft: r.pinRetries }
124
184
  }
125
185
 
126
- async changePin(oldPin: string, newPin: string): Promise<{ ok: boolean; retriesLeft: number }> {
127
- this.requirePresent()
128
- if (this.pinRetries <= 0) throw new VaultError('pin-locked', 'PIN is blocked')
129
- if (oldPin !== this.pin) {
130
- this.pinRetries -= 1
131
- throw new VaultError('pin-invalid', 'Wrong PIN', this.pinRetries)
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
- this.pin = newPin
134
- this.pinRetries = 3
200
+ r.pin = newPin
201
+ r.pinRetries = 3
135
202
  return { ok: true, retriesLeft: 3 }
136
203
  }
137
204
 
138
- async generateVaultKey(_slot: number): Promise<{ publicKey: string }> {
139
- this.requirePresent()
140
- this.slotPriv = p256.utils.randomSecretKey()
141
- this.slotPub = Utils.toHex(Array.from(p256.getPublicKey(this.slotPriv, false)))
142
- return { publicKey: this.slotPub }
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 readVaultPublicKey(_slot: number): Promise<{ publicKey: string } | null> {
146
- this.requirePresent()
147
- return this.slotPub ? { publicKey: this.slotPub } : null
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
- /** Software stand-in for the card's PIV KeyAgreement (on-token ECDH) — the
151
- * touch-gated step that unwraps a sealed vault key (sealing.ts).
152
- *
153
- * pinPolicy=once: a prior verifyPin in this "session" satisfies it; if a
154
- * PIN is supplied here and not yet verified, verify it inline — and check
155
- * the result. A verifyPin call can fail (wrong PIN) without throwing; only
156
- * a locked PIN throws. Discarding that `{ ok: false }` and proceeding
157
- * anyway would make a wrong PIN indistinguishable from a correct one —
158
- * the same trap signEcdsa's inline verify once fell into.
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
- if (!this.slotPriv) throw new VaultError('no-key', 'No key in slot')
168
- if (this.touch === 'timeout') throw new VaultError('touch-timeout', 'Touch not detected')
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
- const secret = softwareEcdh(Utils.toHex(Array.from(this.slotPriv)), peerPublicKey)
171
- return { secret }
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, so
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: @noble/curves defaults P-256 signing
183
- * to low-S normalisation, but real YubiKey PIV hardware does not normalise
184
- * — roughly half of real signatures are high-S. A mock that only ever
185
- * emitted low-S signatures could not catch downstream code that mishandles
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(_slot: number, pin: string, digest: string): Promise<{ signature: string }> {
190
- this.requirePresent()
191
- if (!this.pinVerified) {
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
- const res = await this.verifyPin(pin)
194
- if (!res.ok) throw new VaultError('pin-invalid', 'Wrong PIN', res.retriesLeft)
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 (!this.slotPriv) throw new VaultError('no-key', 'No key in slot')
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), this.slotPriv, { prehash: false, lowS: false })
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
+ }