@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -22,9 +22,17 @@
22
22
  * SECURITY: never log the PIN. Public keys and serials are public data.
23
23
  */
24
24
  import { getVaultDriver } from './driver'
25
- import { compressPubkey, type VaultInstructionsV6 } from './r1comb'
25
+ import { enrolledSerialRegistry, forgetSerialsNoLongerEnrolledForIdentity } from './enrolledSerialRegistry'
26
+ import {
27
+ computeVaultDraftAuthorityTag,
28
+ computeVaultMetaAuthorityTag,
29
+ verifyVaultDraftAuthorityTag,
30
+ verifyVaultMetaAuthorityTag,
31
+ type HmacCapableWallet
32
+ } from './metaAuthority'
33
+ import { compressPubkey, type VaultInstructions } from './r1comb'
26
34
  import { randomBytes } from './random'
27
- import { withKeySession } from './session'
35
+ import { withKeySession, VaultSessionGuard } from './session'
28
36
  import { VaultError } from './types'
29
37
  import {
30
38
  isVaultKeyRecord,
@@ -39,12 +47,66 @@ import {
39
47
  import { Utils } from '@bsv/sdk'
40
48
  import { p256 } from '@noble/curves/nist.js'
41
49
 
50
+ /**
51
+ * XR-001 / XR-002: the admin-scoped wallet capability every meta/draft-tag
52
+ * write and verification in this module needs. Callers pass the SAME
53
+ * admin-scoped wallet + `adminOriginator` transfers.ts already uses (see
54
+ * guardVaultAccess) — never a site-scoped WalletClient, which forwards
55
+ * createHmac/verifyHmac for any non-reserved namespace to the underlying
56
+ * wallet (see guard.ts's VAULT_PROTOCOL_NAMES / metaAuthority.ts's header).
57
+ */
58
+ export interface VaultWalletAuthority {
59
+ wallet: HmacCapableWallet
60
+ adminOriginator: string
61
+ }
62
+
63
+ /** Re-verify `existing`'s own wallet-root tag before trusting it as the
64
+ * basis for a freshly, validly tagged `next` (addKey only APPENDS to
65
+ * `meta.keys`, so a forged `existing` would otherwise "launder" straight
66
+ * through the moment the legitimate user adds one more, genuinely their
67
+ * own, key — see vaultStore.addKey's laundering caveat).
68
+ *
69
+ * Unlike transfers.ts's requireAuthenticatedMeta, this has no on-chain
70
+ * fallback: VaultKeyService has no chain-scanning capability, and inventing
71
+ * one here only to duplicate transfers.ts's would need this module to import
72
+ * from it, which already imports FROM this module (metaFromVerifiedOutputs).
73
+ * A genuinely untagged-but-legitimate meta (every enrollment created before
74
+ * this fix shipped) is recovered instead through the existing VaultScreen
75
+ * reload() → recoverVaultMetaFromOutputs → restoreVerifiedMeta path, which
76
+ * DOES have chain access and tags the result going forward — the "safer
77
+ * route" this refusal directs the user to rather than ever trusting
78
+ * `existing` on sight. */
79
+ async function requireTaggedMeta(
80
+ authority: VaultWalletAuthority,
81
+ meta: VaultMeta,
82
+ scopeToken: VaultScopeToken
83
+ ): Promise<void> {
84
+ vaultStore.assertScopeToken(scopeToken)
85
+ const scope = vaultStore.getScope()
86
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
87
+ const tag = await vaultStore.getMetaTag(scopeToken)
88
+ const ok = await verifyVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, meta, scope, tag)
89
+ if (!ok) {
90
+ throw new VaultError(
91
+ 'template-invalid',
92
+ 'Vault enrollment metadata could not be authenticated; open the vault screen to re-verify it before adding a key'
93
+ )
94
+ }
95
+ }
96
+
42
97
  export const VAULT_SLOT = 0x82
43
98
 
44
99
  /** Spec D3: at least two keys, so one lost YubiKey does not lose the money;
45
100
  * at most five (R1C_MAX_KEYS — the lock carries one commitment per key). */
46
101
  export const VAULT_MIN_KEYS = 2
47
102
  export const VAULT_MAX_KEYS = 5
103
+ /** The key list may hold ONE key beyond the lock's ceiling, never committed:
104
+ * a replacement is added before the key it replaces is removed, so a full
105
+ * vault passes through six on its way back to five, and a single re-lock
106
+ * covers both changes. Nothing locks to more than VAULT_MAX_KEYS (see
107
+ * newVaultOutput and relockVault). Mirrored in vaultStore.ts, which cannot
108
+ * import this module. */
109
+ export const VAULT_MAX_ACTIVE_KEYS = VAULT_MAX_KEYS + 1
48
110
 
49
111
  const DEFAULT_PIV_PIN = '123456'
50
112
  const DEFAULT_PIV_PUK = '12345678'
@@ -124,6 +186,20 @@ function requirePivCode(value: string, label: 'PIN' | 'PUK'): void {
124
186
  }
125
187
  }
126
188
 
189
+ /**
190
+ * XR-004: the same checkpoint enrollKey's session already runs before every
191
+ * mutation (assertScopeToken — wallet/chain unchanged), plus session.assertCurrent
192
+ * — no NEWER Vault hardware session has been acquired since this one started.
193
+ * A timed-out/detached session's continuation can still be running (the native
194
+ * calls it wraps cannot be cancelled) after the lease has already been freed
195
+ * for a retry; this refuses that continuation's next write instead of letting
196
+ * it race the retry's.
197
+ */
198
+ function assertSessionCurrent(session: VaultSessionGuard, scopeToken: VaultScopeToken): void {
199
+ session.assertCurrent()
200
+ vaultStore.assertScopeToken(scopeToken)
201
+ }
202
+
127
203
  /**
128
204
  * Attach the tapped serial to an error leaving the card session.
129
205
  *
@@ -309,6 +385,11 @@ export async function enrollKey(args: {
309
385
  /** Explicit consent to destroy and replace an existing key in Vault's fixed
310
386
  * slot 0x82. Other occupied PIV slots remain a hard failure. */
311
387
  replaceOccupiedVaultSlot?: boolean
388
+ /** XR-001: the admin-scoped wallet capability used to tag this run's
389
+ * `ready` draft the instant it is written, so a later SecureStore-only
390
+ * attacker cannot forge an equivalent one. */
391
+ wallet: HmacCapableWallet
392
+ adminOriginator: string
312
393
  }): Promise<VaultKeyRecord> {
313
394
  const driver = getVaultDriver()
314
395
  if (!driver) throw new VaultError('driver-unavailable')
@@ -321,12 +402,20 @@ export async function enrollKey(args: {
321
402
  }
322
403
 
323
404
  // The enrolled key list, read once from device-only secure storage before any user input or
324
- // key contact. Refused alongside pendingSerials below — meta ∪ pending —
325
- // so an enrolled card is refused even when the caller's own copy of meta
326
- // has not loaded (the wizard's key list arrives asynchronously).
327
- const meta = await vaultStore.getMeta(scopeToken)
405
+ // key contact. Refused alongside pendingSerials below — across every chain
406
+ // of this identity, plus a key mid-removal, plus pending — so an enrolled
407
+ // card is refused even when the caller's own copy of meta has not loaded
408
+ // (the wizard's key list arrives asynchronously), and even when it is
409
+ // enrolled under a different chain of the same wallet identity, or sits in
410
+ // meta.pendingRemoval in this chain (XR-008: `enrolledSerialsAcrossChains`
411
+ // already covers both — it folds pendingRemoval into every chain it scans —
412
+ // and is the exact non-overridable refusal set pivReset.ts already uses
413
+ // before its own destructive card mutation).
328
414
  const quarantines = await vaultStore.getEnrollmentQuarantines(scopeToken)
329
- const refused = new Set<string>([...(meta?.keys.map(k => k.serial) ?? []), ...args.pendingSerials])
415
+ const refused = new Set<string>([
416
+ ...(await vaultStore.enrolledSerialsAcrossChains(scopeToken)),
417
+ ...args.pendingSerials
418
+ ])
330
419
  const k = args.pendingSerials.length + 1
331
420
  const nickname = enrollmentNickname(args.nickname, k)
332
421
  const enrolledAt = Date.now()
@@ -366,8 +455,8 @@ export async function enrollKey(args: {
366
455
  let tappedSerial: string | undefined
367
456
  const record = await withKeySession(
368
457
  driver,
369
- async () => {
370
- vaultStore.assertScopeToken(scopeToken)
458
+ async session => {
459
+ assertSessionCurrent(session, scopeToken)
371
460
  const info = await driver.getKeyInfo()
372
461
  if (!isVaultSerial(info.serial)) {
373
462
  throw new VaultError('template-invalid', 'YubiKey returned an invalid serial number')
@@ -439,14 +528,14 @@ export async function enrollKey(args: {
439
528
  await requireEmptyVaultSlot(info.serial, args.replaceOccupiedVaultSlot === true)
440
529
  // Everything above is read-only. This is the last guard before the
441
530
  // first irreversible token mutation.
442
- vaultStore.assertScopeToken(scopeToken)
531
+ assertSessionCurrent(session, scopeToken)
443
532
  args.onPhase('personalizing')
444
533
  if (pinChange) {
445
534
  // Write intent before the irreversible APDU. If the process dies while
446
535
  // changePin is executing, the next launch must quarantine this serial
447
536
  // instead of guessing which PIN is current and spending retries.
448
537
  await vaultStore.preserveEnrollmentQuarantine(info.serial, 'pin-change-uncertain', scopeToken)
449
- vaultStore.assertScopeToken(scopeToken)
538
+ assertSessionCurrent(session, scopeToken)
450
539
  try {
451
540
  await driver.changePin(info.serial, pinChange.oldPin, pinChange.newPin)
452
541
  } catch (e) {
@@ -476,7 +565,7 @@ export async function enrollKey(args: {
476
565
  try {
477
566
  const changed = await driver.verifyPin(info.serial, pin)
478
567
  requireVerifiedPin(changed, 'New PIN was not accepted')
479
- vaultStore.assertScopeToken(scopeToken)
568
+ assertSessionCurrent(session, scopeToken)
480
569
  } catch (e) {
481
570
  throw new VaultEnrollmentPartialError('pin-changed', e, undefined, true)
482
571
  }
@@ -496,7 +585,7 @@ export async function enrollKey(args: {
496
585
  if (pinChange) throw new VaultEnrollmentPartialError('pin-changed', e, undefined, true)
497
586
  throw e
498
587
  }
499
- vaultStore.assertScopeToken(scopeToken)
588
+ assertSessionCurrent(session, scopeToken)
500
589
  try {
501
590
  await driver.changePuk(info.serial, pukChange.oldPuk, pukChange.newPuk)
502
591
  } catch (e) {
@@ -533,7 +622,7 @@ export async function enrollKey(args: {
533
622
  throw new VaultEnrollmentPartialError('puk-changed', e, undefined, true)
534
623
  }
535
624
  try {
536
- vaultStore.assertScopeToken(scopeToken)
625
+ assertSessionCurrent(session, scopeToken)
537
626
  } catch (e) {
538
627
  // PIN/PUK personalization is confirmed, but no slot key exists yet.
539
628
  throw new VaultEnrollmentPartialError('puk-changed', e, undefined, true)
@@ -547,7 +636,7 @@ export async function enrollKey(args: {
547
636
  } catch (e) {
548
637
  throw new VaultEnrollmentPartialError('puk-changed', e, undefined, true)
549
638
  }
550
- vaultStore.assertScopeToken(scopeToken)
639
+ assertSessionCurrent(session, scopeToken)
551
640
  // Generation is authorized by the still-default management key. The key
552
641
  // is not returned as enrolled until that credential has been replaced by
553
642
  // native CSPRNG material that never crosses the JS bridge.
@@ -593,7 +682,7 @@ export async function enrollKey(args: {
593
682
  throw new VaultEnrollmentPartialError('key-generated', e, generated)
594
683
  }
595
684
  try {
596
- vaultStore.assertScopeToken(scopeToken)
685
+ assertSessionCurrent(session, scopeToken)
597
686
  } catch (e) {
598
687
  throw new VaultEnrollmentPartialError('key-generated', e, generated, true)
599
688
  }
@@ -617,13 +706,17 @@ export async function enrollKey(args: {
617
706
  args.onPhase('challenging')
618
707
  const challenge = Uint8Array.from(randomBytes(32))
619
708
  try {
620
- vaultStore.assertScopeToken(scopeToken)
709
+ assertSessionCurrent(session, scopeToken)
621
710
  const { signature } = await driver.signEcdsa(info.serial, pin, Utils.toHex(challenge))
622
711
  if (!signatureProvesKey(pubkey, challenge, signature)) {
623
712
  throw new VaultError('wrong-key', 'Generated YubiKey did not prove possession of its private key')
624
713
  }
625
- await vaultStore.preserveEnrollmentDraft({ record: generated, assurance: 'ready' }, scopeToken)
626
- vaultStore.assertScopeToken(scopeToken)
714
+ const scope = vaultStore.getScope()
715
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
716
+ await vaultStore.preserveEnrollmentDraft({ record: generated, assurance: 'ready' }, scopeToken, record =>
717
+ computeVaultDraftAuthorityTag(args.wallet, args.adminOriginator, record, scope)
718
+ )
719
+ assertSessionCurrent(session, scopeToken)
627
720
  } catch (e) {
628
721
  throw new VaultEnrollmentPartialError('key-protected', e, generated, true)
629
722
  }
@@ -661,6 +754,10 @@ export async function resumeEnrollmentDraft(args: {
661
754
  getPin: () => Promise<string>
662
755
  nfcMessage?: string
663
756
  scopeToken?: VaultScopeToken
757
+ /** XR-001: used both to verify a `ready` draft's existing tag before
758
+ * trusting its fast path, and to tag it again after a fresh challenge. */
759
+ wallet: HmacCapableWallet
760
+ adminOriginator: string
664
761
  }): Promise<VaultKeyRecord> {
665
762
  if (!isVaultKeyRecord(args.entry.record)) {
666
763
  throw new VaultError('template-invalid', 'Invalid enrollment recovery handle')
@@ -687,8 +784,20 @@ export async function resumeEnrollmentDraft(args: {
687
784
  }
688
785
  if (stored.assurance === 'ready') {
689
786
  vaultStore.assertScopeToken(scopeToken)
690
- args.onPhase('done')
691
- return { ...stored.record }
787
+ const scope = vaultStore.getScope()
788
+ const tag = scope ? await vaultStore.getEnrollmentDraftTag(stored.record.serial, scopeToken) : null
789
+ const authentic =
790
+ scope !== null && (await verifyVaultDraftAuthorityTag(args.wallet, args.adminOriginator, stored.record, scope, tag))
791
+ if (authentic) {
792
+ args.onPhase('done')
793
+ return { ...stored.record }
794
+ }
795
+ // XR-001: an unverifiable 'ready' draft — never tagged (every draft
796
+ // written before this fix shipped) or a forged SecureStore-only write —
797
+ // is never trusted on sight. Fall through to the same live driver
798
+ // challenge the 'challenge-required' case below already requires: a
799
+ // legitimate card can simply re-tap and prove itself again; an attacker
800
+ // without the physical key cannot.
692
801
  }
693
802
 
694
803
  args.onPhase('pin-check')
@@ -730,7 +839,11 @@ export async function resumeEnrollmentDraft(args: {
730
839
  () => args.onPhase('connecting'),
731
840
  { nfcMessage: args.nfcMessage }
732
841
  )
733
- await vaultStore.preserveEnrollmentDraft({ record: stored.record, assurance: 'ready' }, scopeToken)
842
+ const scope = vaultStore.getScope()
843
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
844
+ await vaultStore.preserveEnrollmentDraft({ record: stored.record, assurance: 'ready' }, scopeToken, record =>
845
+ computeVaultDraftAuthorityTag(args.wallet, args.adminOriginator, record, scope)
846
+ )
734
847
  vaultStore.assertScopeToken(scopeToken)
735
848
  } catch (e) {
736
849
  if (e instanceof VaultError && e.code === 'scope-changed') {
@@ -807,8 +920,10 @@ export async function adoptVaultKey(args: {
807
920
  }
808
921
 
809
922
  export interface VerifiedVaultRecoveryOutput {
810
- /** Decoded only after baked-salt and exact-lock verification by transfers. */
811
- instructions: VaultInstructionsV6
923
+ /** Decoded only after baked-salt and exact-lock verification by transfers.
924
+ * v6 or v7 — this function only reads fields common to both shapes
925
+ * (vaultId, revision, createdAt, keys), never `salt`. */
926
+ instructions: VaultInstructions
812
927
  /** Transaction containing this currently spendable output. */
813
928
  txid: string
814
929
  }
@@ -817,7 +932,10 @@ export interface VerifiedVaultRecoveryOutput {
817
932
  * Reconstruct one current enrollment from authoritative spendable R1C outputs.
818
933
  * The transfer layer owns pagination and lock verification; this function owns
819
934
  * conflict detection and version selection. It never accepts a mixture of
820
- * enrollment ids or two different key sets at the same revision.
935
+ * enrollment ids or two different key sets at the same revision. A mixed
936
+ * v6+v7 output set reduces to one VaultMeta the same way a same-version
937
+ * mixture does — version is not part of the conflict/version-selection
938
+ * identity here, only vaultId/createdAt/revision/keys are.
821
939
  */
822
940
  export function metaFromVerifiedOutputs(outputs: readonly VerifiedVaultRecoveryOutput[]): VaultMeta {
823
941
  if (outputs.length === 0) throw new VaultError('vault-empty', 'No verified vault outputs to recover')
@@ -864,13 +982,30 @@ export function metaFromVerifiedOutputs(outputs: readonly VerifiedVaultRecoveryO
864
982
  return meta
865
983
  }
866
984
 
985
+ /**
986
+ * XR-001: a persisted 'ready' entry is data an attacker who can only write
987
+ * SecureStore could fabricate outright — matching serial/slot/pubkey/
988
+ * enrolledAt is a SHAPE check, never proof anyone tapped a real card. Every
989
+ * record this function accepts must ALSO carry a wallet-root authority tag
990
+ * (metaAuthority.ts) that verifies against the SAME record: a tag computed
991
+ * by legitimate code (enrollKey / resumeEnrollmentDraft, immediately after a
992
+ * live driver.signEcdsa challenge) the moment it wrote 'ready', which a
993
+ * storage-only attacker cannot reproduce without the real wallet's
994
+ * admin-scoped createHmac. Reuses the existing 'key-not-adopted' refusal —
995
+ * from the caller's perspective an unauthenticated 'ready' draft is exactly
996
+ * as insufficient as a missing one.
997
+ */
867
998
  async function requireReadyEnrollmentDrafts(
868
999
  records: readonly VaultKeyRecord[],
869
- scopeToken: VaultScopeToken
1000
+ scopeToken: VaultScopeToken,
1001
+ authority: VaultWalletAuthority
870
1002
  ): Promise<void> {
1003
+ vaultStore.assertScopeToken(scopeToken)
1004
+ const scope = vaultStore.getScope()
1005
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
871
1006
  const drafts = await vaultStore.getEnrollmentDrafts(scopeToken)
872
1007
  for (const record of records) {
873
- const ready = drafts.some(
1008
+ const readyDraft = drafts.find(
874
1009
  draft =>
875
1010
  draft.assurance === 'ready' &&
876
1011
  draft.record.serial === record.serial &&
@@ -878,7 +1013,11 @@ async function requireReadyEnrollmentDrafts(
878
1013
  draft.record.pubkey === record.pubkey &&
879
1014
  draft.record.enrolledAt === record.enrolledAt
880
1015
  )
881
- if (!ready) {
1016
+ const tag = readyDraft ? await vaultStore.getEnrollmentDraftTag(record.serial, scopeToken) : null
1017
+ const authentic =
1018
+ readyDraft !== undefined &&
1019
+ (await verifyVaultDraftAuthorityTag(authority.wallet, authority.adminOriginator, record, scope, tag))
1020
+ if (!authentic) {
882
1021
  throw new VaultError(
883
1022
  'key-not-adopted',
884
1023
  `Key ${record.serial} has not completed its protected live enrollment challenge`
@@ -898,7 +1037,11 @@ async function requireReadyEnrollmentDrafts(
898
1037
  * existing code, whose copy the wizard already renders with the serial it
899
1038
  * carries — rather than minting a new VaultErrorCode that would need its own
900
1039
  * copy in every locale. */
901
- export async function finalizeEnrollment(records: VaultKeyRecord[], scopeToken?: VaultScopeToken): Promise<void> {
1040
+ export async function finalizeEnrollment(
1041
+ records: VaultKeyRecord[],
1042
+ scopeToken: VaultScopeToken | undefined,
1043
+ authority: VaultWalletAuthority
1044
+ ): Promise<void> {
902
1045
  if (records.length < VAULT_MIN_KEYS) {
903
1046
  throw new VaultError('not-enough-keys', `A vault needs at least ${VAULT_MIN_KEYS} keys; ${records.length} given`)
904
1047
  }
@@ -922,17 +1065,29 @@ export async function finalizeEnrollment(records: VaultKeyRecord[], scopeToken?:
922
1065
  { serial: existing.keys[0].serial }
923
1066
  )
924
1067
  }
925
- await requireReadyEnrollmentDrafts(records, token)
926
- await vaultStore.createEnrollment(
927
- {
928
- v: 6,
929
- vaultId: Utils.toHex(randomBytes(32)),
930
- revision: 1,
931
- createdAt: Date.now(),
932
- keys: records
933
- },
934
- token
1068
+ // XR-001: every record must carry a live-challenge-backed, wallet-tagged
1069
+ // 'ready' draft — not merely a structurally matching one.
1070
+ await requireReadyEnrollmentDrafts(records, token, authority)
1071
+ vaultStore.assertScopeToken(token)
1072
+ const scope = vaultStore.getScope()
1073
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
1074
+ const meta: VaultMeta = {
1075
+ v: 6,
1076
+ vaultId: Utils.toHex(randomBytes(32)),
1077
+ revision: 1,
1078
+ createdAt: Date.now(),
1079
+ keys: records
1080
+ }
1081
+ // XR-002: a fresh enrollment has no prior `current` meta to launder — see
1082
+ // vaultStore.createEnrollment's own comment — so tagging `meta` here is
1083
+ // always safe.
1084
+ await vaultStore.createEnrollment(meta, token, next =>
1085
+ computeVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, next, scope)
935
1086
  )
1087
+ // XQ-014: record every committed serial in the device-wide registry
1088
+ // (enrolledSerialRegistry.ts) — best-effort, never fails the enrollment
1089
+ // that already committed.
1090
+ await Promise.all(serials.map(serial => enrolledSerialRegistry.record(serial)))
936
1091
  // Drafts are public recovery handles, not authority. A cleanup failure must
937
1092
  // not report enrollment failure after the authoritative write committed.
938
1093
  try {
@@ -943,20 +1098,35 @@ export async function finalizeEnrollment(records: VaultKeyRecord[], scopeToken?:
943
1098
  }
944
1099
 
945
1100
  /** Append one key to an enrolled vault (spec §3.4 "Add key"). vaultStore
946
- * enforces the duplicate-serial and five-key rules. */
947
- export async function addVaultKey(record: VaultKeyRecord, scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1101
+ * enforces the duplicate-serial and VAULT_MAX_ACTIVE_KEYS rules. */
1102
+ export async function addVaultKey(
1103
+ record: VaultKeyRecord,
1104
+ scopeToken: VaultScopeToken | undefined,
1105
+ authority: VaultWalletAuthority
1106
+ ): Promise<VaultMeta> {
948
1107
  if (!isVaultKeyRecord(record)) throw new VaultError('template-invalid', 'Invalid vault key record')
949
1108
  const token = scopeToken ?? vaultStore.captureScopeToken()
950
1109
  const existing = await vaultStore.getMeta(token)
951
1110
  if (!existing) throw new VaultError('not-enrolled', 'Vault is not set up')
952
- if (existing.keys.length >= VAULT_MAX_KEYS) {
953
- throw new VaultError('too-many-keys', `The vault already has ${VAULT_MAX_KEYS} keys`)
1111
+ if (existing.keys.length >= VAULT_MAX_ACTIVE_KEYS) {
1112
+ throw new VaultError('too-many-keys', `The vault already has ${VAULT_MAX_ACTIVE_KEYS} keys`)
954
1113
  }
955
1114
  if (existing.keys.some(key => key.serial === record.serial || key.pubkey === record.pubkey)) {
956
1115
  throw new VaultError('key-already-enrolled', record.serial, undefined, { serial: record.serial })
957
1116
  }
958
- await requireReadyEnrollmentDrafts([record], token)
959
- const meta = await vaultStore.addKey(record, token)
1117
+ // XR-002: verify `existing`'s own tag BEFORE trusting it as the basis for
1118
+ // a freshly tagged `next` — see requireTaggedMeta's laundering caveat.
1119
+ await requireTaggedMeta(authority, existing, token)
1120
+ // XR-001: the record being added must itself carry a live-challenge-backed
1121
+ // 'ready' draft.
1122
+ await requireReadyEnrollmentDrafts([record], token, authority)
1123
+ const scope = vaultStore.getScope()
1124
+ if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
1125
+ const meta = await vaultStore.addKey(record, token, next =>
1126
+ computeVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, next, scope)
1127
+ )
1128
+ // XQ-014: record the newly committed serial device-wide.
1129
+ await enrolledSerialRegistry.record(record.serial)
960
1130
  try {
961
1131
  await vaultStore.consumeEnrollmentDrafts([record.serial], token)
962
1132
  } catch (error) {
@@ -969,5 +1139,18 @@ export async function addVaultKey(record: VaultKeyRecord, scopeToken?: VaultScop
969
1139
  * §3.4); the keys themselves stay on the YubiKeys. */
970
1140
  export async function disableVault(scopeToken?: VaultScopeToken): Promise<void> {
971
1141
  const token = scopeToken ?? vaultStore.captureScopeToken()
1142
+ const existing = await vaultStore.getMeta(token)
972
1143
  await vaultStore.clear(token)
1144
+ // XQ-014: a disabled vault's keys are no longer committed under THIS
1145
+ // chain — forget any of them the device-wide registry no longer needs to
1146
+ // remember, i.e. every one not still enrolled under another chain of this
1147
+ // SAME identity (vaultStore.enrolledSerialsAcrossChains). See
1148
+ // enrolledSerialRegistry's header for the cross-identity residual this
1149
+ // does not resolve.
1150
+ if (existing?.keys.length) {
1151
+ await forgetSerialsNoLongerEnrolledForIdentity(
1152
+ existing.keys.map(key => key.serial),
1153
+ () => vaultStore.enrolledSerialsAcrossChains(token)
1154
+ )
1155
+ }
973
1156
  }