@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,104 +1,1021 @@
1
1
  /**
2
- * Vault persistence.
2
+ * Vault enrollment metadata.
3
3
  *
4
- * - Sealed blob → expo-secure-store ('vault_seal_v1'), same Keychain
5
- * accessibility class as the wallet mnemonic. The seal alone is useless
6
- * without the physical YubiKey; SecureStore here is defense-in-depth, and
7
- * it is deliberately NOT behind LocalStorageProvider's biometric latch —
8
- * the YubiKey ceremony is the gate for anything the seal protects.
9
- * - UI metadata (serial, nickname, deposit-index counter) → AsyncStorage
10
- * ('vault_meta_v1'). Nothing secret lives here, and no key material either:
11
- * v4 carries no xpub and no card public key. The only thing that can
12
- * produce a vault address is the private HD node, which exists solely for
13
- * the length of a ceremony (or a mnemonic + passphrase recovery).
14
- *
15
- * v1-v3 records are not readable — `getMeta` returns null for anything whose
16
- * `v` isn't 4, so an un-migrated install reads as "not enrolled" rather than
17
- * deserialising into something this code would misuse.
4
+ * The SecureStore record is a this-device-only local authority, namespaced by
5
+ * wallet identity and chain. Untrusted AsyncStorage data can therefore never
6
+ * redirect a deposit. The durable recovery copy is carried by every future
7
+ * R1C output's customInstructions and restored only after that metadata has
8
+ * been checked against the output's real lock.
18
9
  */
19
- import AsyncStorage from '@react-native-async-storage/async-storage'
20
10
  import * as SecureStore from 'expo-secure-store'
21
- import { SealedBlob } from './types'
11
+ import { p256 } from '@noble/curves/nist.js'
12
+ import { VaultError } from './types'
22
13
 
23
- const SEAL_KEY = 'vault_seal_v1'
24
- const META_KEY = 'vault_meta_v1'
14
+ const META_KEY_PREFIX = 'vault_meta_v6'
15
+ const ENROLLMENT_DRAFT_KEY_PREFIX = 'vault_enrollment_draft_v1'
16
+ const SECURE_OPTIONS: SecureStore.SecureStoreOptions = {
17
+ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY
18
+ }
19
+ const MIN_KEYS = 2
20
+ const MAX_KEYS = 5
21
+ const VAULT_SLOT = 0x82
25
22
 
26
- /**
27
- * Current enrollment.
28
- *
29
- * K1-only vault: at rest this is just the sealed blob plus this plaintext
30
- * counter. No xpub and no card public key: the one secret at rest is the
31
- * seed inside the sealed blob, and nothing here narrows the search for it.
32
- */
33
- export interface VaultMetaV4 {
34
- v: 4
35
- enrolledAt: number
36
- yubiSerial: string
37
- nickname: string
38
- /** PIV slot holding the card's P-256 ECDH key (0x82). */
23
+ export type VaultScopeChain = 'main' | 'test' | 'teratest'
24
+
25
+ /** Every chain a vault can be namespaced under. One YubiKey is one physical
26
+ * object, so a destructive maintenance operation has to look at all of them —
27
+ * see `enrolledSerialsAcrossChains`. */
28
+ const SCOPE_CHAINS: readonly VaultScopeChain[] = ['main', 'test', 'teratest']
29
+
30
+ export interface VaultStoreScope {
31
+ /** Compressed secp256k1 wallet identity key, lowercase hex. */
32
+ identityKey: string
33
+ chain: VaultScopeChain
34
+ }
35
+
36
+ /** Opaque capability binding an async operation to one configured scope. */
37
+ export interface VaultScopeToken {
38
+ readonly generation: number
39
+ readonly storageKey: string
40
+ readonly chain: VaultScopeChain
41
+ }
42
+
43
+ export interface VaultKeyRecord {
44
+ serial: string
39
45
  slot: number
40
- /** Next unused deposit index — monotonic, never reused. */
41
- nextKeyIndex: number
46
+ /** 33-byte compressed P-256 public key, lowercase hex. */
47
+ pubkey: string
48
+ nickname: string
49
+ enrolledAt: number
50
+ }
51
+
52
+ export interface VaultMetaV6 {
53
+ v: 6
54
+ /** Random identifier for this enrollment, distinct after disable/re-enroll. */
55
+ vaultId: string
56
+ /** Monotonic recovery-record version. Key and nickname changes increment it. */
57
+ revision: number
58
+ createdAt: number
42
59
  lastUsedAt?: number
60
+ lastUsedSerial?: string
61
+ /** Durable two-phase revocation state. The key is no longer active for new
62
+ * outputs, but remains recoverable until its relock transaction is proven. */
63
+ pendingRemoval?: VaultPendingRemoval
64
+ /** Fresh-device recovery remains locked until a restored key proves
65
+ * possession with a live random-signature challenge. */
66
+ recovery?: VaultRecoveryState
67
+ keys: VaultKeyRecord[]
43
68
  }
44
69
 
45
- export type VaultMeta = VaultMetaV4
70
+ export interface VaultRecoveryState {
71
+ required: true
72
+ adoptedSerials: string[]
73
+ }
46
74
 
47
- const secureOpts = { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY }
75
+ export interface VaultPendingRemoval {
76
+ key: VaultKeyRecord
77
+ keyIndex: number
78
+ startedAt: number
79
+ /** The active key-set revision baked into the replacement output. */
80
+ revision: number
81
+ /** `broadcast` means authenticated wallet history has shown at least one
82
+ * matching relock transaction. Transaction history itself stays in the
83
+ * wallet; this security tombstone therefore has constant size. */
84
+ state: 'prepared' | 'broadcast'
85
+ }
86
+
87
+ /** A public-key recovery handle for a token personalized before the wizard
88
+ * atomically commits a VaultMeta. Drafts are stored under a separate scoped
89
+ * SecureStore key and are never consulted by deposit/withdrawal authority. */
90
+ export type VaultEnrollmentDraftAssurance = 'management-uncertain' | 'challenge-required' | 'ready'
91
+
92
+ export interface VaultEnrollmentDraftEntry {
93
+ record: VaultKeyRecord
94
+ assurance: VaultEnrollmentDraftAssurance
95
+ }
96
+
97
+ export type VaultEnrollmentQuarantineStage =
98
+ | 'pin-change-uncertain'
99
+ | 'pin-changed'
100
+ | 'puk-change-uncertain'
101
+ | 'puk-changed'
102
+ | 'generation-uncertain'
103
+
104
+ /** An irreversible/ambiguous global PIV credential change occurred before a
105
+ * public slot key existed. No credential is stored. Generic enrollment must
106
+ * not retry this serial until the user has administratively reset/recovered
107
+ * its dedicated PIV application. */
108
+ export interface VaultEnrollmentQuarantine {
109
+ serial: string
110
+ stage: VaultEnrollmentQuarantineStage
111
+ recordedAt: number
112
+ }
113
+
114
+ interface VaultEnrollmentDraftV1 {
115
+ v: 1
116
+ updatedAt: number
117
+ entries: VaultEnrollmentDraftEntry[]
118
+ quarantines: VaultEnrollmentQuarantine[]
119
+ }
120
+
121
+ export type VaultMeta = VaultMetaV6
122
+
123
+ let activeScope: VaultStoreScope | null = null
124
+ let scopeGeneration = 0
125
+ let mutationTail: Promise<void> = Promise.resolve()
126
+
127
+ /** Serialize every scoped write so two callers cannot both read revision N and
128
+ * then last-write competing N+1 states. A rejected mutation never poisons the
129
+ * queue. Each operation captures its scope before joining and rechecks it when
130
+ * it runs. */
131
+ function enqueueMutation<T>(operation: () => Promise<T>): Promise<T> {
132
+ const result = mutationTail.then(operation, operation)
133
+ mutationTail = result.then(
134
+ () => undefined,
135
+ () => undefined
136
+ )
137
+ return result
138
+ }
139
+
140
+ function validIdentityKey(identityKey: unknown): identityKey is string {
141
+ return typeof identityKey === 'string' && /^0[23][0-9a-f]{64}$/.test(identityKey)
142
+ }
143
+
144
+ function normalizeScope(scope: VaultStoreScope): VaultStoreScope {
145
+ if (!validIdentityKey(scope.identityKey)) {
146
+ throw new VaultError('template-invalid', 'Vault scope requires a canonical wallet identity key')
147
+ }
148
+ if (scope.chain !== 'main' && scope.chain !== 'test' && scope.chain !== 'teratest') {
149
+ throw new VaultError('template-invalid', 'Vault scope requires a supported chain')
150
+ }
151
+ return { identityKey: scope.identityKey, chain: scope.chain }
152
+ }
153
+
154
+ function scopedKey(scope = activeScope): string | null {
155
+ // SecureStore keys accept alphanumerics plus '.', '-' and '_'.
156
+ return scope ? `${META_KEY_PREFIX}_${scope.chain}_${scope.identityKey}` : null
157
+ }
158
+
159
+ /** The shape of a captured meta storage key: `<prefix>_<chain>_<identityKey>`. */
160
+ const SCOPE_KEY_PATTERN = /^vault_meta_v6_(main|test|teratest)_(0[23][0-9a-f]{64})$/
161
+
162
+ function enrollmentDraftKey(token: VaultScopeToken): string {
163
+ const match = SCOPE_KEY_PATTERN.exec(token.storageKey)
164
+ if (!match) throw new VaultError('template-invalid', 'Invalid captured vault scope')
165
+ return `${ENROLLMENT_DRAFT_KEY_PREFIX}_${match[1]}_${match[2]}`
166
+ }
167
+
168
+ /** The wallet identity a captured scope belongs to, without its chain half. */
169
+ function identityKeyFromToken(token: VaultScopeToken): string {
170
+ const match = SCOPE_KEY_PATTERN.exec(token.storageKey)
171
+ if (!match) throw new VaultError('template-invalid', 'Invalid captured vault scope')
172
+ return match[2]
173
+ }
174
+
175
+ function captureScope(required: true): VaultScopeToken
176
+ function captureScope(required: false): VaultScopeToken | null
177
+ function captureScope(required: boolean): VaultScopeToken | null {
178
+ const storageKey = scopedKey()
179
+ if (!storageKey) {
180
+ if (required) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
181
+ return null
182
+ }
183
+ return { generation: scopeGeneration, storageKey, chain: activeScope!.chain }
184
+ }
185
+
186
+ function assertScope(token: VaultScopeToken): void {
187
+ if (token.generation !== scopeGeneration || token.storageKey !== scopedKey() || token.chain !== activeScope?.chain) {
188
+ throw new VaultError('scope-changed', 'Wallet or network changed during the vault operation')
189
+ }
190
+ }
191
+
192
+ function isSafeTime(value: unknown): value is number {
193
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0
194
+ }
195
+
196
+ function isCanonicalP256(pubkey: unknown): pubkey is string {
197
+ if (typeof pubkey !== 'string' || !/^0[23][0-9a-f]{64}$/.test(pubkey)) return false
198
+ try {
199
+ const point = p256.Point.fromHex(pubkey)
200
+ point.assertValidity()
201
+ return point.toHex(true) === pubkey
202
+ } catch {
203
+ return false
204
+ }
205
+ }
206
+
207
+ function isEnrollmentDraft(value: unknown): value is VaultEnrollmentDraftV1 {
208
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
209
+ const draft = value as Record<string, unknown>
210
+ if (Object.keys(draft).some(name => !['v', 'updatedAt', 'entries', 'quarantines'].includes(name))) return false
211
+ if (
212
+ draft.v !== 1 ||
213
+ !isSafeTime(draft.updatedAt) ||
214
+ !Array.isArray(draft.entries) ||
215
+ !Array.isArray(draft.quarantines)
216
+ ) {
217
+ return false
218
+ }
219
+ if (draft.entries.length > MAX_KEYS || draft.quarantines.length > MAX_KEYS) return false
220
+ if (draft.entries.length + draft.quarantines.length < 1) return false
221
+ const entries = draft.entries as unknown[]
222
+ if (
223
+ !entries.every(value => {
224
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
225
+ const entry = value as Record<string, unknown>
226
+ return (
227
+ !Object.keys(entry).some(name => !['record', 'assurance'].includes(name)) &&
228
+ isVaultKeyRecord(entry.record) &&
229
+ (entry.assurance === 'management-uncertain' ||
230
+ entry.assurance === 'challenge-required' ||
231
+ entry.assurance === 'ready')
232
+ )
233
+ })
234
+ ) {
235
+ return false
236
+ }
237
+ const records = (entries as VaultEnrollmentDraftEntry[]).map(entry => entry.record)
238
+ if (new Set(records.map(record => record.serial)).size !== records.length) return false
239
+ if (new Set(records.map(record => record.pubkey)).size !== records.length) return false
240
+ const quarantines = draft.quarantines as unknown[]
241
+ if (
242
+ !quarantines.every(value => {
243
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
244
+ const quarantine = value as Record<string, unknown>
245
+ return (
246
+ !Object.keys(quarantine).some(name => !['serial', 'stage', 'recordedAt'].includes(name)) &&
247
+ isVaultSerial(quarantine.serial) &&
248
+ (quarantine.stage === 'pin-change-uncertain' ||
249
+ quarantine.stage === 'pin-changed' ||
250
+ quarantine.stage === 'puk-change-uncertain' ||
251
+ quarantine.stage === 'puk-changed' ||
252
+ quarantine.stage === 'generation-uncertain') &&
253
+ isSafeTime(quarantine.recordedAt)
254
+ )
255
+ })
256
+ ) {
257
+ return false
258
+ }
259
+ const quarantineSerials = (quarantines as VaultEnrollmentQuarantine[]).map(item => item.serial)
260
+ if (new Set(quarantineSerials).size !== quarantineSerials.length) return false
261
+ if (quarantineSerials.some(serial => records.some(record => record.serial === serial))) return false
262
+ return true
263
+ }
264
+
265
+ export function isVaultSerial(serial: unknown): serial is string {
266
+ return typeof serial === 'string' && /^[A-Za-z0-9._:-]{1,64}$/.test(serial)
267
+ }
268
+
269
+ export function isVaultKeyRecord(value: unknown): value is VaultKeyRecord {
270
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
271
+ const k = value as Record<string, unknown>
272
+ if (Object.keys(k).some(name => !['serial', 'slot', 'pubkey', 'nickname', 'enrolledAt'].includes(name))) return false
273
+ return (
274
+ isVaultSerial(k.serial) &&
275
+ k.slot === VAULT_SLOT &&
276
+ isCanonicalP256(k.pubkey) &&
277
+ typeof k.nickname === 'string' &&
278
+ k.nickname.length >= 1 &&
279
+ k.nickname.length <= 64 &&
280
+ k.nickname.trim() === k.nickname &&
281
+ !/[\u0000-\u001f\u007f]/.test(k.nickname) &&
282
+ isSafeTime(k.enrolledAt)
283
+ )
284
+ }
285
+
286
+ /** Strict runtime validation. Invalid/corrupt records never become authority. */
287
+ export function isVaultMeta(value: unknown): value is VaultMeta {
288
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
289
+ const m = value as Record<string, unknown>
290
+ const allowed = [
291
+ 'v',
292
+ 'vaultId',
293
+ 'revision',
294
+ 'createdAt',
295
+ 'lastUsedAt',
296
+ 'lastUsedSerial',
297
+ 'pendingRemoval',
298
+ 'recovery',
299
+ 'keys'
300
+ ]
301
+ if (Object.keys(m).some(name => !allowed.includes(name))) return false
302
+ if (m.v !== 6 || typeof m.vaultId !== 'string' || !/^[0-9a-f]{64}$/.test(m.vaultId)) return false
303
+ if (typeof m.revision !== 'number' || !Number.isSafeInteger(m.revision) || m.revision < 1) return false
304
+ if (!isSafeTime(m.createdAt)) return false
305
+ if (!Array.isArray(m.keys) || m.keys.length < MIN_KEYS || m.keys.length > MAX_KEYS) return false
306
+ if (!m.keys.every(isVaultKeyRecord)) return false
307
+ const keys = m.keys as VaultKeyRecord[]
308
+ if (new Set(keys.map(k => k.serial)).size !== keys.length) return false
309
+ if (new Set(keys.map(k => k.pubkey)).size !== keys.length) return false
310
+ if (m.lastUsedAt !== undefined && !isSafeTime(m.lastUsedAt)) return false
311
+ if (m.lastUsedSerial !== undefined) {
312
+ if (typeof m.lastUsedSerial !== 'string' || !keys.some(k => k.serial === m.lastUsedSerial)) return false
313
+ if (m.lastUsedAt === undefined) return false
314
+ }
315
+ if (m.pendingRemoval !== undefined) {
316
+ const p = m.pendingRemoval
317
+ if (p === null || typeof p !== 'object' || Array.isArray(p)) return false
318
+ const pending = p as Record<string, unknown>
319
+ if (Object.keys(pending).some(name => !['key', 'keyIndex', 'startedAt', 'revision', 'state'].includes(name))) {
320
+ return false
321
+ }
322
+ if (!isVaultKeyRecord(pending.key)) return false
323
+ const removed = pending.key as VaultKeyRecord
324
+ if (keys.some(k => k.serial === removed.serial || k.pubkey === removed.pubkey)) return false
325
+ if (typeof pending.keyIndex !== 'number' || !Number.isSafeInteger(pending.keyIndex)) return false
326
+ if (pending.keyIndex < 0 || pending.keyIndex > keys.length) return false
327
+ if (!isSafeTime(pending.startedAt) || pending.revision !== m.revision) return false
328
+ if (pending.state !== 'prepared' && pending.state !== 'broadcast') return false
329
+ }
330
+ if (m.recovery !== undefined) {
331
+ const r = m.recovery
332
+ if (r === null || typeof r !== 'object' || Array.isArray(r)) return false
333
+ const recovery = r as Record<string, unknown>
334
+ if (Object.keys(recovery).some(name => !['required', 'adoptedSerials'].includes(name))) return false
335
+ if (recovery.required !== true || !Array.isArray(recovery.adoptedSerials)) return false
336
+ if (!recovery.adoptedSerials.every(isVaultSerial)) return false
337
+ if (new Set(recovery.adoptedSerials as string[]).size !== recovery.adoptedSerials.length) return false
338
+ const known = new Set(keys.map(k => k.serial))
339
+ if (m.pendingRemoval) known.add((m.pendingRemoval as VaultPendingRemoval).key.serial)
340
+ if (!(recovery.adoptedSerials as string[]).every(serial => known.has(serial))) return false
341
+ }
342
+ return true
343
+ }
344
+
345
+ /** Parse one stored namespace. Corrupt is never "absent": a caller that acts on
346
+ * an empty answer must fail instead of reading a smaller key list than the
347
+ * truth. */
348
+ function parseStoredMeta(raw: string | null, corruptMessage: string): VaultMeta | null {
349
+ if (!raw) return null
350
+ let parsed: unknown
351
+ try {
352
+ parsed = JSON.parse(raw)
353
+ } catch {
354
+ throw new VaultError('template-invalid', corruptMessage)
355
+ }
356
+ if (!isVaultMeta(parsed)) throw new VaultError('template-invalid', corruptMessage)
357
+ return parsed
358
+ }
359
+
360
+ async function readMeta(token: VaultScopeToken): Promise<VaultMeta | null> {
361
+ assertScope(token)
362
+ const raw = await SecureStore.getItemAsync(token.storageKey, SECURE_OPTIONS)
363
+ assertScope(token)
364
+ return parseStoredMeta(raw, 'Stored vault enrollment metadata is corrupt')
365
+ }
366
+
367
+ async function writeMeta(token: VaultScopeToken, meta: unknown): Promise<void> {
368
+ const checked = checkedMeta(meta)
369
+ assertScope(token)
370
+ await SecureStore.setItemAsync(token.storageKey, JSON.stringify(checked), SECURE_OPTIONS)
371
+ // The write still targeted the captured namespace if the scope changed while
372
+ // storage was pending, but its caller must not continue as though it updated
373
+ // the newly active wallet.
374
+ assertScope(token)
375
+ }
376
+
377
+ async function readEnrollmentDraft(
378
+ token: VaultScopeToken,
379
+ requireActiveScope: boolean
380
+ ): Promise<VaultEnrollmentDraftV1 | null> {
381
+ if (requireActiveScope) assertScope(token)
382
+ const raw = await SecureStore.getItemAsync(enrollmentDraftKey(token), SECURE_OPTIONS)
383
+ if (requireActiveScope) assertScope(token)
384
+ if (!raw) return null
385
+ let parsed: unknown
386
+ try {
387
+ parsed = JSON.parse(raw)
388
+ } catch {
389
+ throw new VaultError('template-invalid', 'Stored vault enrollment draft is corrupt')
390
+ }
391
+ if (!isEnrollmentDraft(parsed)) throw new VaultError('template-invalid', 'Stored vault enrollment draft is corrupt')
392
+ return parsed
393
+ }
394
+
395
+ /** Write only the non-authoritative enrollment-draft namespace captured at
396
+ * ceremony start. This deliberately remains possible after a scope switch so
397
+ * an already-generated A key gets a durable A recovery handle; the derived key
398
+ * can never target active wallet B's metadata. */
399
+ async function writeCapturedEnrollmentDraft(
400
+ token: VaultScopeToken,
401
+ draft: VaultEnrollmentDraftV1 | null
402
+ ): Promise<void> {
403
+ const key = enrollmentDraftKey(token)
404
+ if (draft !== null && !isEnrollmentDraft(draft)) {
405
+ throw new VaultError('template-invalid', 'Invalid vault enrollment draft')
406
+ }
407
+ if (draft) await SecureStore.setItemAsync(key, JSON.stringify(draft), SECURE_OPTIONS)
408
+ else await SecureStore.deleteItemAsync(key, SECURE_OPTIONS)
409
+ }
410
+
411
+ function draftAssuranceRank(assurance: VaultEnrollmentDraftAssurance): number {
412
+ if (assurance === 'management-uncertain') return 0
413
+ if (assurance === 'challenge-required') return 1
414
+ return 2
415
+ }
416
+
417
+ function isQuarantineStage(value: unknown): value is VaultEnrollmentQuarantineStage {
418
+ return (
419
+ value === 'pin-change-uncertain' ||
420
+ value === 'pin-changed' ||
421
+ value === 'puk-change-uncertain' ||
422
+ value === 'puk-changed' ||
423
+ value === 'generation-uncertain'
424
+ )
425
+ }
426
+
427
+ async function requireMeta(token: VaultScopeToken): Promise<VaultMeta> {
428
+ const meta = await readMeta(token)
429
+ if (!meta) throw new VaultError('not-enrolled', 'Vault is not set up')
430
+ return meta
431
+ }
432
+
433
+ function checkedMeta(meta: unknown): VaultMeta {
434
+ if (!isVaultMeta(meta)) throw new VaultError('template-invalid', 'Invalid vault enrollment metadata')
435
+ return meta
436
+ }
437
+
438
+ function sameRemovalKey(a: VaultPendingRemoval, b: VaultPendingRemoval): boolean {
439
+ return a.revision === b.revision && a.keyIndex === b.keyIndex && JSON.stringify(a.key) === JSON.stringify(b.key)
440
+ }
441
+
442
+ /** Merge two observations of one in-flight removal. Authenticated outputs can
443
+ * prove that a relock was broadcast after a crash left the local state at
444
+ * `prepared`; once observed, `broadcast` never rolls back. Different removed
445
+ * keys at one revision are an irreconcilable authority conflict. */
446
+ function mergePendingRemoval(
447
+ local: VaultPendingRemoval | undefined,
448
+ recovered: VaultPendingRemoval | undefined
449
+ ): VaultPendingRemoval | undefined {
450
+ if (!local) return recovered ? { ...recovered, key: { ...recovered.key } } : undefined
451
+ if (!recovered) return { ...local, key: { ...local.key } }
452
+ if (!sameRemovalKey(local, recovered)) {
453
+ throw new VaultError('template-invalid', 'Conflicting key removals share the same vault revision')
454
+ }
455
+ return {
456
+ ...local,
457
+ startedAt: Math.min(local.startedAt, recovered.startedAt),
458
+ state: local.state === 'broadcast' || recovered.state === 'broadcast' ? 'broadcast' : 'prepared'
459
+ }
460
+ }
48
461
 
49
462
  export const vaultStore = {
50
- async isEnrolled(): Promise<boolean> {
51
- const [meta, seal] = await Promise.all([vaultStore.getMeta(), vaultStore.getSeal()])
52
- return meta != null && seal != null
463
+ /** Select the only wallet+chain namespace subsequent calls may access. */
464
+ configureScope(scope: VaultStoreScope): void {
465
+ activeScope = normalizeScope(scope)
466
+ scopeGeneration++
467
+ },
468
+
469
+ /** Drop the in-memory authority during logout, wallet rebuild or teardown. */
470
+ clearScope(): void {
471
+ activeScope = null
472
+ scopeGeneration++
473
+ },
474
+
475
+ getScope(): VaultStoreScope | null {
476
+ return activeScope ? { ...activeScope } : null
477
+ },
478
+
479
+ /** Capture the current wallet+chain epoch before starting async work. */
480
+ captureScopeToken(): VaultScopeToken {
481
+ return captureScope(true)
482
+ },
483
+
484
+ /** Fail if a captured operation outlived its wallet or chain. */
485
+ assertScopeToken(token: VaultScopeToken): void {
486
+ assertScope(token)
53
487
  },
54
488
 
55
- async getSeal(): Promise<SealedBlob | null> {
56
- const raw = await SecureStore.getItemAsync(SEAL_KEY, secureOpts)
57
- if (!raw) return null
58
- try {
59
- return JSON.parse(raw) as SealedBlob
60
- } catch {
61
- return null
489
+ /** Public recovery handles awaiting an atomic enrollment commit. These are
490
+ * never read by getMeta or any transfer path. */
491
+ async getEnrollmentDrafts(scopeToken?: VaultScopeToken): Promise<VaultEnrollmentDraftEntry[]> {
492
+ const token = scopeToken ?? captureScope(true)
493
+ const draft = await readEnrollmentDraft(token, true)
494
+ return draft?.entries.map(entry => ({ ...entry, record: { ...entry.record } })) ?? []
495
+ },
496
+
497
+ async getEnrollmentQuarantines(scopeToken?: VaultScopeToken): Promise<VaultEnrollmentQuarantine[]> {
498
+ const token = scopeToken ?? captureScope(true)
499
+ const draft = await readEnrollmentDraft(token, true)
500
+ return draft?.quarantines.map(item => ({ ...item })) ?? []
501
+ },
502
+
503
+ /** Preserve a generated key under the wallet+chain captured before token
504
+ * contact. Unlike authority writes, this may finish after the active scope
505
+ * changes: it can write only the separate draft key encoded in `scopeToken`.
506
+ * Assurance is monotonic and same-serial/pubkey conflicts fail closed. */
507
+ async preserveEnrollmentDraft(
508
+ entry: VaultEnrollmentDraftEntry,
509
+ scopeToken: VaultScopeToken
510
+ ): Promise<VaultEnrollmentDraftEntry> {
511
+ if (
512
+ !isVaultKeyRecord(entry.record) ||
513
+ (entry.assurance !== 'management-uncertain' &&
514
+ entry.assurance !== 'challenge-required' &&
515
+ entry.assurance !== 'ready')
516
+ ) {
517
+ throw new VaultError('template-invalid', 'Invalid vault enrollment recovery handle')
62
518
  }
519
+ // Validate the captured namespace before entering the shared mutation
520
+ // queue. No active-scope assertion belongs here; see the method contract.
521
+ enrollmentDraftKey(scopeToken)
522
+ return enqueueMutation(async () => {
523
+ const current = await readEnrollmentDraft(scopeToken, false)
524
+ const entries = current?.entries.map(item => ({ ...item, record: { ...item.record } })) ?? []
525
+ const quarantines = current?.quarantines.map(item => ({ ...item })) ?? []
526
+ const serialMatch = entries.find(item => item.record.serial === entry.record.serial)
527
+ const pubkeyMatch = entries.find(item => item.record.pubkey === entry.record.pubkey)
528
+ if (
529
+ (serialMatch && serialMatch.record.pubkey !== entry.record.pubkey) ||
530
+ (pubkeyMatch && pubkeyMatch.record.serial !== entry.record.serial)
531
+ ) {
532
+ throw new VaultError('template-invalid', 'Conflicting generated keys share an enrollment draft')
533
+ }
534
+ const existingIndex = entries.findIndex(
535
+ item => item.record.serial === entry.record.serial && item.record.pubkey === entry.record.pubkey
536
+ )
537
+ const saved: VaultEnrollmentDraftEntry =
538
+ existingIndex < 0
539
+ ? { assurance: entry.assurance, record: { ...entry.record } }
540
+ : draftAssuranceRank(entries[existingIndex].assurance) >= draftAssuranceRank(entry.assurance)
541
+ ? entries[existingIndex]
542
+ : { assurance: entry.assurance, record: { ...entry.record } }
543
+ if (existingIndex < 0) entries.push(saved)
544
+ else entries[existingIndex] = saved
545
+ const retainedQuarantines = quarantines.filter(item => item.serial !== entry.record.serial)
546
+ const updatedAt = Date.now()
547
+ if (!isSafeTime(updatedAt)) throw new VaultError('template-invalid', 'Invalid enrollment draft time')
548
+ await writeCapturedEnrollmentDraft(scopeToken, {
549
+ v: 1,
550
+ updatedAt,
551
+ entries,
552
+ quarantines: retainedQuarantines
553
+ })
554
+ return { ...saved, record: { ...saved.record } }
555
+ })
63
556
  },
64
557
 
65
- async setSeal(b: SealedBlob): Promise<void> {
66
- await SecureStore.setItemAsync(SEAL_KEY, JSON.stringify(b), secureOpts)
558
+ /** Persist the no-secret intent marker BEFORE the first irreversible PIV
559
+ * command for this serial. A process death while the APDU is in flight then
560
+ * leaves a durable quarantine instead of making the next launch retry it as
561
+ * a fresh token. Later state changes use transitionEnrollmentQuarantine's
562
+ * compare-and-swap contract. */
563
+ async preserveEnrollmentQuarantine(
564
+ serial: string,
565
+ stage: VaultEnrollmentQuarantineStage,
566
+ scopeToken: VaultScopeToken
567
+ ): Promise<VaultEnrollmentQuarantine> {
568
+ if (!isVaultSerial(serial) || !isQuarantineStage(stage)) {
569
+ throw new VaultError('template-invalid', 'Invalid enrollment quarantine marker')
570
+ }
571
+ enrollmentDraftKey(scopeToken)
572
+ return enqueueMutation(async () => {
573
+ const current = await readEnrollmentDraft(scopeToken, false)
574
+ const entries = current?.entries.map(item => ({ ...item, record: { ...item.record } })) ?? []
575
+ if (entries.some(entry => entry.record.serial === serial)) {
576
+ throw new VaultError('template-invalid', 'A generated-key draft cannot be replaced by a credential marker')
577
+ }
578
+ const quarantines = current?.quarantines.map(item => ({ ...item })) ?? []
579
+ const index = quarantines.findIndex(item => item.serial === serial)
580
+ const recordedAt = Date.now()
581
+ if (!isSafeTime(recordedAt)) throw new VaultError('template-invalid', 'Invalid enrollment quarantine time')
582
+ const candidate: VaultEnrollmentQuarantine = { serial, stage, recordedAt }
583
+ let saved = candidate
584
+ if (index < 0) quarantines.push(candidate)
585
+ else if (quarantines[index].stage === stage) saved = quarantines[index]
586
+ else throw new VaultError('template-invalid', 'PIV enrollment mutation state changed unexpectedly')
587
+ await writeCapturedEnrollmentDraft(scopeToken, { v: 1, updatedAt: recordedAt, entries, quarantines })
588
+ return { ...saved }
589
+ })
67
590
  },
68
591
 
69
- async getMeta(): Promise<VaultMeta | null> {
70
- const raw = await AsyncStorage.getItem(META_KEY)
71
- if (!raw) return null
72
- try {
73
- const parsed = JSON.parse(raw) as { v?: unknown }
74
- return parsed?.v === 4 ? (parsed as VaultMeta) : null
75
- } catch {
76
- return null
592
+ /** Advance or resolve one in-memory enrollment attempt only if durable state
593
+ * still matches the stage written before its APDU. The narrow transition set
594
+ * prevents an old callback from clearing or advancing a newer quarantine. */
595
+ async transitionEnrollmentQuarantine(
596
+ serial: string,
597
+ from: VaultEnrollmentQuarantineStage,
598
+ to: VaultEnrollmentQuarantineStage | null,
599
+ scopeToken: VaultScopeToken
600
+ ): Promise<void> {
601
+ if (!isVaultSerial(serial) || !isQuarantineStage(from) || (to !== null && !isQuarantineStage(to))) {
602
+ throw new VaultError('template-invalid', 'Invalid enrollment quarantine transition')
77
603
  }
604
+ const allowed =
605
+ (from === 'pin-change-uncertain' && (to === 'pin-changed' || to === null)) ||
606
+ (from === 'pin-changed' && to === 'puk-change-uncertain') ||
607
+ (from === 'puk-change-uncertain' && (to === 'pin-changed' || to === 'puk-changed' || to === null)) ||
608
+ (from === 'puk-changed' && to === 'generation-uncertain')
609
+ if (!allowed) throw new VaultError('template-invalid', 'Disallowed enrollment quarantine transition')
610
+ enrollmentDraftKey(scopeToken)
611
+ return enqueueMutation(async () => {
612
+ const current = await readEnrollmentDraft(scopeToken, false)
613
+ if (!current) throw new VaultError('template-invalid', 'Enrollment quarantine is missing')
614
+ const entries = current.entries.map(item => ({ ...item, record: { ...item.record } }))
615
+ const quarantines = current.quarantines.map(item => ({ ...item }))
616
+ const index = quarantines.findIndex(item => item.serial === serial)
617
+ if (index < 0 || quarantines[index].stage !== from) {
618
+ throw new VaultError('template-invalid', 'Enrollment quarantine no longer matches this operation')
619
+ }
620
+ const updatedAt = Date.now()
621
+ if (!isSafeTime(updatedAt)) throw new VaultError('template-invalid', 'Invalid enrollment quarantine time')
622
+ if (to === null) quarantines.splice(index, 1)
623
+ else quarantines[index] = { serial, stage: to, recordedAt: updatedAt }
624
+ if (entries.length === 0 && quarantines.length === 0) await writeCapturedEnrollmentDraft(scopeToken, null)
625
+ else await writeCapturedEnrollmentDraft(scopeToken, { v: 1, updatedAt, entries, quarantines })
626
+ })
627
+ },
628
+
629
+ /** Remove records only after their authoritative meta write succeeds. */
630
+ async consumeEnrollmentDrafts(serials: readonly string[], scopeToken?: VaultScopeToken): Promise<void> {
631
+ const token = scopeToken ?? captureScope(true)
632
+ if (!serials.every(isVaultSerial)) throw new VaultError('template-invalid', 'Invalid enrollment draft serial')
633
+ const consumed = new Set(serials)
634
+ return enqueueMutation(async () => {
635
+ const current = await readEnrollmentDraft(token, true)
636
+ if (!current) return
637
+ const entries = current.entries.filter(entry => !consumed.has(entry.record.serial))
638
+ assertScope(token)
639
+ if (entries.length === 0 && current.quarantines.length === 0) await writeCapturedEnrollmentDraft(token, null)
640
+ else {
641
+ const updatedAt = Date.now()
642
+ if (!isSafeTime(updatedAt)) throw new VaultError('template-invalid', 'Invalid enrollment draft time')
643
+ await writeCapturedEnrollmentDraft(token, {
644
+ v: 1,
645
+ updatedAt,
646
+ entries,
647
+ quarantines: current.quarantines
648
+ })
649
+ }
650
+ assertScope(token)
651
+ })
652
+ },
653
+
654
+ /** Explicitly abandon a non-authoritative handle after the user decides to
655
+ * reset that token or use another one. */
656
+ async discardEnrollmentDraft(serial: string, scopeToken?: VaultScopeToken): Promise<void> {
657
+ return vaultStore.consumeEnrollmentDrafts([serial], scopeToken)
658
+ },
659
+
660
+ /** Call only after the user has reset/recovered the token's whole PIV
661
+ * application; removing the marker does not itself make any card change. */
662
+ async discardEnrollmentQuarantine(serial: string, scopeToken?: VaultScopeToken): Promise<void> {
663
+ const token = scopeToken ?? captureScope(true)
664
+ if (!isVaultSerial(serial)) throw new VaultError('template-invalid', 'Invalid enrollment quarantine serial')
665
+ return enqueueMutation(async () => {
666
+ const current = await readEnrollmentDraft(token, true)
667
+ if (!current) return
668
+ const quarantines = current.quarantines.filter(item => item.serial !== serial)
669
+ assertScope(token)
670
+ if (current.entries.length === 0 && quarantines.length === 0) await writeCapturedEnrollmentDraft(token, null)
671
+ else {
672
+ const updatedAt = Date.now()
673
+ if (!isSafeTime(updatedAt)) throw new VaultError('template-invalid', 'Invalid enrollment quarantine time')
674
+ await writeCapturedEnrollmentDraft(token, { v: 1, updatedAt, entries: current.entries, quarantines })
675
+ }
676
+ assertScope(token)
677
+ })
678
+ },
679
+
680
+ async clearEnrollmentDrafts(scopeToken?: VaultScopeToken): Promise<void> {
681
+ const token = scopeToken ?? captureScope(true)
682
+ return enqueueMutation(async () => {
683
+ assertScope(token)
684
+ await writeCapturedEnrollmentDraft(token, null)
685
+ assertScope(token)
686
+ })
687
+ },
688
+
689
+ async isEnrolled(): Promise<boolean> {
690
+ return (await vaultStore.getMeta()) != null
78
691
  },
79
692
 
80
- async setMeta(m: VaultMeta): Promise<void> {
81
- await AsyncStorage.setItem(META_KEY, JSON.stringify(m))
693
+ async getMeta(scopeToken?: VaultScopeToken): Promise<VaultMeta | null> {
694
+ const token = scopeToken ?? captureScope(false)
695
+ return token ? readMeta(token) : null
82
696
  },
83
697
 
84
698
  /**
85
- * Reserve the next deposit index and advance the counter.
699
+ * Every YubiKey serial this wallet identity has enrolled under ANY chain,
700
+ * including one mid-removal. Deliberately crosses the chain half of the
701
+ * namespace — and only that half.
702
+ *
703
+ * Metadata is namespaced per wallet+chain because a deposit must never be
704
+ * redirected across wallets. A YubiKey is not: it is one physical object that
705
+ * can be a live signer for the mainnet vault while the app is showing
706
+ * testnet. `getMeta` sees one namespace, so it answers "empty" for a card
707
+ * that is holding real money — which is safe for a read and catastrophic for
708
+ * an erase. Destructive maintenance (services/vault/pivReset.ts) must ask
709
+ * this instead.
86
710
  *
87
- * Persisted before returning: a crash between deposits must never reissue an
88
- * index, since two deposits to the same K1 key are linkable and confusing.
711
+ * Returns serials only: no other namespace's metadata leaves this function.
712
+ * Fails closed — unreadable or corrupt metadata in ANY chain throws rather
713
+ * than reporting a shorter list, because the caller destroys a key when the
714
+ * answer comes back without it. Does NOT cross wallet identities; that
715
+ * residual needs a device-wide serial index (SecureStore cannot be
716
+ * enumerated) and is tracked outside this module.
717
+ */
718
+ async enrolledSerialsAcrossChains(scopeToken?: VaultScopeToken): Promise<string[]> {
719
+ const token = scopeToken ?? captureScope(true)
720
+ const identityKey = identityKeyFromToken(token)
721
+ assertScope(token)
722
+ const serials = new Set<string>()
723
+ for (const chain of SCOPE_CHAINS) {
724
+ const storageKey = `${META_KEY_PREFIX}_${chain}_${identityKey}`
725
+ const raw = await SecureStore.getItemAsync(storageKey, SECURE_OPTIONS)
726
+ const meta = parseStoredMeta(raw, `Stored vault enrollment metadata is corrupt (${chain})`)
727
+ for (const key of meta?.keys ?? []) serials.add(key.serial)
728
+ if (meta?.pendingRemoval) serials.add(meta.pendingRemoval.key.serial)
729
+ }
730
+ // The read spanned chains, never wallets: the operation still must not
731
+ // outlive the wallet it was captured for.
732
+ assertScope(token)
733
+ return [...serials]
734
+ },
735
+
736
+ async setMeta(meta: VaultMeta, scopeToken?: VaultScopeToken): Promise<void> {
737
+ const token = scopeToken ?? captureScope(true)
738
+ return enqueueMutation(() => writeMeta(token, meta))
739
+ },
740
+
741
+ /** Create one enrollment without a read/write scope-switch window. */
742
+ async createEnrollment(meta: VaultMeta, scopeToken?: VaultScopeToken): Promise<void> {
743
+ const token = scopeToken ?? captureScope(true)
744
+ return enqueueMutation(async () => {
745
+ const existing = await readMeta(token)
746
+ if (existing?.keys.length) {
747
+ throw new VaultError(
748
+ 'key-already-enrolled',
749
+ 'A vault is already enrolled on this device; disable it before enrolling again',
750
+ undefined,
751
+ { serial: existing.keys[0].serial }
752
+ )
753
+ }
754
+ await writeMeta(token, meta)
755
+ })
756
+ },
757
+
758
+ /**
759
+ * Restore the scoped cache from metadata already authenticated against a
760
+ * spendable output's real R1C lock. The caller performs that lock check;
761
+ * this boundary performs strict schema validation and refuses to replace a
762
+ * different live enrollment.
763
+ */
764
+ async restoreVerifiedMeta(meta: VaultMeta, scopeToken?: VaultScopeToken): Promise<void> {
765
+ const token = scopeToken ?? captureScope(true)
766
+ const checked = checkedMeta(meta)
767
+ return enqueueMutation(async () => {
768
+ const current = await readMeta(token)
769
+ if (current && current.vaultId !== checked.vaultId) {
770
+ throw new VaultError('template-invalid', 'Refusing to replace a different vault enrollment')
771
+ }
772
+ if (current && current.createdAt !== checked.createdAt) {
773
+ throw new VaultError('template-invalid', 'Conflicting vault creation times share an enrollment id')
774
+ }
775
+ if (current && checked.revision < current.revision) {
776
+ throw new VaultError('template-invalid', 'Refusing to restore stale vault enrollment metadata')
777
+ }
778
+ if (
779
+ current &&
780
+ checked.revision === current.revision &&
781
+ JSON.stringify(checked.keys) !== JSON.stringify(current.keys)
782
+ ) {
783
+ throw new VaultError('template-invalid', 'Conflicting vault key sets share the same revision')
784
+ }
785
+
786
+ // A same-revision output is another observation of the authority already
787
+ // stored on this device. Merge a discovered tombstone conservatively and
788
+ // preserve local-only recovery/usage state. In particular, replaying a
789
+ // same-revision output must never clear an adoption gate or an unfinished
790
+ // key removal.
791
+ if (current && checked.revision === current.revision) {
792
+ const pendingRemoval = mergePendingRemoval(current.pendingRemoval, checked.pendingRemoval)
793
+ const restored: VaultMeta = { ...current }
794
+ if (pendingRemoval) restored.pendingRemoval = pendingRemoval
795
+ else delete restored.pendingRemoval
796
+ await writeMeta(token, restored)
797
+ return
798
+ }
799
+
800
+ const knownSerials = new Set([
801
+ ...checked.keys.map(key => key.serial),
802
+ ...(checked.pendingRemoval ? [checked.pendingRemoval.key.serial] : [])
803
+ ])
804
+ const activeSerials = new Set(checked.keys.map(key => key.serial))
805
+ const restored: VaultMeta = {
806
+ ...checked,
807
+ // last-use and adoption status are device-local facts, never output
808
+ // instructions supplied by a recovery caller.
809
+ recovery: {
810
+ required: true,
811
+ adoptedSerials: (current?.recovery?.adoptedSerials ?? []).filter(serial => knownSerials.has(serial))
812
+ }
813
+ }
814
+ delete restored.lastUsedAt
815
+ delete restored.lastUsedSerial
816
+ if (current?.lastUsedSerial && activeSerials.has(current.lastUsedSerial)) {
817
+ restored.lastUsedAt = current.lastUsedAt
818
+ restored.lastUsedSerial = current.lastUsedSerial
819
+ }
820
+ await writeMeta(token, restored)
821
+ })
822
+ },
823
+
824
+ async markKeyAdopted(record: Pick<VaultKeyRecord, 'serial' | 'pubkey'>, scopeToken?: VaultScopeToken): Promise<void> {
825
+ const token = scopeToken ?? captureScope(true)
826
+ return enqueueMutation(async () => {
827
+ const meta = await readMeta(token)
828
+ if (!meta) throw new VaultError('not-enrolled', 'Vault is not set up')
829
+ const known = [...meta.keys, ...(meta.pendingRemoval ? [meta.pendingRemoval.key] : [])]
830
+ if (!known.some(k => k.serial === record.serial && k.pubkey === record.pubkey)) {
831
+ throw new VaultError('wrong-key', 'Challenged key does not match restored vault metadata')
832
+ }
833
+ if (!meta.recovery || meta.recovery.adoptedSerials.includes(record.serial)) return
834
+ await writeMeta(token, {
835
+ ...meta,
836
+ recovery: { required: true, adoptedSerials: [...meta.recovery.adoptedSerials, record.serial] }
837
+ })
838
+ })
839
+ },
840
+
841
+ async requireKeyAdopted(serial: string, scopeToken?: VaultScopeToken): Promise<void> {
842
+ const token = scopeToken ?? captureScope(true)
843
+ const meta = await requireMeta(token)
844
+ if (meta.recovery?.required && !meta.recovery.adoptedSerials.includes(serial)) {
845
+ throw new VaultError('key-not-adopted', 'Prove possession of this restored YubiKey before withdrawing')
846
+ }
847
+ },
848
+
849
+ async addKey(k: VaultKeyRecord, scopeToken?: VaultScopeToken): Promise<VaultMeta> {
850
+ const token = scopeToken ?? captureScope(true)
851
+ if (!isVaultKeyRecord(k)) throw new VaultError('template-invalid', 'Invalid vault key record')
852
+ return enqueueMutation(async () => {
853
+ const meta = await requireMeta(token)
854
+ if (meta.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal first')
855
+ if (meta.keys.length >= MAX_KEYS) {
856
+ throw new VaultError('too-many-keys', `The vault already has ${MAX_KEYS} keys`)
857
+ }
858
+ if (meta.keys.some(x => x.serial === k.serial || x.pubkey === k.pubkey)) {
859
+ throw new VaultError('key-already-enrolled', k.serial, undefined, { serial: k.serial })
860
+ }
861
+ const next: VaultMeta = { ...meta, revision: meta.revision + 1, keys: [...meta.keys, k] }
862
+ await writeMeta(token, next)
863
+ return next
864
+ })
865
+ },
866
+
867
+ async beginKeyRemoval(serial: string, scopeToken?: VaultScopeToken): Promise<VaultMeta> {
868
+ const token = scopeToken ?? captureScope(true)
869
+ return enqueueMutation(async () => {
870
+ const meta = await requireMeta(token)
871
+ if (meta.pendingRemoval) throw new VaultError('relock-required', 'Another key removal is already pending')
872
+ if (meta.keys.length <= MIN_KEYS) {
873
+ throw new VaultError('last-keys', `A vault needs at least ${MIN_KEYS} keys`)
874
+ }
875
+ if (!meta.keys.some(x => x.serial === serial)) {
876
+ throw new VaultError('not-enrolled', `Key ${serial} is not enrolled`)
877
+ }
878
+ const keyIndex = meta.keys.findIndex(x => x.serial === serial)
879
+ const revision = meta.revision + 1
880
+ const next: VaultMeta = {
881
+ ...meta,
882
+ revision,
883
+ keys: meta.keys.filter(x => x.serial !== serial),
884
+ pendingRemoval: {
885
+ key: meta.keys[keyIndex],
886
+ keyIndex,
887
+ startedAt: Date.now(),
888
+ revision,
889
+ state: 'prepared'
890
+ }
891
+ }
892
+ if (next.lastUsedSerial === serial) {
893
+ delete next.lastUsedSerial
894
+ delete next.lastUsedAt
895
+ }
896
+ await writeMeta(token, next)
897
+ return next
898
+ })
899
+ },
900
+
901
+ async markKeyRemovalBroadcast(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
902
+ const token = scopeToken ?? captureScope(true)
903
+ return enqueueMutation(async () => {
904
+ const meta = await requireMeta(token)
905
+ const pending = meta.pendingRemoval
906
+ if (!pending) throw new VaultError('not-enrolled', 'No key removal is pending')
907
+ if (pending.state === 'broadcast') return meta
908
+ const next: VaultMeta = {
909
+ ...meta,
910
+ pendingRemoval: { ...pending, state: 'broadcast' }
911
+ }
912
+ await writeMeta(token, next)
913
+ return next
914
+ })
915
+ },
916
+
917
+ /** Caller must establish from authenticated action history and two complete
918
+ * output scans that no spendable lock still authorizes the removed key and
919
+ * that no relevant action is pending before invoking. */
920
+ async finalizeProvenKeyRemoval(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
921
+ const token = scopeToken ?? captureScope(true)
922
+ return enqueueMutation(async () => {
923
+ const meta = await requireMeta(token)
924
+ const pending = meta.pendingRemoval
925
+ if (!pending || pending.state !== 'broadcast') {
926
+ throw new VaultError('template-invalid', 'No broadcast key removal is ready for proven finalization')
927
+ }
928
+ const next: VaultMeta = { ...meta }
929
+ delete next.pendingRemoval
930
+ await writeMeta(token, next)
931
+ return next
932
+ })
933
+ },
934
+
935
+ /**
936
+ * Complete a removal when the authoritative preflight and postflight scans
937
+ * both prove there were no vault outputs to relock. The transfer layer owns
938
+ * those scans and serializes them with deposits; this method only permits
939
+ * the corresponding untouched, unbroadcast state transition.
89
940
  */
90
- async takeNextIndex(): Promise<number | null> {
91
- const meta = await vaultStore.getMeta()
92
- if (!meta) return null
93
- const index = meta.nextKeyIndex
94
- await vaultStore.setMeta({ ...meta, nextKeyIndex: index + 1 })
95
- return index
96
- },
97
-
98
- /** Remove everything, including the sealed blob — used by disable +
99
- * recovery flows. */
100
- async clear(): Promise<void> {
101
- await SecureStore.deleteItemAsync(SEAL_KEY).catch(() => {})
102
- await AsyncStorage.removeItem(META_KEY)
941
+ async finalizeEmptyKeyRemoval(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
942
+ const token = scopeToken ?? captureScope(true)
943
+ return enqueueMutation(async () => {
944
+ const meta = await requireMeta(token)
945
+ const pending = meta.pendingRemoval
946
+ if (!pending || pending.state !== 'prepared') {
947
+ throw new VaultError('template-invalid', 'Empty-vault removal does not match the pending state')
948
+ }
949
+ const next: VaultMeta = { ...meta }
950
+ delete next.pendingRemoval
951
+ await writeMeta(token, next)
952
+ return next
953
+ })
954
+ },
955
+
956
+ /**
957
+ * Restore a prepared key only after the caller has proved no transaction was
958
+ * broadcast (for example, its reserved action was successfully aborted).
959
+ */
960
+ async cancelUnbroadcastKeyRemoval(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
961
+ const token = scopeToken ?? captureScope(true)
962
+ return enqueueMutation(async () => {
963
+ const meta = await requireMeta(token)
964
+ const pending = meta.pendingRemoval
965
+ if (!pending || pending.state !== 'prepared') {
966
+ throw new VaultError('relock-required', 'A broadcast or unknown removal cannot be cancelled')
967
+ }
968
+ const keys = [...meta.keys]
969
+ keys.splice(pending.keyIndex, 0, pending.key)
970
+ const next: VaultMeta = { ...meta, revision: meta.revision + 1, keys }
971
+ delete next.pendingRemoval
972
+ await writeMeta(token, next)
973
+ return next
974
+ })
975
+ },
976
+
977
+ async renameKey(serial: string, nickname: string, scopeToken?: VaultScopeToken): Promise<VaultMeta> {
978
+ const token = scopeToken ?? captureScope(true)
979
+ return enqueueMutation(async () => {
980
+ const meta = await requireMeta(token)
981
+ if (meta.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal first')
982
+ const clean = nickname.trim()
983
+ if (clean.length < 1 || clean.length > 64) throw new VaultError('template-invalid', 'Invalid vault key nickname')
984
+ if (!meta.keys.some(k => k.serial === serial))
985
+ throw new VaultError('not-enrolled', `Key ${serial} is not enrolled`)
986
+ const next: VaultMeta = {
987
+ ...meta,
988
+ revision: meta.revision + 1,
989
+ keys: meta.keys.map(x => (x.serial === serial ? { ...x, nickname: clean } : x))
990
+ }
991
+ await writeMeta(token, next)
992
+ return next
993
+ })
994
+ },
995
+
996
+ async noteLastUsed(serial: string, scopeToken?: VaultScopeToken): Promise<void> {
997
+ const token = scopeToken ?? captureScope(false)
998
+ if (!token) return
999
+ return enqueueMutation(async () => {
1000
+ const meta = await readMeta(token)
1001
+ if (!meta || !meta.keys.some(k => k.serial === serial)) return
1002
+ await writeMeta(token, { ...meta, lastUsedAt: Date.now(), lastUsedSerial: serial })
1003
+ })
1004
+ },
1005
+
1006
+ /** Forget only the active wallet+chain enrollment. */
1007
+ async clear(scopeToken?: VaultScopeToken): Promise<void> {
1008
+ const token = scopeToken ?? captureScope(true)
1009
+ return enqueueMutation(async () => {
1010
+ // Distinguish absent from corrupt: corruption needs recovery, not a setup
1011
+ // or disable path that silently destroys the last local copy.
1012
+ const meta = await readMeta(token)
1013
+ if (meta?.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal first')
1014
+ assertScope(token)
1015
+ await SecureStore.deleteItemAsync(token.storageKey, SECURE_OPTIONS)
1016
+ assertScope(token)
1017
+ await writeCapturedEnrollmentDraft(token, null)
1018
+ assertScope(token)
1019
+ })
103
1020
  }
104
1021
  }