@bsv/expo-wallet-toolbox 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,46 +1,68 @@
1
1
  /**
2
- * Vault enrollment wizard — backup gate → passphrase → PIN → tap → done.
2
+ * Vault enrollment wizard — spec §3.3.
3
3
  *
4
- * The vault key is derived from the wallet's EXISTING mnemonic plus a vault
5
- * passphrase, so there is no second phrase to write down and no confirmation
6
- * quiz. What replaces them is the passphrase step: a strength meter, because
7
- * the KDF is only 2048 rounds, and a confirm field, because BIP39 passphrases
8
- * have no checksum and a typo silently opens a different, empty vault.
4
+ * enroll mode: intro → key (× k; sub-states pin · puk · tap · save · error) → more → done
5
+ * add-key mode: key → done
9
6
  *
10
- * enrollVault() drives the YubiKey (getKeyInfo → PIN → generate). Every prompt
11
- * is gathered BEFORE the tap, since the NFC sheet covers the app.
7
+ * Public, non-authoritative recovery handles are persisted in wallet-scoped
8
+ * SecureStore as soon as a slot key exists. Ready handles are restored into
9
+ * this wizard after a crash; protected handles repeat only a live possession
10
+ * challenge. PINs and PUKs are never stored. Every credential prompt is
11
+ * gathered BEFORE the tap, because
12
+ * the iOS NFC sheet covers the app for the whole card session. The PIN lives
13
+ * in input state only while its key step is open: it is kept across an
14
+ * error → Try again (a re-tap needs it) and cleared the moment the step is
15
+ * left, the card is swapped, or the PIN turns out to be wrong.
12
16
  *
13
- * The adopt step exists because slot occupancy is only knowable ON the card:
14
- * enrollVault refuses an occupied slot with 'slot-occupied', this wizard turns
15
- * that refusal into an explicit choice, and a second run with adoptExisting
16
- * enrolls against the key already there. That costs a second tap only in the
17
- * occupied case, which is what keeps the one-tap rule intact for the normal
18
- * one.
17
+ * A key is named on the user's behalf — Key 1, Key 2, … — and never asked
18
+ * about here: the name is cosmetic, it is renamed from the vault screen at any
19
+ * time, and a text field between a finished card and a saved key is one more
20
+ * thing to get wrong mid-ceremony.
21
+ *
22
+ * The host screen hides its own back chevron while this is mounted: leaving
23
+ * goes through `leave()` — the leave-confirm alert when at least one key is
24
+ * unsaved — which is also wired to Android's hardware back button. On the
25
+ * `done` step back completes the wizard (`onDone`) instead, and while a card
26
+ * session is open it is swallowed: the tap's outcome must land somewhere.
27
+ *
28
+ * Whatever meta is stored is loaded in BOTH modes and its serials are always
29
+ * passed to `enrollKey` as `pendingSerials` (spec §3.3 step 2). The service
30
+ * probes the slot and refuses any occupied token; enrollment never overwrites
31
+ * an existing PIV key. In enroll mode a stored meta is a host-state anomaly — its keys are
32
+ * refused (loud, safe) but never counted toward the ordinal or the cap, since
33
+ * Finish replaces whatever is stored.
19
34
  */
20
- import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'
21
- import { View, Text, StyleSheet, TextInput, ScrollView, ActivityIndicator } from 'react-native'
22
- import { PassphraseField } from './PassphraseField'
35
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
36
+ import { View, Text, StyleSheet, TextInput, ScrollView, ActivityIndicator, BackHandler, Platform } from 'react-native'
23
37
  import PressableScale from '../ui/PressableScale'
38
+ import { showAlert } from '../ui/AlertCard'
24
39
  import { showToast } from '../ui/Toast'
25
- import { printRecoveryShares } from '../../printRecoveryShares'
26
- import { PhraseBackupSheet } from './PhraseBackupSheet'
40
+ import { vaultErrorCopy } from './vaultErrorCopy'
41
+ import { vaultKeyLabel } from './KeyChooser'
27
42
  import {
28
43
  useTheme,
29
44
  spacing,
30
45
  radii,
31
46
  typography,
32
- enrollVault,
47
+ enrollKey,
48
+ resumeEnrollmentDraft,
33
49
  finalizeEnrollment,
50
+ addVaultKey,
51
+ resetPivApplication,
52
+ vaultStore,
53
+ VAULT_MIN_KEYS,
54
+ VAULT_MAX_KEYS,
34
55
  VaultError,
35
- useLocalStorage,
36
- sounds,
56
+ VaultEnrollmentPartialError,
37
57
  haptics,
58
+ randomBytes,
38
59
  i18n,
39
- readBackupAttestation,
40
- recordBackupAttestation,
41
- type BackupMedium,
42
- useWallet,
43
- UserContext
60
+ type VaultKeyRecord,
61
+ type VaultEnrollmentDraftEntry,
62
+ type VaultEnrollmentQuarantine,
63
+ type VaultScopeToken,
64
+ type VaultErrorCode,
65
+ type EnrollPhase
44
66
  } from '@bsv/expo-wallet-toolbox'
45
67
 
46
68
  const t = (k: string, o?: Record<string, unknown>) => i18n.t(k, o) as string
@@ -49,14 +71,11 @@ const t = (k: string, o?: Record<string, unknown>) => i18n.t(k, o) as string
49
71
  * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
50
72
  * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
51
73
  * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
52
- * Both icon sets are loaded lazily, only when actually rendering, same
53
- * pattern as this package's other native-module-boundary fixes (expo-router,
54
- * expo-blur).
74
+ * Loaded lazily, only when actually rendering, same pattern as this
75
+ * package's other native-module-boundary fixes.
55
76
  */
56
77
  type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
57
- type MaterialCommunityIconsComponent = typeof import('@expo/vector-icons').MaterialCommunityIcons
58
78
  let ioniconsComponent: IoniconsComponent | undefined
59
- let materialCommunityIconsComponent: MaterialCommunityIconsComponent | undefined
60
79
  function loadIonicons(): IoniconsComponent {
61
80
  if (!ioniconsComponent) {
62
81
  // eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -64,510 +83,1459 @@ function loadIonicons(): IoniconsComponent {
64
83
  }
65
84
  return ioniconsComponent
66
85
  }
67
- function loadMaterialCommunityIcons(): MaterialCommunityIconsComponent {
68
- if (!materialCommunityIconsComponent) {
69
- materialCommunityIconsComponent = require('@expo/vector-icons')
70
- // eslint-disable-next-line @typescript-eslint/no-require-imports
71
- .MaterialCommunityIcons as MaterialCommunityIconsComponent
86
+
87
+ type Step = 'intro' | 'key' | 'more' | 'done'
88
+ type KeySub = 'pin' | 'puk' | 'tap' | 'save' | 'reset' | 'error'
89
+
90
+ /** Pages a single key's setup walks through, for the progress indicator. The
91
+ * count is per key, not per wizard: the number of keys is chosen during the
92
+ * run (2 to 5), so a whole-wizard bar would move at a rate nobody can predict.
93
+ * `save` is not one of them: it is a write, not a page the user works through. */
94
+ const KEY_STEPS: readonly KeySub[] = ['pin', 'puk', 'tap']
95
+
96
+ /** The PIV factory codes. The intro's whole-PIV acknowledgement asserts a
97
+ * factory-reset (or Vault-dedicated) PIV application, so these are supplied to
98
+ * the service below the UI rather than typed. */
99
+ const DEFAULT_PIV_PIN = '123456'
100
+ const DEFAULT_PIV_PUK = '12345678'
101
+ const PIN_MAX = 8
102
+ const pivCodeOk = (p: string) => /^[0-9]{6,8}$/.test(p)
103
+
104
+ const PUK_LENGTH = 8
105
+
106
+ /**
107
+ * A fresh recovery code (PIV PUK) for one key.
108
+ *
109
+ * Rejection sampling, not `byte % 10`: a modulo over 256 would make the digits
110
+ * 0-5 measurably likelier than 6-9. Bytes of 250 or more are discarded.
111
+ *
112
+ * The service refuses a PUK equal to the PIN (validatePukChange), so a
113
+ * collision is redrawn rather than surfaced as a validation error.
114
+ */
115
+ function generateRecoveryCode(pin: string): string {
116
+ for (;;) {
117
+ let code = ''
118
+ while (code.length < PUK_LENGTH) {
119
+ for (const byte of randomBytes(PUK_LENGTH)) {
120
+ if (byte >= 250) continue
121
+ code += String(byte % 10)
122
+ if (code.length === PUK_LENGTH) break
123
+ }
124
+ }
125
+ if (code !== DEFAULT_PIV_PUK && code !== pin) return code
72
126
  }
73
- return materialCommunityIconsComponent
74
127
  }
75
128
 
76
- type Step = 'backup' | 'phrase' | 'passphrase' | 'adopt' | 'running' | 'done'
129
+ interface KeyStepError {
130
+ code: VaultErrorCode | undefined
131
+ copy: string
132
+ /** Generation may have completed, so retrying on this token must not reach
133
+ * another enrollment attempt. The service will also refuse its occupied
134
+ * slot; the UI sends the user straight to a fresh token. */
135
+ mustUseDifferent?: boolean
136
+ /**
137
+ * The card THIS failure may offer to erase, or absent for no offer.
138
+ *
139
+ * Deliberately a field of the error and not separate state. A reset offer
140
+ * bound to the wrong card is the worst outcome in this feature, and separate
141
+ * state survives whatever the code forgets to clear: every exit from the
142
+ * error page would have to remember, and nothing enforces that. Living here,
143
+ * the binding is replaced wholesale every time a failure is recorded and
144
+ * disappears with `setKeyError(null)` — a stale serial cannot outlive the
145
+ * failure that produced it.
146
+ */
147
+ resetSerial?: string
148
+ }
149
+
150
+ /**
151
+ * The duplicate's serial from a key-already-enrolled rejection. The services
152
+ * attach it as `details.serial` (VaultKeyService.enrollKey, vaultStore.addKey);
153
+ * the message is never parsed for it.
154
+ */
155
+ function duplicateSerial(err: VaultError | undefined): string | undefined {
156
+ const s = err?.details?.serial
157
+ return typeof s === 'string' ? s : undefined
158
+ }
159
+
160
+ /**
161
+ * Codes a PIV reset can actually fix — a card that has been used before and
162
+ * whose PIV application is therefore not the factory one enrollment needs.
163
+ */
164
+ const RESETTABLE: ReadonlySet<VaultErrorCode> = new Set<VaultErrorCode>([
165
+ 'mgmt-key-custom',
166
+ 'slot-occupied',
167
+ 'pin-invalid',
168
+ 'puk-invalid',
169
+ 'pin-locked',
170
+ 'puk-locked',
171
+ 'enrollment-partial'
172
+ ])
173
+
174
+ /**
175
+ * Never offered a reset, whatever RESETTABLE comes to say.
176
+ *
177
+ * `key-already-enrolled` is a LIVE vault signer: erasing it removes one of the
178
+ * k-of-n keys and can make vault funds permanently unspendable. pivReset
179
+ * refuses it below the UI too, and that refusal is not overridable — but the
180
+ * UI must never invite the attempt in the first place.
181
+ *
182
+ * `attestation-invalid` means the factory F9 chain did not verify, i.e. the
183
+ * token is counterfeit or tampered with. A reset changes nothing about that,
184
+ * so offering one would tell the user a lie about what would fix their key.
185
+ */
186
+ const NEVER_RESETTABLE: ReadonlySet<VaultErrorCode> = new Set<VaultErrorCode>([
187
+ 'key-already-enrolled',
188
+ 'attestation-invalid'
189
+ ])
190
+
191
+ /**
192
+ * Codes whose retry can never succeed, so the error page must send the token
193
+ * away instead of offering a Try again that is a dead button.
194
+ *
195
+ * `pin-invalid` (Task 8): the app supplies the factory PIN, so this means the
196
+ * PIV application is not the factory one — presenting 123456 again can only
197
+ * fail, three times over into `pin-locked`.
198
+ *
199
+ * `mgmt-key-custom`: the management key is not the factory one either, and
200
+ * nothing about a re-tap changes that.
201
+ *
202
+ * `attestation-invalid`: the factory F9 chain did not verify. The token is
203
+ * counterfeit or tampered with, and `vault_err_attestation_invalid` already
204
+ * tells the user to fetch a genuine key — a Retry button underneath it
205
+ * contradicts the very copy above it.
206
+ *
207
+ * `pin-locked`: raised from `info.pinRetries === 0`, read off the card before
208
+ * anything is presented to it. A re-tap re-reads the same zero — only the PUK
209
+ * or a factory reset moves that counter — so a Retry here is the same dead
210
+ * button as the three above, and a worse one, because [Reset this key] renders
211
+ * directly over it.
212
+ *
213
+ * A reset offer, where one is allowed at all, renders ABOVE this branch: a
214
+ * card with a known serial gets [Reset this key] + [Use a different YubiKey],
215
+ * which is the right pair. A counterfeit gets only the latter, because
216
+ * `attestation-invalid` is in NEVER_RESETTABLE.
217
+ */
218
+ const MUST_USE_DIFFERENT: ReadonlySet<VaultErrorCode> = new Set<VaultErrorCode>([
219
+ 'pin-invalid',
220
+ 'mgmt-key-custom',
221
+ 'attestation-invalid',
222
+ 'pin-locked'
223
+ ])
224
+
225
+ /**
226
+ * Rejections from `resetPivApplication` that are provably raised BEFORE the
227
+ * RESET APDU, so their own copy is truthful about the card being untouched.
228
+ *
229
+ * Everything else has to warn instead of reassure: a scope change or an NFC
230
+ * lift after the erase rejects on a card that is already at factory state
231
+ * (`scope-changed`, `key-removed-mid-op`, `nfc-lost`, and `template-invalid`
232
+ * from the post-reset draft/quarantine cleanup), and no code distinguishes
233
+ * that from a refusal before contact.
234
+ *
235
+ * `driver-unavailable` is deliberately NOT a member, even though pivReset does
236
+ * raise it before contact when no driver is installed. It is also
237
+ * `vaultErrorFromNative`'s fallback for ANY native rejection that is not a
238
+ * `VAULT_ERR:` string (types.ts), so a bridge or serialization failure AFTER
239
+ * the RESET APDU landed arrives under this same code. It is the one candidate
240
+ * that can hedge in the unsafe direction — telling the user nothing was erased
241
+ * when the key is already blank — so it takes the warning copy instead.
242
+ */
243
+ const RESET_BEFORE_ERASE: ReadonlySet<VaultErrorCode> = new Set<VaultErrorCode>([
244
+ 'key-already-enrolled',
245
+ 'slot-occupied',
246
+ 'serial-mismatch',
247
+ 'user-cancelled'
248
+ ])
77
249
 
78
- interface PinRequest {
79
- kind: 'pin' | 'change'
80
- retries?: number
81
- resolve: (v: any) => void
82
- reject: (e: unknown) => void
250
+ export interface EnrollWizardProps {
251
+ mode: 'enroll' | 'add-key'
252
+ onDone: () => void
253
+ onCancel: () => void
83
254
  }
84
255
 
85
- export const EnrollWizard: React.FC<{ onDone: () => void; onCancel: () => void }> = ({
86
- onDone,
87
- onCancel
88
- }) => {
256
+ export const EnrollWizard: React.FC<EnrollWizardProps> = ({ mode, onDone, onCancel }) => {
89
257
  const { colors } = useTheme()
90
258
  const Ionicons = loadIonicons()
91
- const MaterialCommunityIcons = loadMaterialCommunityIcons()
92
- const { getMnemonic, getRecoveredKey } = useLocalStorage()
93
- const { appName } = useContext(UserContext)
94
- const [step, setStep] = useState<Step>('backup')
95
- const [medium, setMedium] = useState<BackupMedium | null>(null)
96
- const [wordCount, setWordCount] = useState<number | null>(null)
97
- const [revealed, setRevealed] = useState<string | null>(null)
98
- const [passphrase, setPassphrase] = useState('')
99
- const [confirm, setConfirm] = useState('')
100
- const [passphraseOk, setPassphraseOk] = useState(false)
101
- const [phaseLabel, setPhaseLabel] = useState('')
102
- const [pinReq, setPinReq] = useState<PinRequest | null>(null)
259
+ // Every public record collected in this wizard belongs to the wallet/chain
260
+ // scope that opened it. Holding one token for the whole lifetime prevents a
261
+ // late enrollment result from being persisted after logout or a network
262
+ // switch has mounted a different vault.
263
+ const scopeTokenRef = useRef<VaultScopeToken | null>(null)
264
+ if (!scopeTokenRef.current) scopeTokenRef.current = vaultStore.captureScopeToken()
265
+ const scopeToken = scopeTokenRef.current
266
+
267
+ const [step, setStep] = useState<Step>(mode === 'enroll' ? 'intro' : 'key')
268
+ const [sub, setSub] = useState<KeySub>('pin')
269
+ const [ack, setAck] = useState(false)
270
+ /** Whole-PIV acknowledgement. Enrollment rotates global PIV credentials,
271
+ * so this starts false even when the recovery-risk acknowledgement is set. */
272
+ const [pivAck, setPivAck] = useState(false)
273
+ /** Keys already in the stored meta, loaded in both modes. Their serials are
274
+ * always refused; they count toward the ordinal and the cap in add-key mode
275
+ * only (see the file comment). */
276
+ const [metaKeys, setMetaKeys] = useState<VaultKeyRecord[]>([])
277
+ /** Keys set up in this run and not yet persisted. Public data only. */
278
+ const [pending, setPending] = useState<VaultKeyRecord[]>([])
279
+ const [recoverableDrafts, setRecoverableDrafts] = useState<VaultEnrollmentDraftEntry[]>([])
280
+ const [blockedDrafts, setBlockedDrafts] = useState<(VaultEnrollmentDraftEntry | VaultEnrollmentQuarantine)[]>([])
281
+ /** The PIN the user chose for this key. The factory PIN is supplied to the
282
+ * service below the UI, never typed. */
283
+ const [newPin, setNewPin] = useState('')
284
+ const [confirmPin, setConfirmPin] = useState('')
285
+ /** The generated recovery code for this key. Created when the PUK page is
286
+ * first shown and cleared with the rest of the key's inputs. */
287
+ const [newPuk, setNewPuk] = useState('')
288
+ const [pukAck, setPukAck] = useState(false)
103
289
  const [pinError, setPinError] = useState<string | null>(null)
104
- const [pinInput, setPinInput] = useState('')
105
- const [newPinInput, setNewPinInput] = useState('')
106
- const [printing, setPrinting] = useState(false)
107
- const [error, setError] = useState<string | null>(null)
290
+ const [phase, setPhase] = useState<EnrollPhase | null>(null)
291
+ /** The record the card produced, while its write to the vault is in flight
292
+ * or has failed and can be retried. */
293
+ const [fresh, setFresh] = useState<VaultKeyRecord | null>(null)
294
+ const [keyError, setKeyError] = useState<KeyStepError | null>(null)
295
+ /** "This erases everything on this key" — the whole-token consequence. */
296
+ const [resetAck, setResetAck] = useState(false)
297
+ /** The card answered that its Vault slot holds a key no vault on this device
298
+ * claims. Set only by pivReset's own refusal, never guessed from the
299
+ * enrollment error: it is the card, not the app, that knows. */
300
+ const [resetUnknownSlot, setResetUnknownSlot] = useState(false)
301
+ /** The separate consent that unknown key may be destroyed. */
302
+ const [resetUnknownAck, setResetUnknownAck] = useState(false)
303
+ const [resetting, setResetting] = useState(false)
304
+ /** A write (finalizeEnrollment / addVaultKey) is in flight. */
305
+ const [busy, setBusy] = useState(false)
306
+ const [stepError, setStepError] = useState<string | null>(null)
307
+ const [addedNickname, setAddedNickname] = useState('')
308
+ /** One card session at a time: a double-tapped Continue must not open two. */
309
+ const tapInFlight = useRef(false)
310
+ /** One leave-confirm at a time. */
311
+ const leaving = useRef(false)
312
+ /** The PIN field, focused on a delay below instead of via `autoFocus`. */
313
+ const pinInputRef = useRef<TextInput>(null)
108
314
 
109
- const { managers, adminOriginator } = useWallet()
315
+ /** Stored keys that count toward the ordinal and the 5-key cap: all of them
316
+ * when adding to a vault, none while enrolling one (Finish overwrites). */
317
+ const enrolledCount = mode === 'add-key' ? metaKeys.length : 0
318
+ const total = enrolledCount + pending.length
319
+ /** Ordinal of the next key on screen. Existing/occupied tokens are never overwritten. */
320
+ const k = total + 1
321
+ const pinChosen = pivCodeOk(newPin) && newPin !== DEFAULT_PIV_PIN
322
+ const pinOk = pinChosen && confirmPin === newPin
323
+ /** Keys that would be lost by leaving: pending ones plus a just-generated, not-yet-named one. */
324
+ const unsaved = pending.length + (fresh ? 1 : 0)
110
325
 
111
- const wallet = managers?.permissionsManager
326
+ /**
327
+ * The ticks the reset page gathered. Consent is destructive and specific: it
328
+ * is never carried from one card to the next, nor from one attempt to the
329
+ * next. (The card it is consent ABOUT lives on `keyError.resetSerial`, which
330
+ * cannot go stale — see KeyStepError.)
331
+ */
332
+ const clearResetConsent = () => {
333
+ setResetAck(false)
334
+ setResetUnknownSlot(false)
335
+ setResetUnknownAck(false)
336
+ }
112
337
 
113
- // A user who already backed up should not be asked twice — including the
114
- // user who wrote their phrase down during wallet creation minutes ago, which
115
- // now records an attestation of its own. Skipping the step outright rather
116
- // than showing it pre-ticked: a screen full of green ticks is still a
117
- // checkpoint to read and clear.
118
- useEffect(() => {
119
- let alive = true
120
- void (async () => {
121
- const existing = await readBackupAttestation(wallet, adminOriginator)
122
- if (!alive || !existing) return
123
- setMedium(existing.medium)
124
- // Straight to the passphrase. The mnemonic guard that toPassphrase runs
125
- // is skipped on this path on purpose — it calls getMnemonic(), which is
126
- // biometric-gated, and prompting for Face ID on mount would be worse than
127
- // surfacing 'requires mnemonic' when enrolment actually starts.
128
- setStep(current => (current === 'backup' ? 'passphrase' : current))
129
- })()
130
- return () => {
131
- alive = false
132
- }
133
- }, [wallet, adminOriginator])
338
+ /** Everything the key step gathered: the chosen PIN, its confirmation, the
339
+ * generated recovery code and its acknowledgement, and the fresh record. */
340
+ const clearKeyInputs = () => {
341
+ setNewPin('')
342
+ setConfirmPin('')
343
+ setNewPuk('')
344
+ setPukAck(false)
345
+ setPinError(null)
346
+ setFresh(null)
347
+ clearResetConsent()
348
+ }
134
349
 
350
+ // ── saving a finished key ───────────────────────────────────────────
135
351
  /**
136
- * Only a persisted attestation may unlock Continue. A wallet that ticks the
137
- * row without a written flag would enrol into a vault the deposit gate then
138
- * refuses forever, since the gate would find nothing recorded.
352
+ * Persist the key a card just produced, under the default name for its
353
+ * ordinal when the record carries none.
354
+ *
355
+ * The user is never asked for a name: a key is Key 1, Key 2, … and is
356
+ * renamed from the vault screen whenever they care to. In enroll mode this
357
+ * is a push into `pending` (nothing is written until Finish); in add-key
358
+ * mode it is the vault write, which can fail — hence the `save` page, whose
359
+ * only job is that failure and its retry.
139
360
  */
140
- const attest = useCallback(
141
- async (m: BackupMedium): Promise<boolean> => {
142
- if (!(await recordBackupAttestation(wallet, adminOriginator, m))) {
143
- setError(t('vault_backup_attest_failed'))
144
- return false
361
+ const saveKey = useCallback(
362
+ async (produced: VaultKeyRecord) => {
363
+ const record: VaultKeyRecord = {
364
+ ...produced,
365
+ nickname: produced.nickname.trim() || t('vault_name_default', { k })
366
+ }
367
+ if (mode !== 'add-key') {
368
+ setPending(prev => [...prev, record])
369
+ clearKeyInputs()
370
+ setStep('more')
371
+ return
372
+ }
373
+ setFresh(record)
374
+ setSub('save')
375
+ setBusy(true)
376
+ setStepError(null)
377
+ try {
378
+ await addVaultKey(record, scopeToken)
379
+ clearKeyInputs()
380
+ haptics.success()
381
+ showToast(t('vault_key_added_toast'), { type: 'success' })
382
+ setAddedNickname(record.nickname)
383
+ setStep('done')
384
+ } catch (e) {
385
+ haptics.error()
386
+ const err = e instanceof VaultError ? e : undefined
387
+ if (err?.code === 'scope-changed') {
388
+ clearKeyInputs()
389
+ showToast(vaultErrorCopy('scope-changed'), { type: 'error' })
390
+ onCancel()
391
+ return
392
+ }
393
+ // `fresh` is also a scoped ready draft. Keep it and stay on the save
394
+ // page so a transient SecureStore write failure can be retried without
395
+ // touching or regenerating the now-occupied token.
396
+ setStepError(vaultErrorCopy(err?.code))
397
+ } finally {
398
+ setBusy(false)
145
399
  }
146
- setError(null)
147
- setMedium(m)
148
- return true
149
400
  },
150
- [wallet, adminOriginator]
401
+ [k, mode, onCancel, scopeToken]
151
402
  )
152
403
 
153
- const requestPin = useCallback(
154
- () => new Promise<string>((resolve, reject) => setPinReq({ kind: 'pin', resolve, reject })),
155
- []
156
- )
157
- const requestPinChange = useCallback(
158
- (retries: number) =>
159
- new Promise<{ oldPin: string; newPin: string }>((resolve, reject) =>
160
- setPinReq({ kind: 'change', retries, resolve, reject })
161
- ),
162
- []
163
- )
404
+ /**
405
+ * Always the current `saveKey`, for the restore below to call.
406
+ *
407
+ * Depending on `saveKey` directly would re-run that effect whenever the
408
+ * ordinal it names keys after moves — and that ordinal comes from the very
409
+ * state the effect sets, so a restored draft could be written twice.
410
+ */
411
+ const saveKeyRef = useRef(saveKey)
412
+ useEffect(() => {
413
+ saveKeyRef.current = saveKey
414
+ }, [saveKey])
164
415
 
165
- const onPrintShares = useCallback(async () => {
166
- if (printing) return
167
- setPrinting(true)
168
- try {
169
- const result = await printRecoveryShares({
170
- mnemonic: await getMnemonic(),
171
- recoveredKeyWif: await getRecoveredKey?.(),
172
- appName
416
+ useEffect(() => {
417
+ let alive = true
418
+ Promise.all([
419
+ vaultStore.getMeta(scopeToken),
420
+ vaultStore.getEnrollmentDrafts(scopeToken),
421
+ vaultStore.getEnrollmentQuarantines(scopeToken)
422
+ ])
423
+ .then(([m, drafts, quarantines]) => {
424
+ if (!alive) return
425
+ const enrolledSerials = new Set(m?.keys.map(key => key.serial) ?? [])
426
+ const unused = drafts.filter(entry => !enrolledSerials.has(entry.record.serial))
427
+ const ready = unused.filter(entry => entry.assurance === 'ready')
428
+ const challenge = unused.filter(entry => entry.assurance === 'challenge-required')
429
+ const blocked = unused.filter(entry => entry.assurance === 'management-uncertain')
430
+ if (m) setMetaKeys(m.keys)
431
+ setRecoverableDrafts(challenge)
432
+ setBlockedDrafts([...blocked, ...quarantines])
433
+ if (mode === 'enroll') {
434
+ setPending(current => {
435
+ const serials = new Set(current.map(key => key.serial))
436
+ return [...current, ...ready.map(entry => entry.record).filter(record => !serials.has(record.serial))]
437
+ })
438
+ } else if (ready[0]) {
439
+ // A ready draft's card already holds its key, and its name was
440
+ // settled when it was drafted: there is nothing left to ask, so
441
+ // restoring it means writing it.
442
+ void saveKeyRef.current(ready[0].record)
443
+ }
173
444
  })
174
- if (result.ok) {
175
- // Only a resolved print sheet counts. A cancelled one produced no paper.
176
- await attest('shares')
177
- } else if (result.reason === 'unsupported-word-count') {
178
- showToast(t('vault_shares_word_count'), { type: 'error' })
179
- } else {
180
- showToast(t('vault_shares_unavailable'), { type: 'error' })
181
- }
182
- } catch {
183
- // Print sheet dismissed or unavailable — not an error worth blocking on.
184
- } finally {
185
- setPrinting(false)
445
+ .catch(e => {
446
+ if (alive && e instanceof VaultError && e.code === 'scope-changed') onCancel()
447
+ })
448
+ return () => {
449
+ alive = false
186
450
  }
187
- }, [printing, getMnemonic, getRecoveredKey, attest])
188
-
189
- const onRevealPhrase = useCallback(async () => {
190
- setError(null)
191
- // getMnemonic() is behind the biometric latch, so the reveal is
192
- // re-authenticated without a second prompt of our own.
193
- const mnemonic = await getMnemonic()
194
- if (!mnemonic) {
195
- setError(t('vault_requires_mnemonic'))
196
- haptics.error()
451
+ }, [mode, onCancel, scopeToken])
452
+
453
+ // ── leaving ─────────────────────────────────────────────────────────
454
+ const leave = useCallback(async () => {
455
+ // Everything is saved on `done`: back means the same as the Done button —
456
+ // hand off to the host (the re-lock prompt in add-key mode), never a
457
+ // "won't be saved yet" alert over a persisted vault.
458
+ if (step === 'done') {
459
+ onDone()
197
460
  return
198
461
  }
199
- setWordCount(mnemonic.trim().split(/\s+/).length)
200
- setRevealed(mnemonic)
201
- setStep('phrase')
202
- }, [getMnemonic])
203
-
204
- // Gate: a wallet restored from backup shares has no mnemonic, so it can
205
- // neither enroll nor ever recover a vault. Refuse rather than create a vault
206
- // with only one recovery path.
207
- const toPassphrase = useCallback(async () => {
208
- setError(null)
209
- const mnemonic = await getMnemonic()
210
- if (!mnemonic) {
211
- setError(t('vault_requires_mnemonic'))
212
- haptics.error()
213
- return
462
+ // A card session is open: its result must land in state, so back is
463
+ // swallowed (the BackHandler handler still returns true) until it settles.
464
+ if (tapInFlight.current) return
465
+ if (busy || leaving.current) return
466
+ leaving.current = true
467
+ try {
468
+ if (unsaved > 0) {
469
+ const choice = await showAlert({
470
+ title: t('vault_leave_title'),
471
+ message: t('vault_leave_body', { count: unsaved }),
472
+ buttons: [
473
+ { text: t('vault_leave_confirm'), key: 'leave', style: 'destructive' },
474
+ { text: t('vault_leave_stay'), key: 'stay', style: 'cancel' }
475
+ ]
476
+ })
477
+ if (choice !== 'leave') return
478
+ }
479
+ onCancel()
480
+ } finally {
481
+ leaving.current = false
214
482
  }
215
- setStep('passphrase')
216
- }, [getMnemonic])
483
+ }, [step, busy, unsaved, onCancel, onDone])
217
484
 
218
- /** Set to `start` below; the wrong-PIN path re-enters the ceremony. */
219
- const startRef = useRef<((adoptExisting?: boolean) => Promise<void>) | null>(null)
485
+ useEffect(() => {
486
+ const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
487
+ void leave()
488
+ return true
489
+ })
490
+ return () => subscription.remove()
491
+ }, [leave])
492
+
493
+ // Focus the PIN field on a delay rather than via `autoFocus`, which grabs
494
+ // focus before this step's mount/layout settles and drops the first
495
+ // keystroke (see the matching fix + comment in VaultCeremonySheet).
496
+ useEffect(() => {
497
+ if (step !== 'key' || sub !== 'pin') return
498
+ const timer = setTimeout(() => pinInputRef.current?.focus(), 150)
499
+ return () => clearTimeout(timer)
500
+ }, [step, sub])
220
501
 
221
- const start = useCallback(async (adoptExisting = false) => {
222
- setStep('running')
223
- setError(null)
502
+ // ── intro → key 1 ───────────────────────────────────────────────────
503
+ const begin = useCallback(() => {
504
+ if (!ack || !pivAck || busy) return
505
+ vaultStore.assertScopeToken(scopeToken)
506
+ setStep(pending.length > 0 ? 'more' : 'key')
507
+ if (pending.length === 0) setSub('pin')
508
+ }, [ack, pivAck, busy, pending.length, scopeToken])
509
+
510
+ /**
511
+ * Re-read the scoped draft and quarantine LISTS, and only those.
512
+ *
513
+ * The mount effect also folds ready drafts into `pending` (or into `fresh`
514
+ * plus a jump to the name page in add-key mode); doing that again mid-run
515
+ * would move the page out from under the user. What has to stay current is
516
+ * what the wizard believes this device still holds a record of: a partial
517
+ * enrollment writes a new draft or quarantine during the run, and a reset
518
+ * deletes one (pivReset's discardEnrollmentDraft / ...Quarantine). Both
519
+ * change what the user must be told before erasing a card, and a stale list
520
+ * also leaves a Resume button pointing at a key that no longer exists.
521
+ */
522
+ const reloadDraftLists = useCallback(async () => {
224
523
  try {
225
- const mnemonic = await getMnemonic()
226
- if (!mnemonic) throw new VaultError('bad-mnemonic', t('vault_requires_mnemonic'))
227
- const { pending } = await enrollVault({
228
- // Empty by design: the vault screen identifies the key by its serial,
229
- // which the key itself reports. A nickname field was one more thing to
230
- // fill in during setup and named nothing the user could not already see.
231
- nickname: '',
232
- mnemonic,
233
- passphrase,
234
- adoptExisting,
235
- onPhase: p => setPhaseLabel(t(`vault_enroll_phase_${p}`)),
236
- getPin: requestPin,
237
- requestPinChange
238
- })
239
- await finalizeEnrollment(pending)
240
- setPassphrase('')
241
- setConfirm('')
242
- sounds.vaultOpen()
524
+ const [meta, drafts, quarantines] = await Promise.all([
525
+ vaultStore.getMeta(scopeToken),
526
+ vaultStore.getEnrollmentDrafts(scopeToken),
527
+ vaultStore.getEnrollmentQuarantines(scopeToken)
528
+ ])
529
+ const enrolledSerials = new Set(meta?.keys.map(key => key.serial) ?? [])
530
+ const unused = drafts.filter(entry => !enrolledSerials.has(entry.record.serial))
531
+ setRecoverableDrafts(unused.filter(entry => entry.assurance === 'challenge-required'))
532
+ setBlockedDrafts([...unused.filter(entry => entry.assurance === 'management-uncertain'), ...quarantines])
533
+ } catch {
534
+ // Advisory only. These lists drive what the user is TOLD; every action
535
+ // taken on them (resume, reset) re-reads the store below the UI, so a
536
+ // failed refresh degrades to the previous lists rather than to a wrong
537
+ // decision.
538
+ }
539
+ }, [scopeToken])
540
+
541
+ // ── the card session ────────────────────────────────────────────────
542
+ const runTap = useCallback(
543
+ async (replaceOccupiedVaultSlot = false) => {
544
+ if (tapInFlight.current || !pivAck) return
545
+ tapInFlight.current = true
546
+ setSub('tap')
547
+ setPhase(null)
548
+ setKeyError(null)
549
+ setStepError(null)
550
+ clearResetConsent()
551
+ // Stored ∪ pending, in every mode: the service refuses these BEFORE it
552
+ // spends the PIN or regenerates the slot (spec §3.3 step 2).
553
+ const known = [...metaKeys.map(r => r.serial), ...pending.map(r => r.serial)]
554
+ try {
555
+ const record = await enrollKey({
556
+ scopeToken,
557
+ acknowledgeDedicatedPivApplication: true,
558
+ pendingSerials: known,
559
+ nickname: t('vault_name_default', { k }),
560
+ // TEMP DIAG: the phase stream says how far the card session got.
561
+ onPhase: p => {
562
+ if (__DEV__) console.log(`[vault][diag] phase=${p}`)
563
+ setPhase(p)
564
+ },
565
+ // The intro's whole-PIV acknowledgement already asserts a
566
+ // factory-reset, dedicated PIV application, and preflight
567
+ // authenticates the factory management key before any mutation. So
568
+ // the factory PIN and PUK are ours to supply; making the user type
569
+ // '123456' was ceremony, not security.
570
+ getPin: async () => DEFAULT_PIV_PIN,
571
+ requestPinChange: async () => ({ oldPin: DEFAULT_PIV_PIN, newPin }),
572
+ requestPukChange: async () => ({ oldPuk: DEFAULT_PIV_PUK, newPuk }),
573
+ // Localised iOS NFC sheet text for this tap (enrollKey forwards it to
574
+ // withKeySession → driver.start). Omitting it would fall back to the
575
+ // native default wording.
576
+ nfcMessage: t('vault_nfc_enroll_message'),
577
+ replaceOccupiedVaultSlot
578
+ })
579
+ haptics.success()
580
+ await saveKey(record)
581
+ } catch (e) {
582
+ haptics.error()
583
+ // TEMP DIAG: the real error behind whatever copy the screen shows.
584
+ if (__DEV__) {
585
+ const ve = e instanceof VaultError ? e : undefined
586
+ console.log(
587
+ `[vault][diag] enrollKey threw code=${ve?.code ?? '(not VaultError)'} name=${
588
+ (e as Error)?.name
589
+ } msg=${JSON.stringify((e as Error)?.message)} details=${JSON.stringify(ve?.details)} cause=${JSON.stringify(
590
+ (() => {
591
+ const c = (e as { cause?: unknown })?.cause
592
+ if (!c) return null
593
+ const cv = c instanceof VaultError ? c : undefined
594
+ return {
595
+ code: cv?.code,
596
+ name: (c as Error)?.name,
597
+ message: (c as Error)?.message,
598
+ retriesLeft: cv?.retriesLeft
599
+ }
600
+ })()
601
+ )}`
602
+ )
603
+ }
604
+ try {
605
+ vaultStore.assertScopeToken(scopeToken)
606
+ } catch {
607
+ clearKeyInputs()
608
+ showToast(vaultErrorCopy('scope-changed'), { type: 'error' })
609
+ onCancel()
610
+ return
611
+ }
612
+ const err = e instanceof VaultError ? e : undefined
613
+ // The user dismissed the system NFC sheet: not an error to explain.
614
+ // Everything gathered stays, and the page that starts the tap is the
615
+ // recovery-code one, so Continue can simply be pressed again.
616
+ if (err?.code === 'user-cancelled') {
617
+ setSub('puk')
618
+ return
619
+ }
620
+ // Every partial personalization result is represented by a durable
621
+ // scoped draft or quarantine. Never guess which global PIV credential
622
+ // is current and never re-enter generic enrollment on the same token;
623
+ // a challenge-required draft is resumed through the explicit path
624
+ // loaded above after reconnect/reopen.
625
+ const tapped = duplicateSerial(err)
626
+ const dupPending = tapped ? pending.find(p => p.serial === tapped) : undefined
627
+ const dupEnrolled = tapped ? metaKeys.find(p => p.serial === tapped) : undefined
628
+ let copy: string
629
+ if (err?.code === 'key-already-enrolled') {
630
+ // Name the duplicate; with no record to name, the serial tail still
631
+ // identifies the card. Without even a serial the copy degrades to the
632
+ // generic line inside vaultErrorCopy.
633
+ copy = vaultErrorCopy(err.code, {
634
+ nickname: dupPending?.nickname ?? dupEnrolled?.nickname ?? (tapped ? `…${tapped.slice(-4)}` : undefined)
635
+ })
636
+ } else if (err?.code === 'pin-locked') {
637
+ // Enrolment-specific: there is no "use another of your vault keys"
638
+ // yet, so the remedy is the PUK or a different card.
639
+ copy = t('vault_err_pin_locked_enroll')
640
+ } else if (err?.code === 'pin-invalid') {
641
+ // The factory PIN is supplied below the UI, so this is never "you
642
+ // mistyped": the card's PIV PIN is not 123456, i.e. the application
643
+ // is not the factory-reset one the acknowledgement claimed. Retrying
644
+ // would present 123456 again — it can only fail, and three of them
645
+ // reach pin-locked on a PIV application that may hold unrelated
646
+ // credentials. So this token is sent away rather than retried, and
647
+ // the retry count is dropped: it means nothing when the app, not the
648
+ // user, picks the PIN. The reset copy is literally true here, and is
649
+ // where the reset offer attaches.
650
+ copy = t('vault_enrollment_reset_required')
651
+ } else if (err instanceof VaultEnrollmentPartialError) {
652
+ // Deliberately the hedged copy, not the reset-required one. enrollKey
653
+ // throws this carrying any stage, including `pin-change-uncertain` —
654
+ // which VaultKeyService records BEFORE calling changePin, so a process
655
+ // death in that window leaves a card that may still be at factory
656
+ // state. Claiming it is not would be a lie in that case. The remedy
657
+ // is the same either way, so the copy states the uncertainty instead
658
+ // of guessing past it.
659
+ copy = t('vault_enrollment_state_uncertain')
660
+ } else {
661
+ copy = vaultErrorCopy(err?.code)
662
+ }
663
+ setKeyError({
664
+ code: err?.code,
665
+ copy,
666
+ mustUseDifferent: err instanceof VaultEnrollmentPartialError || (!!err && MUST_USE_DIFFERENT.has(err.code)),
667
+ // A reset can only be bound to a specific card, and only offered for
668
+ // failures a factory reset actually fixes. Without a serial there is
669
+ // nothing to bind to — the reset tap has no other way to learn which
670
+ // card failed — so no offer is made at all.
671
+ resetSerial: tapped && err && RESETTABLE.has(err.code) && !NEVER_RESETTABLE.has(err.code) ? tapped : undefined
672
+ })
673
+ setSub('error')
674
+ if (err instanceof VaultEnrollmentPartialError) {
675
+ // A partial has just written a draft or a quarantine for this exact
676
+ // serial. The reset page has to know that before it can describe
677
+ // what erasing the card would destroy.
678
+ void reloadDraftLists()
679
+ }
680
+ } finally {
681
+ tapInFlight.current = false
682
+ }
683
+ },
684
+ [k, metaKeys, pending, newPin, newPuk, onCancel, pivAck, saveKey, scopeToken, reloadDraftLists]
685
+ )
686
+
687
+ /** Resume only the non-mutating possession challenge for a protected draft.
688
+ * The service re-reads the scoped draft and exact serial/pubkey before it
689
+ * opens the YubiKey session. */
690
+ const resumeDraft = useCallback(
691
+ async (entry: VaultEnrollmentDraftEntry) => {
692
+ if (tapInFlight.current || !pivAck || !pinOk) return
693
+ tapInFlight.current = true
694
+ setSub('tap')
695
+ setPhase(null)
696
+ setKeyError(null)
697
+ setStepError(null)
698
+ clearResetConsent()
699
+ try {
700
+ const record = await resumeEnrollmentDraft({
701
+ entry,
702
+ scopeToken,
703
+ onPhase: setPhase,
704
+ // A protected draft's card already carries the PIN chosen in this run.
705
+ getPin: async () => newPin,
706
+ nfcMessage: t('vault_nfc_enroll_message')
707
+ })
708
+ vaultStore.assertScopeToken(scopeToken)
709
+ setRecoverableDrafts(current => current.filter(draft => draft.record.serial !== record.serial))
710
+ haptics.success()
711
+ await saveKey(record)
712
+ } catch (e) {
713
+ haptics.error()
714
+ try {
715
+ vaultStore.assertScopeToken(scopeToken)
716
+ } catch {
717
+ clearKeyInputs()
718
+ showToast(vaultErrorCopy('scope-changed'), { type: 'error' })
719
+ onCancel()
720
+ return
721
+ }
722
+ const err = e instanceof VaultError ? e : undefined
723
+ if (err?.code === 'pin-invalid') {
724
+ setNewPin('')
725
+ setConfirmPin('')
726
+ setPinError(vaultErrorCopy('pin-invalid', { count: err.retriesLeft }))
727
+ setSub('pin')
728
+ return
729
+ }
730
+ setKeyError({
731
+ code: err?.code,
732
+ // resumeEnrollmentDraft only ever throws `key-generated` or
733
+ // `key-protected`, so the card here is certainly mutated and the
734
+ // reset-required copy would be literally true. The hedged copy is
735
+ // used anyway: it is also true (the management-key state is exactly
736
+ // what is unknown), no reset is offered from this path, and one rule
737
+ // — proven state gets the definite copy, recorded uncertainty gets
738
+ // the hedged one — is easier to keep right than a per-site judgement.
739
+ copy:
740
+ err instanceof VaultEnrollmentPartialError
741
+ ? t('vault_enrollment_state_uncertain')
742
+ : vaultErrorCopy(err?.code),
743
+ // Same dead-button argument as the enrollment tap: `pin-invalid` is
744
+ // already handled above, and the rest of the set cannot be retried
745
+ // into success from here either.
746
+ mustUseDifferent: err instanceof VaultEnrollmentPartialError || (!!err && MUST_USE_DIFFERENT.has(err.code))
747
+ // No `resetSerial`: no reset is offered from the resume path, and
748
+ // because the binding lives on this object there is no earlier
749
+ // serial that could follow the user here.
750
+ })
751
+ setSub('error')
752
+ } finally {
753
+ tapInFlight.current = false
754
+ }
755
+ },
756
+ [onCancel, newPin, pinOk, pivAck, saveKey, scopeToken]
757
+ )
758
+
759
+ // ── finish (enroll mode) ────────────────────────────────────────────
760
+ const finish = useCallback(async () => {
761
+ if (pending.length < VAULT_MIN_KEYS || busy) return
762
+ setBusy(true)
763
+ setStepError(null)
764
+ try {
765
+ await finalizeEnrollment(pending, scopeToken)
766
+ // No tone here (see useConfirmationSound): vaultDeposit/vaultWithdraw
767
+ // name an actual transfer, and enrolling isn't one.
243
768
  haptics.success()
244
769
  showToast(t('vault_enrolled_toast'), { type: 'success' })
245
770
  setStep('done')
246
- onDone()
247
771
  } catch (e) {
248
- // An occupied slot is a fork in the road, not a failure: the key already
249
- // there is exactly what a second device needs. Offer it instead of
250
- // dropping the user back to the passphrase step with a dead-end error.
251
- if (e instanceof VaultError && e.code === 'slot-occupied' && !adoptExisting) {
252
- setStep('adopt')
772
+ haptics.error()
773
+ setStepError(vaultErrorCopy(e instanceof VaultError ? e.code : undefined))
774
+ } finally {
775
+ setBusy(false)
776
+ }
777
+ }, [pending, busy, scopeToken])
778
+
779
+ const addAnother = useCallback(() => {
780
+ setStepError(null)
781
+ // A destructive tick must never survive into the next key's step.
782
+ clearResetConsent()
783
+ setStep('key')
784
+ setSub('pin')
785
+ }, [])
786
+
787
+ /** A different card has a different PIN: start the step over. */
788
+ const chooseDifferentKey = () => {
789
+ setKeyError(null)
790
+ clearKeyInputs()
791
+ setSub('pin')
792
+ }
793
+
794
+ /**
795
+ * Erase this card's whole PIV application so a previously used YubiKey can
796
+ * be enrolled.
797
+ *
798
+ * TWO consents, deliberately separate, because they are two different facts.
799
+ * `resetAck` is "this erases everything on this key" — every certificate and
800
+ * key in the PIV application, not only Vault's slot. `resetUnknownAck` is a
801
+ * narrower and worse one: the Vault slot holds a key that no vault this
802
+ * device can see claims, so erasing it destroys a vault key belonging to a
803
+ * vault we cannot inspect. `acknowledgeUnrecognizedVaultKey` is the ONLY
804
+ * guard in pivReset a caller can talk past, so it is never sent on the first
805
+ * attempt: the card decides whether the question needs asking at all, and
806
+ * the user answers that exact question before it is sent.
807
+ */
808
+ const runReset = useCallback(async () => {
809
+ // Read straight off the failure being shown: the serial erased is by
810
+ // construction the one that failed, and the one rendered above the button.
811
+ const resetSerial = keyError?.resetSerial
812
+ if (!resetSerial || !resetAck || resetting || tapInFlight.current) return
813
+ if (resetUnknownSlot && !resetUnknownAck) return
814
+ setResetting(true)
815
+ // A card session is open: hardware back is swallowed until its outcome
816
+ // lands, the same invariant the enrollment tap holds — more so here,
817
+ // because the outcome may be an erased key.
818
+ tapInFlight.current = true
819
+ setStepError(null)
820
+ let wiped = false
821
+ try {
822
+ // Read the cross-chain enrolled set HERE rather than leaving it to
823
+ // pivReset alone. Corrupt metadata on any chain — including one this
824
+ // wallet never used — makes that read throw, and from the service's
825
+ // rejection there is no way to tell that apart from a failure after the
826
+ // card was already erased. Asked here it is provably before any card
827
+ // contact, so the copy can say what actually happened: nothing.
828
+ let acrossChains: readonly string[] = []
829
+ try {
830
+ acrossChains = await vaultStore.enrolledSerialsAcrossChains(scopeToken)
831
+ } catch (e) {
832
+ haptics.error()
833
+ if (e instanceof VaultError && e.code === 'scope-changed') {
834
+ // Still before any card contact, so the ordinary line is truthful
835
+ // here — unlike the same code raised around the reset itself.
836
+ clearKeyInputs()
837
+ showToast(vaultErrorCopy('scope-changed'), { type: 'error' })
838
+ onCancel()
839
+ return
840
+ }
841
+ setStepError(t('vault_err_reset_unreadable'))
253
842
  return
254
843
  }
844
+ await resetPivApplication({
845
+ serial: resetSerial,
846
+ // Stored ∪ pending ∪ every chain: pivReset refuses all of these below
847
+ // the UI too, but the wizard holds pending records the store has not
848
+ // seen yet, and dropping them would silently remove half of that
849
+ // refusal for exactly the keys set up in this run.
850
+ refuseSerials: [...acrossChains, ...metaKeys.map(r => r.serial), ...pending.map(r => r.serial)],
851
+ acknowledgeDestroysAllCredentials: true,
852
+ ...(resetUnknownAck ? { acknowledgeUnrecognizedVaultKey: true as const } : {}),
853
+ scopeToken,
854
+ nfcMessage: t('vault_nfc_enroll_message')
855
+ })
856
+ wiped = true
857
+ } catch (e) {
255
858
  haptics.error()
256
-
257
- // A wrong PIN is feedback on the PIN, so it belongs on the PIN prompt.
258
- // Dropping back to the passphrase screen with "Wrong PIN." underneath it
259
- // asked the user to re-confirm a passphrase that was never the problem.
260
- // Nothing has been written to the key at this point — verifyPin runs
261
- // before generateVaultKey — so re-entering the ceremony is safe, and it
262
- // is what puts the PIN sheet back on screen.
263
- if (e instanceof VaultError && e.code === 'pin-invalid') {
264
- setPinError(
265
- e.retriesLeft !== undefined
266
- ? `${t('vault_err_pin_invalid')} ${t('vault_pin_retries', { count: e.retriesLeft })}`
267
- : t('vault_err_pin_invalid')
859
+ const err = e instanceof VaultError ? e : undefined
860
+ // TEMP DIAG: the real error behind the reset failure.
861
+ if (__DEV__) {
862
+ console.log(
863
+ `[vault][diag] resetPivApplication threw code=${err?.code ?? '(not VaultError)'} msg=${JSON.stringify(
864
+ (e as Error)?.message
865
+ )} details=${JSON.stringify(err?.details)}`
268
866
  )
269
- void startRef.current?.(adoptExisting)
867
+ }
868
+ if (err?.code === 'scope-changed') {
869
+ clearKeyInputs()
870
+ // Not the usual scope-changed line. This assertion also runs AFTER the
871
+ // reset APDU, and what the user needs to know about a destructive
872
+ // command is the state of the card, not why the wizard closed.
873
+ showToast(t('vault_reset_uncertain'), { type: 'error' })
874
+ onCancel()
270
875
  return
271
876
  }
272
-
273
- const msg =
274
- e instanceof VaultError ? t(`vault_err_${e.code.replace(/-/g, '_')}`, {}) : String(e)
275
- setError(msg || t('vault_err_generic'))
276
- setStep('passphrase')
277
- }
278
- }, [passphrase, getMnemonic, requestPin, requestPinChange, onDone])
279
-
280
- startRef.current = start
281
-
282
- const submitPin = useCallback(() => {
283
- if (!pinReq) return
284
- if (pinReq.kind === 'change') {
285
- if (newPinInput.length < 6) return
286
- pinReq.resolve({ oldPin: '123456', newPin: newPinInput })
287
- } else {
288
- if (pinInput.length < 4) return
289
- pinReq.resolve(pinInput)
877
+ if (err?.code === 'slot-occupied') {
878
+ // The card's own answer (pivReset guard 3, pivReset.ts:109-116), which
879
+ // runs BEFORE driver.resetPivApplication. This is the one rejection
880
+ // where "nothing was erased" is provable, and the user has just
881
+ // pressed a destructive button and watched a card session open and
882
+ // close — so it is reported, not merely implied by a new checkbox
883
+ // appearing. A checkbox states a consequence; it does not report an
884
+ // outcome.
885
+ setResetUnknownSlot(true)
886
+ setStepError(t('vault_reset_nothing_erased'))
887
+ return
888
+ }
889
+ setStepError(
890
+ err?.code === 'key-already-enrolled'
891
+ ? t('vault_err_reset_enrolled')
892
+ : err && RESET_BEFORE_ERASE.has(err.code)
893
+ ? vaultErrorCopy(err.code)
894
+ : t('vault_reset_uncertain')
895
+ )
896
+ return
897
+ } finally {
898
+ tapInFlight.current = false
899
+ setResetting(false)
290
900
  }
291
- setPinReq(null)
292
- setPinInput('')
293
- setNewPinInput('')
294
- }, [pinReq, pinInput, newPinInput])
901
+ if (!wiped) return
902
+ haptics.success()
903
+ showToast(t('vault_reset_done'), { type: 'success' })
904
+ clearResetConsent()
905
+ setKeyError(null)
906
+ // pivReset deletes this serial's draft and quarantine as part of the reset.
907
+ // Without this the PIN page keeps offering "Resume · …xxxx" for a key that
908
+ // no longer exists — a dead-end button of exactly the kind this plan spent
909
+ // its last two tasks removing.
910
+ await reloadDraftLists()
911
+ // Back to the recovery-code page, whose Continue starts the next tap — NOT
912
+ // straight into runTap(). CoreNFC refuses a new reader session until the
913
+ // previous one has finished invalidating, and the reset's session closed
914
+ // milliseconds ago, so an immediate re-tap hangs on a sheet that never
915
+ // connects. Requiring the user's press is both the spacing that makes it
916
+ // work and what the toast already tells them to do.
917
+ //
918
+ // The PIN and recovery code chosen for this key are still valid: the card is
919
+ // back at factory state and neither was ever written to it, so this does not
920
+ // ask for them again.
921
+ setSub('puk')
922
+ }, [
923
+ keyError,
924
+ resetAck,
925
+ resetUnknownSlot,
926
+ resetUnknownAck,
927
+ resetting,
928
+ metaKeys,
929
+ pending,
930
+ scopeToken,
931
+ onCancel,
932
+ runTap,
933
+ reloadDraftLists
934
+ ])
295
935
 
296
- // ── backup (prerequisite) ───────────────────────────────────────────
297
- if (step === 'backup') {
298
- return (
299
- <ScrollView contentContainerStyle={styles.gateBody}>
300
- {/* No hero glyph here. A shield-with-a-tick says "you are protected",
301
- which is the opposite of this screen's message — it is asking for
302
- work, not confirming it is done. The two rows below are the
303
- instruction, so nothing should out-shout them. */}
304
- <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_backup_title')}</Text>
305
- <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_backup_intro')}</Text>
306
-
307
- <BackupRow
308
- icon="document-text-outline"
309
- title={t('vault_backup_phrase_title')}
310
- // The actual count is only known once the phrase has been
311
- // revealed (getMnemonic() is biometric-gated, so it isn't read
312
- // just to label this row). 12 is the count for every wallet this
313
- // app generates; imported 24-word wallets get the correct number
314
- // here as soon as they reveal once.
315
- subtitle={t('vault_backup_phrase_sub', { count: wordCount ?? 12 })}
316
- done={medium === 'phrase'}
317
- busy={false}
318
- onPress={onRevealPhrase}
319
- />
320
- <BackupRow
321
- icon="print-outline"
322
- title={t('vault_backup_shares_title')}
323
- subtitle={t('vault_backup_shares_sub')}
324
- done={medium === 'shares'}
325
- busy={printing}
326
- onPress={onPrintShares}
327
- />
328
-
329
-
330
- {error && <Text style={[styles.err, { color: colors.error }]}>{error}</Text>}
331
- <PressableScale
332
- haptic="confirm"
333
- onPress={medium ? toPassphrase : undefined}
334
- style={[
335
- styles.primary,
336
- // Outlined while it is not yet armed. Filled with the secondary
337
- // background it was indistinguishable from the page in dark mode,
338
- // so the disabled CTA read as a stray line of grey text rather
339
- // than as a button waiting on the rows above it.
340
- {
341
- backgroundColor: medium ? colors.accent : 'transparent',
342
- borderWidth: medium ? 0 : StyleSheet.hairlineWidth,
343
- borderColor: colors.separator
344
- }
345
- ]}
346
- >
347
- <Text
348
- style={[
349
- styles.primaryLabel,
350
- { color: medium ? colors.textOnAccent : colors.textTertiary }
351
- ]}
352
- >
353
- {t('vault_continue')}
354
- </Text>
355
- </PressableScale>
356
- </ScrollView>
357
- )
358
- }
936
+ const leaveLink = (
937
+ <PressableScale onPress={() => void leave()} style={styles.secondary}>
938
+ <Text style={[styles.secondaryLabel, { color: colors.textSecondary }]}>
939
+ {unsaved > 0 ? t('vault_leave_setup') : t('vault_cancel')}
940
+ </Text>
941
+ </PressableScale>
942
+ )
359
943
 
360
- // ── phrase reveal ───────────────────────────────────────────────────
361
- if (step === 'phrase' && revealed) {
362
- return (
363
- <PhraseBackupSheet
364
- mnemonic={revealed}
365
- onAttest={async () => {
366
- // Whatever attest() decides, the phrase should not linger on
367
- // screen: on success the row ticks; on failure the backup step's
368
- // inline error tells the user to retry rather than stranding them
369
- // here with no feedback.
370
- await attest('phrase')
371
- setRevealed(null)
372
- setStep('backup')
373
- }}
374
- onCancel={() => {
375
- setRevealed(null)
376
- setStep('backup')
377
- }}
944
+ const pivAcknowledgement = (
945
+ <PressableScale
946
+ accessibilityRole="checkbox"
947
+ accessibilityState={{ checked: pivAck }}
948
+ haptic="tap"
949
+ onPress={() => setPivAck(value => !value)}
950
+ style={[styles.ackRow, { borderColor: pivAck ? colors.accent : colors.separator }]}
951
+ >
952
+ <Ionicons
953
+ name={pivAck ? 'checkbox' : 'square-outline'}
954
+ size={24}
955
+ color={pivAck ? colors.accent : colors.textTertiary}
378
956
  />
379
- )
380
- }
957
+ <Text style={[styles.ackText, { color: colors.textPrimary }]}>{t('vault_intro_piv_ack')}</Text>
958
+ </PressableScale>
959
+ )
381
960
 
382
- // ── passphrase ──────────────────────────────────────────────────────
383
- if (step === 'passphrase') {
961
+ // ── intro ───────────────────────────────────────────────────────────
962
+ if (step === 'intro') {
384
963
  return (
385
- <ScrollView contentContainerStyle={styles.body} keyboardShouldPersistTaps="handled">
386
- <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_enroll_title')}</Text>
387
- <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_enroll_intro')}</Text>
388
-
389
- <PassphraseField
390
- value={passphrase}
391
- onChangeText={setPassphrase}
392
- confirm={confirm}
393
- onChangeConfirm={setConfirm}
394
- onValidityChange={setPassphraseOk}
395
- />
396
-
397
- <View style={[styles.warnBox, { backgroundColor: colors.warning + '14' }]}>
398
- <Ionicons name="warning-outline" size={16} color={colors.warning} />
399
- <Text style={[styles.warnText, { color: colors.textSecondary }]}>
400
- {t('vault_passphrase_no_reset')}
401
- </Text>
964
+ <ScrollView contentContainerStyle={styles.body}>
965
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_intro_title')}</Text>
966
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_intro_what')}</Text>
967
+ <View style={[styles.bullets, { borderColor: colors.separator }]}>
968
+ <Bullet icon="key-outline" text={t('vault_intro_two_keys')} />
969
+ <Bullet icon="location-outline" text={t('vault_intro_apart')} />
970
+ <Bullet icon="cloud-upload-outline" text={t('vault_intro_backup')} />
402
971
  </View>
403
-
404
- {error && <Text style={[styles.err, { color: colors.error }]}>{error}</Text>}
405
972
  <PressableScale
406
- haptic="confirm"
407
- onPress={passphraseOk ? () => start() : undefined}
408
- style={[
409
- styles.primary,
410
- {
411
- backgroundColor: passphraseOk ? colors.accent : 'transparent',
412
- borderWidth: passphraseOk ? 0 : StyleSheet.hairlineWidth,
413
- borderColor: colors.separator
414
- }
415
- ]}
973
+ accessibilityRole="checkbox"
974
+ accessibilityState={{ checked: ack }}
975
+ haptic="tap"
976
+ onPress={() => setAck(a => !a)}
977
+ style={[styles.ackRow, { borderColor: ack ? colors.accent : colors.separator }]}
416
978
  >
417
- <Text
418
- style={[
419
- styles.primaryLabel,
420
- { color: passphraseOk ? colors.textOnAccent : colors.textTertiary }
421
- ]}
422
- >
423
- {t('vault_enroll_begin')}
424
- </Text>
979
+ <Ionicons
980
+ name={ack ? 'checkbox' : 'square-outline'}
981
+ size={24}
982
+ color={ack ? colors.accent : colors.textTertiary}
983
+ />
984
+ <Text style={[styles.ackText, { color: colors.textPrimary }]}>{t('vault_intro_ack')}</Text>
985
+ </PressableScale>
986
+ {pivAcknowledgement}
987
+ {/* `blockedDrafts` mixes management-uncertain drafts (certainly mutated)
988
+ with quarantines, and the earliest quarantine stage is recorded
989
+ before the card is touched — so this banner cannot claim the key is
990
+ non-factory. It also names no key, because none is in hand here. */}
991
+ {blockedDrafts.length > 0 && (
992
+ <Text style={[styles.warn, { color: colors.warning }]}>{t('vault_enrollment_state_uncertain')}</Text>
993
+ )}
994
+ <ActionButton label={t('vault_intro_begin')} enabled={ack && pivAck} busy={busy} onPress={() => void begin()} />
995
+ <PressableScale onPress={onCancel} style={styles.secondary}>
996
+ <Text style={[styles.secondaryLabel, { color: colors.textSecondary }]}>{t('vault_cancel')}</Text>
425
997
  </PressableScale>
426
998
  </ScrollView>
427
999
  )
428
1000
  }
429
1001
 
430
- // ── adopt (slot already holds a key) ────────────────────────────────
431
- if (step === 'adopt') {
432
- return (
433
- <ScrollView contentContainerStyle={styles.body}>
434
- <Ionicons
435
- name="hardware-chip-outline"
436
- size={48}
437
- color={colors.textPrimary}
438
- style={styles.hero}
439
- />
440
- <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_slot_in_use_title')}</Text>
441
- <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_slot_in_use_body')}</Text>
1002
+ // ── key k ───────────────────────────────────────────────────────────
1003
+ if (step === 'key') {
1004
+ if (sub === 'pin') {
1005
+ const advance = () => {
1006
+ if (!pivAck || busy) return
1007
+ if (!pinChosen) {
1008
+ // Never leave this silent: Continue is live so that pressing it is
1009
+ // what produces the message, and a cleared error would read as the
1010
+ // button simply not working.
1011
+ setPinError(newPin === DEFAULT_PIV_PIN ? t('vault_pin_not_default') : t('vault_pin_choose_sub'))
1012
+ return
1013
+ }
1014
+ if (confirmPin !== newPin) {
1015
+ setPinError(t('vault_pin_mismatch'))
1016
+ return
1017
+ }
1018
+ setPinError(null)
1019
+ // Generated once per visit to the PUK page, so going back and forward
1020
+ // does not silently hand the user a different code to write down. The
1021
+ // one exception is a PIN that now equals the code: the service refuses
1022
+ // that pair (validatePukChange) before the session opens, and the error
1023
+ // page offers only a Retry that would fail identically forever.
1024
+ if (!newPuk || newPuk === newPin) setNewPuk(generateRecoveryCode(newPin))
1025
+ setSub('puk')
1026
+ }
1027
+ return (
1028
+ <ScrollView contentContainerStyle={styles.body} keyboardShouldPersistTaps="handled">
1029
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_key_step_title', { k })}</Text>
1030
+ <StepProgress sub={sub} />
1031
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_key_step_replace')}</Text>
1032
+ {mode === 'add-key' && pivAcknowledgement}
442
1033
 
443
- <PressableScale
444
- haptic="confirm"
445
- onPress={() => start(true)}
446
- style={[styles.primary, { backgroundColor: colors.accent }]}
447
- >
448
- <Text style={[styles.primaryLabel, { color: colors.textOnAccent }]}>
449
- {t('vault_use_existing_key')}
1034
+ <Text style={[styles.label, { color: colors.textPrimary }]}>{t('vault_pin_choose_title')}</Text>
1035
+ <Text style={[styles.hint, { color: colors.textSecondary }]}>{t('vault_pin_choose_sub')}</Text>
1036
+ <TextInput
1037
+ ref={pinInputRef}
1038
+ accessibilityLabel={t('vault_pin_choose_title')}
1039
+ style={[styles.pin, { color: colors.textPrimary, backgroundColor: colors.backgroundSecondary }]}
1040
+ value={newPin}
1041
+ onChangeText={text => {
1042
+ setPinError(null)
1043
+ setNewPin(text)
1044
+ }}
1045
+ placeholder="••••••"
1046
+ placeholderTextColor={colors.textTertiary}
1047
+ keyboardType="number-pad"
1048
+ // Always secure: toggling this prop on based on length forces the
1049
+ // native field to remount on the first keystroke and drops it.
1050
+ secureTextEntry
1051
+ maxLength={PIN_MAX}
1052
+ />
1053
+
1054
+ <Text style={[styles.label, { color: colors.textPrimary }]}>{t('vault_pin_confirm_label')}</Text>
1055
+ <TextInput
1056
+ accessibilityLabel={t('vault_pin_confirm_label')}
1057
+ style={[styles.pin, { color: colors.textPrimary, backgroundColor: colors.backgroundSecondary }]}
1058
+ value={confirmPin}
1059
+ onChangeText={text => {
1060
+ setPinError(null)
1061
+ setConfirmPin(text)
1062
+ }}
1063
+ placeholder="••••••"
1064
+ placeholderTextColor={colors.textTertiary}
1065
+ keyboardType="number-pad"
1066
+ secureTextEntry
1067
+ maxLength={PIN_MAX}
1068
+ />
1069
+
1070
+ {pinError && <Text style={[styles.err, { color: colors.error }]}>{pinError}</Text>}
1071
+ {stepError && <Text style={[styles.err, { color: colors.error }]}>{stepError}</Text>}
1072
+ {/* This page says "Choose a PIN", but resuming sends what is typed
1073
+ here to a card that already carries the PIN an earlier run set.
1074
+ A fresh choice is a guess, and three guesses lock a card holding
1075
+ a real, partially enrolled vault key — so say which PIN is wanted
1076
+ whenever a resume is actually on offer. */}
1077
+ {recoverableDrafts.length > 0 && (
1078
+ <Text style={[styles.hint, { color: colors.textSecondary }]}>{t('vault_enrollment_resume_pin_hint')}</Text>
1079
+ )}
1080
+ {recoverableDrafts.map(entry => (
1081
+ <ActionButton
1082
+ key={entry.record.serial}
1083
+ label={`${t('vault_enrollment_resume')} · …${entry.record.serial.slice(-4)}`}
1084
+ variant="outline"
1085
+ enabled={pivAck && pinOk && !busy}
1086
+ onPress={() => void resumeDraft(entry)}
1087
+ />
1088
+ ))}
1089
+ {/* Same hedge as the intro banner, and for the same reason. */}
1090
+ {blockedDrafts.length > 0 && (
1091
+ <Text style={[styles.warn, { color: colors.warning }]}>{t('vault_enrollment_state_uncertain')}</Text>
1092
+ )}
1093
+ {/* TEMP DIAG (remove before commit): a quarantine is cleared only by a
1094
+ successful in-app pivReset, so a card reset with `ykman piv reset`
1095
+ stays locked out with no in-app escape. That is a real gap worth
1096
+ fixing properly; this is the debugging shortcut in the meantime. */}
1097
+ {__DEV__ && blockedDrafts.length > 0 && (
1098
+ <ActionButton
1099
+ label="DEV: clear stored quarantine"
1100
+ variant="outline"
1101
+ onPress={() => {
1102
+ void (async () => {
1103
+ for (const item of blockedDrafts) {
1104
+ const serial = 'record' in item ? item.record.serial : item.serial
1105
+ try {
1106
+ await vaultStore.discardEnrollmentDraft(serial, scopeToken)
1107
+ await vaultStore.discardEnrollmentQuarantine(serial, scopeToken)
1108
+ console.log(`[vault][diag] DEV cleared quarantine + draft for ${serial}`)
1109
+ } catch (e) {
1110
+ console.log(`[vault][diag] DEV clear failed: ${JSON.stringify((e as Error)?.message)}`)
1111
+ }
1112
+ }
1113
+ await reloadDraftLists()
1114
+ })()
1115
+ }}
1116
+ />
1117
+ )}
1118
+ {/* NFC only: a brand-new YubiKey ships in restricted NFC mode (Yubico's
1119
+ anti-scan-in-transit policy) and stays that way until it is plugged
1120
+ into USB-C for a few seconds — a one-time, per-key step done outside
1121
+ this app. Shown on every key here since we cannot tell a fresh card
1122
+ from a already-activated one before the tap. */}
1123
+ {Platform.OS === 'ios' && (
1124
+ <Text style={[styles.hint, { color: colors.textSecondary }]}>{t('vault_nfc_activation_hint')}</Text>
1125
+ )}
1126
+ <ActionButton label={t('vault_continue')} enabled={pivAck && !busy} onPress={advance} />
1127
+ {leaveLink}
1128
+ </ScrollView>
1129
+ )
1130
+ }
1131
+
1132
+ if (sub === 'puk') {
1133
+ return (
1134
+ <ScrollView contentContainerStyle={styles.body} keyboardShouldPersistTaps="handled">
1135
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_key_step_title', { k })}</Text>
1136
+ <StepProgress sub={sub} />
1137
+ <Text style={[styles.label, { color: colors.textPrimary }]}>{t('vault_puk_title')}</Text>
1138
+ {/* Shown once and never stored, exactly like the PIN. The
1139
+ acknowledgement is a tick rather than a plain button because
1140
+ losing this code silently is the failure this page exists to
1141
+ prevent. */}
1142
+ {/* Spaced digits, not the heading: an accessibilityLabel REPLACES the
1143
+ content, so labelling this with the title announced "Your recovery
1144
+ code" twice and never read the digits — on the one page whose
1145
+ whole job is getting eight digits into the user's head. Spacing
1146
+ them makes VoiceOver/TalkBack read them one at a time instead of
1147
+ as a single eight-digit number. */}
1148
+ <Text
1149
+ testID="vault-recovery-code"
1150
+ accessibilityLabel={newPuk.split('').join(' ')}
1151
+ selectable
1152
+ style={[styles.code, { color: colors.textPrimary, backgroundColor: colors.backgroundSecondary }]}
1153
+ >
1154
+ {newPuk}
450
1155
  </Text>
451
- </PressableScale>
452
- <PressableScale onPress={onCancel} style={styles.secondary}>
453
- <Text style={[styles.secondaryLabel, { color: colors.textSecondary }]}>
454
- {t('vault_cancel')}
1156
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_puk_body')}</Text>
1157
+ <PressableScale
1158
+ accessibilityRole="checkbox"
1159
+ accessibilityState={{ checked: pukAck }}
1160
+ haptic="tap"
1161
+ onPress={() => setPukAck(value => !value)}
1162
+ style={[styles.ackRow, { borderColor: pukAck ? colors.accent : colors.separator }]}
1163
+ >
1164
+ <Ionicons
1165
+ name={pukAck ? 'checkbox' : 'square-outline'}
1166
+ size={24}
1167
+ color={pukAck ? colors.accent : colors.textTertiary}
1168
+ />
1169
+ <Text style={[styles.ackText, { color: colors.textPrimary }]}>{t('vault_puk_ack')}</Text>
1170
+ </PressableScale>
1171
+ {stepError && <Text style={[styles.err, { color: colors.error }]}>{stepError}</Text>}
1172
+ <ActionButton label={t('vault_continue')} enabled={pukAck && pinOk && !busy} onPress={() => void runTap()} />
1173
+ <ActionButton label={t('vault_back')} variant="outline" onPress={() => setSub('pin')} />
1174
+ {leaveLink}
1175
+ </ScrollView>
1176
+ )
1177
+ }
1178
+
1179
+ if (sub === 'tap') {
1180
+ return (
1181
+ <View style={styles.body}>
1182
+ <ActivityIndicator color={colors.textPrimary} size="large" style={styles.hero} />
1183
+ <StepProgress sub={sub} />
1184
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>
1185
+ {phase ? t(`vault_enroll_phase_${phase.replace(/-/g, '_')}`) : t('vault_reading_key')}
455
1186
  </Text>
456
- </PressableScale>
457
- </ScrollView>
458
- )
459
- }
1187
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_touch_when_blinks')}</Text>
1188
+ </View>
1189
+ )
1190
+ }
460
1191
 
461
- // ── running (PIN prompts + tap) ─────────────────────────────────────
462
- if (step === 'running') {
463
- return (
464
- <View style={styles.body}>
465
- {pinReq ? (
466
- <>
467
- <Ionicons name="keypad-outline" size={40} color={colors.textPrimary} style={styles.hero} />
468
- <Text style={[styles.h1, { color: colors.textPrimary }]}>
469
- {pinReq.kind === 'change' ? t('vault_set_new_pin') : t('vault_enter_pin')}
470
- </Text>
471
- {/* Which PIN, and what it is if they have never set one. Without
472
- this the prompt is ambiguous with the phone's own passcode, and
473
- a factory key's PIN is not something users know they have. */}
474
- <Text style={[styles.p, { color: colors.textSecondary }]}>
475
- {pinReq.kind === 'change' ? t('vault_default_pin_warning') : t('vault_enter_pin_sub')}
476
- </Text>
477
- {pinError && <Text style={[styles.err, { color: colors.error }]}>{pinError}</Text>}
478
- <TextInput
479
- style={[
480
- styles.pin,
481
- { color: colors.textPrimary, backgroundColor: colors.backgroundSecondary }
482
- ]}
483
- value={pinReq.kind === 'change' ? newPinInput : pinInput}
484
- onChangeText={text => {
485
- setPinError(null)
486
- ;(pinReq.kind === 'change' ? setNewPinInput : setPinInput)(text)
487
- }}
488
- placeholder="••••••"
489
- placeholderTextColor={colors.textTertiary}
490
- keyboardType="number-pad"
491
- // Masking only once there is something to mask: iOS renders a
492
- // secure field's PLACEHOLDER with masked-glyph metrics, which is
493
- // what stretches the bullets apart before any digit is typed.
494
- secureTextEntry={(pinReq.kind === 'change' ? newPinInput : pinInput).length > 0}
495
- maxLength={8}
496
- autoFocus
1192
+ if (sub === 'save') {
1193
+ // add-key mode only — enroll mode's save is a synchronous push into
1194
+ // `pending`. Nothing is asked here, so there is nothing to show but the
1195
+ // write itself, and the retry if it fails. The card is done either way:
1196
+ // the retry saves the record again, it never taps anything.
1197
+ return (
1198
+ <View style={styles.body}>
1199
+ {stepError ? (
1200
+ <>
1201
+ <Ionicons name="alert-circle-outline" size={48} color={colors.error} style={styles.hero} />
1202
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{stepError}</Text>
1203
+ <ActionButton
1204
+ label={t('vault_retry')}
1205
+ busy={busy}
1206
+ onPress={() => {
1207
+ if (fresh) void saveKey(fresh)
1208
+ }}
1209
+ />
1210
+ {leaveLink}
1211
+ </>
1212
+ ) : (
1213
+ <ActivityIndicator color={colors.textPrimary} size="large" style={styles.hero} />
1214
+ )}
1215
+ </View>
1216
+ )
1217
+ }
1218
+
1219
+ if (sub === 'reset') {
1220
+ // The same field `runReset` reads, so the serial shown above the button
1221
+ // is the serial erased, with no second copy that could disagree.
1222
+ const resetSerial = keyError?.resetSerial
1223
+ // Is the key in this card's Vault slot one THIS device has a record of —
1224
+ // a draft or a quarantine from an earlier attempt, possibly this very
1225
+ // run's? If so, "a vault key that no vault on this device claims" is
1226
+ // simply false, and telling the user that trains them to tick the only
1227
+ // guard in pivReset a caller can override. They would then meet the case
1228
+ // it exists for — another identity's live vault key — with the habit
1229
+ // already formed.
1230
+ const knownDraft =
1231
+ resetSerial !== undefined &&
1232
+ (recoverableDrafts.some(entry => entry.record.serial === resetSerial) ||
1233
+ blockedDrafts.some(item => ('record' in item ? item.record.serial : item.serial) === resetSerial))
1234
+ const resumableDraft = recoverableDrafts.find(entry => entry.record.serial === resetSerial)
1235
+ return (
1236
+ <ScrollView contentContainerStyle={styles.body}>
1237
+ <Ionicons name="warning-outline" size={48} color={colors.warning} style={styles.hero} />
1238
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_reset_title')}</Text>
1239
+ <Text style={[styles.p, { color: colors.textSecondary }]}>
1240
+ {resetSerial ? `…${resetSerial.slice(-4)}` : ''}
1241
+ </Text>
1242
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_reset_body')}</Text>
1243
+ <PressableScale
1244
+ accessibilityRole="checkbox"
1245
+ accessibilityState={{ checked: resetAck }}
1246
+ haptic="tap"
1247
+ onPress={() => setResetAck(value => !value)}
1248
+ style={[styles.ackRow, { borderColor: resetAck ? colors.error : colors.separator }]}
1249
+ >
1250
+ <Ionicons
1251
+ name={resetAck ? 'checkbox' : 'square-outline'}
1252
+ size={24}
1253
+ color={resetAck ? colors.error : colors.textTertiary}
497
1254
  />
1255
+ <Text style={[styles.ackText, { color: colors.textPrimary }]}>{t('vault_reset_ack')}</Text>
1256
+ </PressableScale>
1257
+ {/* Directly above the question it explains. On `slot-occupied` this
1258
+ is the pre-erase line: the user pressed a destructive button and
1259
+ watched a card session open and close, and needs to be told the
1260
+ erase did not happen before being asked anything else. */}
1261
+ {stepError && <Text style={[styles.err, { color: colors.error }]}>{stepError}</Text>}
1262
+ {/* Shown only once the card itself has reported an occupied Vault
1263
+ slot. A separate question, because it is a separate loss — and
1264
+ which loss it is depends on whether this device knows the key in
1265
+ that slot. */}
1266
+ {resetUnknownSlot && (
498
1267
  <PressableScale
499
- haptic="confirm"
500
- onPress={submitPin}
501
- style={[styles.primary, { backgroundColor: colors.accent }]}
1268
+ accessibilityRole="checkbox"
1269
+ accessibilityState={{ checked: resetUnknownAck }}
1270
+ haptic="tap"
1271
+ onPress={() => setResetUnknownAck(value => !value)}
1272
+ style={[styles.ackRow, { borderColor: resetUnknownAck ? colors.error : colors.separator }]}
502
1273
  >
503
- <Text style={[styles.primaryLabel, { color: colors.textOnAccent }]}>
504
- {t('vault_continue')}
1274
+ <Ionicons
1275
+ name={resetUnknownAck ? 'checkbox' : 'square-outline'}
1276
+ size={24}
1277
+ color={resetUnknownAck ? colors.error : colors.textTertiary}
1278
+ />
1279
+ <Text style={[styles.ackText, { color: colors.textPrimary }]}>
1280
+ {knownDraft ? t('vault_reset_own_draft_ack') : t('vault_reset_unknown_ack')}
505
1281
  </Text>
506
1282
  </PressableScale>
507
- </>
508
- ) : (
1283
+ )}
1284
+ {/* The non-destructive way out of the case above: this device holds a
1285
+ resumable record for the very key the reset would erase. Carries
1286
+ the same PIN warning as the PIN page, because resuming sends the
1287
+ PIN in state and only an earlier run's PIN will open that card. */}
1288
+ {resetUnknownSlot && resumableDraft && (
1289
+ <>
1290
+ <Text style={[styles.hint, { color: colors.textSecondary }]}>
1291
+ {t('vault_enrollment_resume_pin_hint')}
1292
+ </Text>
1293
+ <ActionButton
1294
+ label={`${t('vault_enrollment_resume')} · …${resumableDraft.record.serial.slice(-4)}`}
1295
+ variant="outline"
1296
+ enabled={pinOk && !resetting}
1297
+ onPress={() => void resumeDraft(resumableDraft)}
1298
+ />
1299
+ </>
1300
+ )}
1301
+ <ActionButton
1302
+ label={resetting ? t('vault_resetting') : t('vault_reset_confirm')}
1303
+ enabled={resetAck && (!resetUnknownSlot || resetUnknownAck) && !resetting}
1304
+ onPress={() => void runReset()}
1305
+ />
1306
+ <ActionButton
1307
+ label={t('vault_key_use_different')}
1308
+ variant="outline"
1309
+ enabled={!resetting}
1310
+ onPress={() => {
1311
+ setStepError(null)
1312
+ chooseDifferentKey()
1313
+ }}
1314
+ />
1315
+ </ScrollView>
1316
+ )
1317
+ }
1318
+
1319
+ // sub === 'error'
1320
+ const code = keyError?.code
1321
+ return (
1322
+ <View style={styles.body}>
1323
+ <Ionicons name="alert-circle-outline" size={48} color={colors.error} style={styles.hero} />
1324
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{keyError?.copy ?? t('vault_err_generic')}</Text>
1325
+ {/* Set only for a card whose failure a factory reset can actually fix
1326
+ (RESETTABLE minus NEVER_RESETTABLE), and only when the failure named
1327
+ the card. It is a field of THIS failure, so it cannot be a leftover
1328
+ from an earlier one. */}
1329
+ {keyError?.resetSerial ? (
1330
+ <ActionButton
1331
+ label={t('vault_reset_offer')}
1332
+ variant="outline"
1333
+ onPress={() => {
1334
+ setStepError(null)
1335
+ setSub('reset')
1336
+ }}
1337
+ />
1338
+ ) : null}
1339
+ {code === 'slot-occupied' ? (
509
1340
  <>
510
- <ActivityIndicator color={colors.textPrimary} size="large" style={styles.hero} />
511
- <Text style={[styles.h1, { color: colors.textPrimary }]}>
512
- {phaseLabel || t('vault_reading_key')}
513
- </Text>
514
- <Text style={[styles.p, { color: colors.textSecondary }]}>
515
- {t('vault_touch_when_blinks')}
516
- </Text>
1341
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_replace_key_warning')}</Text>
1342
+ <ActionButton label={t('vault_replace_key_confirm')} onPress={() => void runTap(true)} />
1343
+ <ActionButton label={t('vault_key_use_different')} variant="outline" onPress={chooseDifferentKey} />
517
1344
  </>
1345
+ ) : code === 'key-already-enrolled' || code === 'puk-locked' || keyError?.mustUseDifferent ? (
1346
+ <ActionButton label={t('vault_key_use_different')} onPress={chooseDifferentKey} />
1347
+ ) : code === 'enrollment-partial' ? (
1348
+ // The one exit from the error page that does not go through
1349
+ // clearKeyInputs, so the destructive ticks are dropped explicitly:
1350
+ // the next thing reached from the PIN page may be a resume of a
1351
+ // DIFFERENT card, and consent must not be waiting for it.
1352
+ <ActionButton
1353
+ label={t('vault_retry')}
1354
+ onPress={() => {
1355
+ clearResetConsent()
1356
+ setSub('pin')
1357
+ }}
1358
+ />
1359
+ ) : (
1360
+ <ActionButton label={t('vault_retry')} onPress={() => void runTap()} />
518
1361
  )}
1362
+ {leaveLink}
519
1363
  </View>
520
1364
  )
521
1365
  }
522
1366
 
523
- return null
1367
+ // ── more ────────────────────────────────────────────────────────────
1368
+ if (step === 'more') {
1369
+ const canAdd = total < VAULT_MAX_KEYS
1370
+ const canFinish = pending.length >= VAULT_MIN_KEYS
1371
+ return (
1372
+ <ScrollView contentContainerStyle={styles.body}>
1373
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_more_title')}</Text>
1374
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_more_body')}</Text>
1375
+ <View style={[styles.list, { backgroundColor: colors.backgroundElevated, borderColor: colors.separator }]}>
1376
+ {pending.map((p, i) => (
1377
+ <View
1378
+ key={p.serial}
1379
+ style={[
1380
+ styles.listRow,
1381
+ i < pending.length - 1 && {
1382
+ borderBottomWidth: StyleSheet.hairlineWidth,
1383
+ borderBottomColor: colors.separator
1384
+ }
1385
+ ]}
1386
+ >
1387
+ <Ionicons name="key-outline" size={20} color={colors.success} />
1388
+ <Text style={[styles.listLabel, { color: colors.textPrimary }]} numberOfLines={1}>
1389
+ {vaultKeyLabel(p)}
1390
+ </Text>
1391
+ </View>
1392
+ ))}
1393
+ </View>
1394
+ {!canFinish && <Text style={[styles.warn, { color: colors.warning }]}>{t('vault_more_need_two')}</Text>}
1395
+ {stepError && <Text style={[styles.err, { color: colors.error }]}>{stepError}</Text>}
1396
+ {/* The filled button is whichever moves the user forward: Add while a
1397
+ second key is still required, Finish once there are enough. */}
1398
+ {canAdd && (
1399
+ <ActionButton
1400
+ label={t('vault_more_add')}
1401
+ variant={canFinish ? 'outline' : 'primary'}
1402
+ enabled={!busy}
1403
+ onPress={addAnother}
1404
+ />
1405
+ )}
1406
+ <ActionButton label={t('vault_more_finish')} enabled={canFinish} busy={busy} onPress={() => void finish()} />
1407
+ {leaveLink}
1408
+ </ScrollView>
1409
+ )
1410
+ }
1411
+
1412
+ // ── done ────────────────────────────────────────────────────────────
1413
+ return (
1414
+ <View style={[styles.body, styles.doneBody]}>
1415
+ <Ionicons name="checkmark-circle" size={56} color={colors.success} style={styles.hero} />
1416
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>
1417
+ {mode === 'enroll' ? t('vault_enrolled_toast') : t('vault_key_added_toast')}
1418
+ </Text>
1419
+ <Text style={[styles.p, { color: colors.textSecondary }]}>
1420
+ {mode === 'enroll'
1421
+ ? t('vault_done_body', { count: pending.length })
1422
+ : t('vault_add_key_done', { nickname: addedNickname })}
1423
+ </Text>
1424
+ <ActionButton label={mode === 'enroll' ? t('vault_done_cta') : t('vault_relock_now')} onPress={onDone} />
1425
+ </View>
1426
+ )
524
1427
  }
525
1428
 
526
- /** One backup route: tappable, ticks when satisfied, stays tappable after. */
527
- const BackupRow: React.FC<{
528
- icon: React.ComponentProps<IoniconsComponent>['name']
529
- title: string
530
- subtitle: string
531
- done: boolean
532
- busy: boolean
533
- onPress: () => void
534
- }> = ({ icon, title, subtitle, done, busy, onPress }) => {
1429
+ /**
1430
+ * Where this key's setup has got to. Per key, three steps: choose a PIN, note
1431
+ * the recovery code, tap.
1432
+ */
1433
+ const StepProgress: React.FC<{ sub: KeySub }> = ({ sub }) => {
1434
+ const { colors } = useTheme()
1435
+ const index = KEY_STEPS.indexOf(sub)
1436
+ if (index < 0) return null
1437
+ const n = index + 1
1438
+ const total = KEY_STEPS.length
1439
+ return (
1440
+ <View style={styles.progress} accessibilityRole="progressbar" accessibilityValue={{ min: 1, max: total, now: n }}>
1441
+ <View style={[styles.progressTrack, { backgroundColor: colors.backgroundSecondary }]}>
1442
+ <View style={[styles.progressFill, { backgroundColor: colors.accent, width: `${(n / total) * 100}%` }]} />
1443
+ </View>
1444
+ <Text style={[styles.progressLabel, { color: colors.textSecondary }]}>{t('vault_setup_step', { n, total })}</Text>
1445
+ </View>
1446
+ )
1447
+ }
1448
+
1449
+ /** One intro bullet: glyph + line. */
1450
+ const Bullet: React.FC<{ icon: React.ComponentProps<IoniconsComponent>['name']; text: string }> = ({ icon, text }) => {
535
1451
  const { colors } = useTheme()
536
1452
  const Ionicons = loadIonicons()
1453
+ return (
1454
+ <View style={styles.bulletRow}>
1455
+ <Ionicons name={icon} size={18} color={colors.info} />
1456
+ <Text style={[styles.bulletText, { color: colors.textPrimary }]}>{text}</Text>
1457
+ </View>
1458
+ )
1459
+ }
1460
+
1461
+ /**
1462
+ * The wizard's button. Filled accent when primary and enabled; outlined when
1463
+ * disabled or `variant="outline"` — filled with the secondary background it was
1464
+ * indistinguishable from the page in dark mode.
1465
+ */
1466
+ const ActionButton: React.FC<{
1467
+ label: string
1468
+ enabled?: boolean
1469
+ busy?: boolean
1470
+ variant?: 'primary' | 'outline'
1471
+ onPress: () => void
1472
+ }> = ({ label, enabled = true, busy = false, variant = 'primary', onPress }) => {
1473
+ const { colors } = useTheme()
1474
+ const active = enabled && !busy
1475
+ const filled = active && variant === 'primary'
537
1476
  return (
538
1477
  <PressableScale
539
- onPress={busy ? undefined : onPress}
540
- style={[styles.backupRow, { borderColor: done ? colors.success : colors.separator }]}
1478
+ haptic="confirm"
1479
+ // `disabled` (not only a dropped handler) so the responder itself
1480
+ // refuses the press: a11y reports it, and nothing above it in the tree
1481
+ // can pick the press up.
1482
+ disabled={!active}
1483
+ onPress={active ? onPress : undefined}
1484
+ accessibilityState={{ disabled: !active }}
1485
+ style={[
1486
+ styles.primary,
1487
+ filled
1488
+ ? { backgroundColor: colors.accent }
1489
+ : { backgroundColor: 'transparent', borderWidth: StyleSheet.hairlineWidth, borderColor: colors.separator }
1490
+ ]}
541
1491
  >
542
1492
  {busy ? (
543
- <ActivityIndicator color={colors.info} size="small" />
1493
+ <ActivityIndicator color={filled ? colors.textOnAccent : colors.textPrimary} />
544
1494
  ) : (
545
- <Ionicons name={icon} size={22} color={done ? colors.success : colors.info} />
1495
+ <Text
1496
+ style={[
1497
+ styles.primaryLabel,
1498
+ { color: filled ? colors.textOnAccent : active ? colors.textPrimary : colors.textTertiary }
1499
+ ]}
1500
+ >
1501
+ {label}
1502
+ </Text>
546
1503
  )}
547
- <View style={styles.backupRowText}>
548
- <Text style={[styles.backupRowTitle, { color: colors.textPrimary }]}>{title}</Text>
549
- <Text style={[styles.backupRowSub, { color: colors.textSecondary }]}>{subtitle}</Text>
550
- </View>
551
- {done && <Ionicons name="checkmark-circle" size={20} color={colors.success} />}
552
1504
  </PressableScale>
553
1505
  )
554
1506
  }
555
1507
 
556
1508
  const styles = StyleSheet.create({
557
1509
  body: { padding: spacing.xl, gap: spacing.lg },
558
- // The gate is three short blocks; top-aligned they sat in the upper third
559
- // with half a screen of nothing under them.
560
- gateBody: { padding: spacing.xl, gap: spacing.lg, flexGrow: 1, justifyContent: 'center' },
1510
+ doneBody: { flexGrow: 1, justifyContent: 'center', alignItems: 'center' },
561
1511
  hero: { marginTop: spacing.lg, alignSelf: 'center' },
562
1512
  h1: { ...typography.title2, textAlign: 'center' },
563
1513
  p: { ...typography.subhead, textAlign: 'center' },
564
- input: {
565
- width: '100%',
1514
+ label: { ...typography.headline },
1515
+ hint: { ...typography.footnote },
1516
+ warn: { ...typography.footnote, textAlign: 'center' },
1517
+ err: { ...typography.footnote, textAlign: 'center' },
1518
+ progress: { gap: spacing.xs },
1519
+ progressTrack: { height: 4, borderRadius: radii.sm, overflow: 'hidden' },
1520
+ progressFill: { height: 4, borderRadius: radii.sm },
1521
+ progressLabel: { ...typography.footnote, textAlign: 'center' },
1522
+ bullets: {
1523
+ gap: spacing.md,
566
1524
  borderRadius: radii.md,
567
- paddingVertical: spacing.md,
568
- paddingHorizontal: spacing.lg,
569
- ...typography.body
1525
+ borderWidth: StyleSheet.hairlineWidth,
1526
+ padding: spacing.lg
570
1527
  },
1528
+ bulletRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm },
1529
+ bulletText: { ...typography.subhead, flex: 1 },
1530
+ ackRow: {
1531
+ flexDirection: 'row',
1532
+ alignItems: 'flex-start',
1533
+ gap: spacing.md,
1534
+ borderRadius: radii.md,
1535
+ borderWidth: StyleSheet.hairlineWidth,
1536
+ padding: spacing.lg
1537
+ },
1538
+ ackText: { ...typography.subhead, flex: 1 },
571
1539
  pin: {
572
1540
  width: '70%',
573
1541
  alignSelf: 'center',
@@ -577,51 +1545,27 @@ const styles = StyleSheet.create({
577
1545
  borderRadius: radii.md,
578
1546
  paddingVertical: spacing.md
579
1547
  },
580
- primary: { width: '100%', borderRadius: radii.md, paddingVertical: spacing.lg, alignItems: 'center' },
581
- primaryLabel: { ...typography.headline },
582
- secondary: { paddingVertical: spacing.md, alignItems: 'center' },
583
- secondaryLabel: { ...typography.body },
584
- err: { ...typography.footnote, textAlign: 'center' },
585
- fine: { ...typography.caption2, textAlign: 'center' },
586
- ghost: {
587
- flexDirection: 'row',
588
- alignItems: 'center',
589
- justifyContent: 'center',
590
- gap: spacing.xs,
1548
+ code: {
1549
+ width: '80%',
1550
+ alignSelf: 'center',
1551
+ textAlign: 'center',
1552
+ ...typography.title2,
1553
+ letterSpacing: 6,
591
1554
  borderRadius: radii.md,
592
- borderWidth: StyleSheet.hairlineWidth,
593
- paddingVertical: spacing.md
1555
+ paddingVertical: spacing.lg
594
1556
  },
595
- ghostLabel: { ...typography.footnote, fontWeight: '600' },
596
- backupRow: {
1557
+ list: { borderRadius: radii.lg, borderWidth: StyleSheet.hairlineWidth, overflow: 'hidden' },
1558
+ listRow: {
597
1559
  flexDirection: 'row',
598
1560
  alignItems: 'center',
599
1561
  gap: spacing.md,
600
- borderRadius: radii.md,
601
- borderWidth: StyleSheet.hairlineWidth,
602
- padding: spacing.lg
603
- },
604
- backupRowText: { flex: 1, gap: spacing.xs },
605
- backupRowTitle: { ...typography.headline },
606
- backupRowSub: { ...typography.footnote },
607
- paths: {
608
- width: '100%',
609
- gap: spacing.sm,
610
- borderRadius: radii.md,
611
- borderWidth: StyleSheet.hairlineWidth,
612
- padding: spacing.lg
613
- },
614
- pathsTitle: { ...typography.footnote, fontWeight: '600' },
615
- pathRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm },
616
- pathText: { ...typography.footnote, flex: 1 },
617
- pathsFine: { ...typography.caption2 },
618
- warnBox: {
619
- flexDirection: 'row',
620
- gap: spacing.sm,
621
- alignItems: 'flex-start',
622
- borderRadius: radii.md,
623
- borderWidth: StyleSheet.hairlineWidth,
624
- padding: spacing.md
1562
+ minHeight: 44,
1563
+ paddingVertical: spacing.md,
1564
+ paddingHorizontal: spacing.lg
625
1565
  },
626
- warnText: { ...typography.footnote, flex: 1 }
1566
+ listLabel: { ...typography.body, flex: 1 },
1567
+ primary: { width: '100%', borderRadius: radii.md, paddingVertical: spacing.lg, alignItems: 'center' },
1568
+ primaryLabel: { ...typography.headline },
1569
+ secondary: { paddingVertical: spacing.md, alignItems: 'center' },
1570
+ secondaryLabel: { ...typography.body }
627
1571
  })