@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
@@ -7,13 +7,17 @@
7
7
  * tap — so a dropped session can never leave the enrollment quarantine
8
8
  * machinery in a state it was not designed for.
9
9
  *
10
- * SAFETY. A PIV reset destroys the P-256 key in Vault slot 0x82. If the token
11
- * is already an enrolled vault key, that removes one of the k-of-n signers and
12
- * can make vault funds permanently unspendable. The enrolled-serial refusal
13
- * below runs before the card is touched AND again inside the session, and is
14
- * deliberately not overridable by any caller flag — unlike
15
- * `replaceOccupiedVaultSlot`, which consents to replacing a slot that is by
16
- * definition not yet part of the vault.
10
+ * SAFETY. A PIV reset destroys the P-256 key in Vault slot 0x82. The vault
11
+ * script accepts a signature from ANY ONE of its enrolled keys (1-of-N, not a
12
+ * threshold scheme), so resetting one enrolled key does not by itself lock
13
+ * funds committed to multiple keys — but it permanently removes that key's
14
+ * own ability to satisfy the script, and if the vault currently has only one
15
+ * enrolled key (or an output was locked before other keys were added), that
16
+ * reset destroys the only remaining way to spend those outputs. The
17
+ * enrolled-serial refusal below runs before the card is touched AND again
18
+ * inside the session, and is deliberately not overridable by any caller flag
19
+ * — unlike `replaceOccupiedVaultSlot`, which consents to replacing a slot
20
+ * that is by definition not yet part of the vault.
17
21
  *
18
22
  * "Enrolled" is read wider than `getMeta` reads it, on purpose:
19
23
  *
@@ -26,15 +30,24 @@
26
30
  * testnet enrollment wizard sees as unknown, so the refusal set comes from
27
31
  * `vaultStore.enrolledSerialsAcrossChains`, not `getMeta`.
28
32
  *
29
- * What that still cannot see is a vault belonging to a DIFFERENT wallet
30
- * identity on this device: SecureStore cannot be enumerated, so proving that
31
- * negative needs a device-wide serial index this module does not have. Against
32
- * that residual there is one last, purely local signal — a key sitting in slot
33
- * 0x82 means this card is a vault key for SOME vault — so an occupied slot is
34
- * refused unless the caller passes `acknowledgeUnrecognizedVaultKey`. That one
35
- * IS overridable, because a card left over from a vault the user has already
36
- * abandoned is the whole reason this service exists; the enrolled-serial
37
- * refusal above is not.
33
+ * XQ-014 UPDATE. `vaultStore.enrolledSerialsAcrossChains` still only ever
34
+ * sees ONE wallet identity: a vault belonging to a DIFFERENT identity on this
35
+ * device was genuinely invisible to it, because SecureStore cannot be
36
+ * enumerated across identities. `enrolledSerialRegistry.ts` closes most of
37
+ * that gap: a plain, device-wide, non-secret set of bare serials that EVERY
38
+ * identity's vaultStore writes to when it commits or fully removes an
39
+ * enrolled key, checked below alongside the identity-scoped set and refused
40
+ * exactly as unconditionally. What is left, and cannot be fully resolved
41
+ * without the same cross-identity enumeration SecureStore disallows, is one
42
+ * physical key committed under two different identities' vaults on this
43
+ * device where one identity has since fully removed its own copy — see
44
+ * enrolledSerialRegistry.ts's header. Against THAT narrower residual there is
45
+ * still the one last, purely local signal — a key sitting in slot 0x82 means
46
+ * this card is a vault key for SOME vault — so an occupied slot is refused
47
+ * unless the caller passes `acknowledgeUnrecognizedVaultKey`. That one IS
48
+ * overridable, because a card left over from a vault the user has already
49
+ * abandoned is the whole reason this service exists; neither enrolled-serial
50
+ * refusal above is.
38
51
  *
39
52
  * That occupancy question goes to `isVaultSlotOccupied`, which both platforms
40
53
  * answer from the card (iOS attests the slot; Android reads its metadata) and
@@ -44,10 +57,24 @@
44
57
  * reports null for every 0x82 and this refusal would never fire there.
45
58
  */
46
59
  import { getVaultDriver } from './driver'
47
- import { withKeySession } from './session'
60
+ import { enrolledSerialRegistry } from './enrolledSerialRegistry'
61
+ import { withKeySession, VaultSessionGuard } from './session'
48
62
  import { VaultError } from './types'
49
63
  import { isVaultSerial, vaultStore, type VaultScopeToken } from './vaultStore'
50
64
 
65
+ /**
66
+ * XR-004: mirrors VaultKeyService.ts's assertSessionCurrent — the same
67
+ * wallet/chain scope check this reset already runs before every mutation,
68
+ * plus session.assertCurrent so a timed-out/detached session's continuation
69
+ * (the native reset/discard calls it wraps cannot be cancelled) refuses its
70
+ * next write once a NEWER Vault hardware session has been acquired, instead
71
+ * of racing a retry's.
72
+ */
73
+ function assertSessionCurrent(session: VaultSessionGuard, scopeToken: VaultScopeToken): void {
74
+ session.assertCurrent()
75
+ vaultStore.assertScopeToken(scopeToken)
76
+ }
77
+
51
78
  export type PivResetPhase = 'waiting' | 'resetting'
52
79
 
53
80
  export async function resetPivApplication(args: {
@@ -87,6 +114,13 @@ export async function resetPivApplication(args: {
87
114
  // The message IS the serial, matching enrollKey's convention.
88
115
  throw new VaultError('key-already-enrolled', args.serial, undefined, { serial: args.serial })
89
116
  }
117
+ // XQ-014: the device-wide registry can see a serial committed under a
118
+ // DIFFERENT wallet identity's vault on this device — never overridable
119
+ // by `acknowledgeUnrecognizedVaultKey`, exactly like the identity-scoped
120
+ // check above (see this module's header).
121
+ if (await enrolledSerialRegistry.has(args.serial)) {
122
+ throw new VaultError('key-already-enrolled', args.serial, undefined, { serial: args.serial })
123
+ }
90
124
  }
91
125
 
92
126
  // Guard 1: before any card contact.
@@ -95,8 +129,8 @@ export async function resetPivApplication(args: {
95
129
 
96
130
  await withKeySession(
97
131
  driver,
98
- async () => {
99
- vaultStore.assertScopeToken(scopeToken)
132
+ async session => {
133
+ assertSessionCurrent(session, scopeToken)
100
134
  const info = await driver.getKeyInfo()
101
135
  if (info.serial !== args.serial) {
102
136
  throw new VaultError('serial-mismatch', 'A different YubiKey was presented', undefined, {
@@ -108,7 +142,7 @@ export async function resetPivApplication(args: {
108
142
  // first check and the tap, and this is the last chance before an
109
143
  // irreversible destruction.
110
144
  await refuse()
111
- vaultStore.assertScopeToken(scopeToken)
145
+ assertSessionCurrent(session, scopeToken)
112
146
 
113
147
  // Guard 3: the card's own answer, for the vaults no namespace on this
114
148
  // device can show us. Reused code, not new copy: 'slot-occupied' is
@@ -128,14 +162,21 @@ export async function resetPivApplication(args: {
128
162
  { serial: args.serial }
129
163
  )
130
164
  }
131
- vaultStore.assertScopeToken(scopeToken)
165
+ assertSessionCurrent(session, scopeToken)
132
166
 
133
167
  args.onPhase?.('resetting')
134
168
  await driver.resetPivApplication(args.serial)
135
169
 
136
170
  // The reset destroyed whatever partial state these described. Leaving
137
- // them would refuse this key forever.
138
- vaultStore.assertScopeToken(scopeToken)
171
+ // them would refuse this key forever — but XR-004 still applies here:
172
+ // if this continuation is only resuming now because the native reset
173
+ // call stalled and a NEWER session has since run (e.g. re-enrolling
174
+ // this same, now-actually-reset serial), these discards must not wipe
175
+ // out whatever fresh draft/quarantine state that session just wrote.
176
+ // Refusing here leaves a stale entry that the next explicit reset
177
+ // attempt clears — a mild extra tap, not a permanent block, since the
178
+ // card is by then already factory and that retry completes at once.
179
+ assertSessionCurrent(session, scopeToken)
139
180
  await vaultStore.discardEnrollmentDraft(args.serial, scopeToken)
140
181
  await vaultStore.discardEnrollmentQuarantine(args.serial, scopeToken)
141
182
  },
@@ -870,7 +870,38 @@ export interface VaultInstructionsV6 {
870
870
  createdAt: number
871
871
  keys: VaultInstructionKey[]
872
872
  }
873
- export type VaultInstructions = VaultInstructionsV6
873
+ /**
874
+ * v7 recovery metadata: exactly the v6 fields minus `salt`. The salt is never
875
+ * persisted for a v7 output — it is re-derived in memory (deriveVaultSalt)
876
+ * whenever a v7 lock must be rebuilt or a v7 witness built, from the same
877
+ * unchanged HMAC protocol v6 always used. See docs/security's v7 design: the
878
+ * exact 8-field shape and the `v===7` gate make it structurally impossible
879
+ * for a salt to ride along with a v7 record, and structurally impossible for
880
+ * a v6 record (which REQUIRES `salt`) to decode as v7 or vice versa.
881
+ */
882
+ export interface VaultInstructionsV7 {
883
+ v: 7
884
+ type: 'R1C'
885
+ /** Canonical positive decimal wallet key index (`"1"`, `"2"`, ...). */
886
+ saltKeyId: string
887
+ /** Network scope of the output. */
888
+ chain: VaultSaltChain
889
+ vaultId: string
890
+ revision: number
891
+ createdAt: number
892
+ keys: VaultInstructionKey[]
893
+ }
894
+ export type VaultInstructions = VaultInstructionsV6 | VaultInstructionsV7
895
+
896
+ /**
897
+ * Hard cap on the v7 descriptor's AES-256-GCM ciphertext
898
+ * (`iv(32B) || ciphertext || authTag(16B)`, @bsv/sdk SymmetricKey.encrypt),
899
+ * enforced at both encode time (creation fails closed) and decode time (an
900
+ * oversized blob is never trusted, not merely truncated). Measured worst case:
901
+ * N=5 keys at max field lengths serializes to roughly 1.45 KB of v7 JSON, so
902
+ * +48 B of AES-GCM overhead leaves a comfortable margin under 2,200.
903
+ */
904
+ export const MAX_DESCRIPTOR_CIPHERTEXT_BYTES = 2200
874
905
 
875
906
  const MAX_CUSTOM_INSTRUCTIONS_CHARS = 4096
876
907
  const exactFields = (v: Record<string, unknown>, fields: readonly string[]): boolean => {
@@ -883,7 +914,7 @@ const positiveSafeInteger = (v: unknown): v is number => Number.isSafeInteger(v)
883
914
  * Parse exact v6 output recovery metadata. Older and extended shapes fail
884
915
  * closed: future code must explicitly version any semantic change.
885
916
  */
886
- export function decodeVaultInstructions(ci?: string): VaultInstructionsV6 | null {
917
+ export function decodeVaultInstructionsV6(ci?: string): VaultInstructionsV6 | null {
887
918
  if (typeof ci !== 'string' || ci.length === 0 || ci.length > MAX_CUSTOM_INSTRUCTIONS_CHARS) return null
888
919
  let parsed: unknown
889
920
  try {
@@ -971,6 +1002,111 @@ export function encodeVaultInstructions(i: VaultInstructionsV6): string {
971
1002
  enrolledAt: k.enrolledAt
972
1003
  }))
973
1004
  })
974
- if (decodeVaultInstructions(s) === null) throw invalid('encodeVaultInstructions: record would not decode as canonical v6 vault metadata')
1005
+ if (decodeVaultInstructionsV6(s) === null) throw invalid('encodeVaultInstructions: record would not decode as canonical v6 vault metadata')
1006
+ return s
1007
+ }
1008
+
1009
+ /**
1010
+ * Parse exact v7 output recovery metadata: the v6 shape minus `salt`. A
1011
+ * record carrying a `salt` field (extra field), a `p.v` other than 7, or any
1012
+ * other v6-shaped field set fails closed here — see VaultInstructionsV7's
1013
+ * docstring. Every other field rule is identical to the v6 decoder.
1014
+ */
1015
+ export function decodeVaultInstructionsV7(ci?: string): VaultInstructionsV7 | null {
1016
+ if (typeof ci !== 'string' || ci.length === 0 || ci.length > MAX_CUSTOM_INSTRUCTIONS_CHARS) return null
1017
+ let parsed: unknown
1018
+ try {
1019
+ parsed = JSON.parse(ci)
1020
+ } catch {
1021
+ return null
1022
+ }
1023
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
1024
+ const p = parsed as Record<string, unknown>
1025
+ if (!exactFields(p, ['v', 'type', 'saltKeyId', 'chain', 'vaultId', 'revision', 'createdAt', 'keys'])) return null
1026
+ if (p.v !== 7 || p.type !== 'R1C') return null
1027
+ if (typeof p.vaultId !== 'string' || !/^[0-9a-f]{64}$/.test(p.vaultId)) return null
1028
+ if (
1029
+ typeof p.saltKeyId !== 'string' ||
1030
+ !/^[1-9][0-9]{0,15}$/.test(p.saltKeyId)
1031
+ ) return null
1032
+ if (p.chain !== 'main' && p.chain !== 'test' && p.chain !== 'teratest') return null
1033
+ const saltIndex = Number(p.saltKeyId)
1034
+ if (!positiveSafeInteger(saltIndex)) return null
1035
+ if (!positiveSafeInteger(p.revision) || !positiveSafeInteger(p.createdAt)) return null
1036
+ if (!Array.isArray(p.keys) || p.keys.length < 1 || p.keys.length > R1C_MAX_KEYS) return null
1037
+ const keys: VaultInstructionKey[] = []
1038
+ for (const raw of p.keys) {
1039
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
1040
+ const k = raw as Record<string, unknown>
1041
+ if (!exactFields(k, ['serial', 'slot', 'pubkey', 'nickname', 'enrolledAt'])) return null
1042
+ if (typeof k.serial !== 'string' || !/^[A-Za-z0-9._:-]{1,64}$/.test(k.serial)) return null
1043
+ if (k.slot !== 0x82) return null
1044
+ if (typeof k.pubkey !== 'string' || !/^0[23][0-9a-f]{64}$/.test(k.pubkey)) return null
1045
+ if (
1046
+ typeof k.nickname !== 'string' || k.nickname.length < 1 || k.nickname.length > 64 ||
1047
+ k.nickname !== k.nickname.trim() || /[\u0000-\u001f\u007f]/.test(k.nickname)
1048
+ ) return null
1049
+ if (!positiveSafeInteger(k.enrolledAt)) return null
1050
+ try {
1051
+ if (compressPubkey(k.pubkey) !== k.pubkey) return null
1052
+ } catch {
1053
+ return null
1054
+ }
1055
+ keys.push({
1056
+ serial: k.serial,
1057
+ slot: k.slot,
1058
+ pubkey: k.pubkey,
1059
+ nickname: k.nickname,
1060
+ enrolledAt: k.enrolledAt
1061
+ })
1062
+ }
1063
+ if (new Set(keys.map(k => k.serial)).size !== keys.length) return null
1064
+ if (new Set(keys.map(k => k.pubkey)).size !== keys.length) return null
1065
+ try {
1066
+ vaultSaltHmacData(keys.map(k => k.serial))
1067
+ } catch {
1068
+ return null
1069
+ }
1070
+ return {
1071
+ v: 7,
1072
+ type: 'R1C',
1073
+ saltKeyId: p.saltKeyId,
1074
+ chain: p.chain,
1075
+ vaultId: p.vaultId,
1076
+ revision: p.revision,
1077
+ createdAt: p.createdAt,
1078
+ keys
1079
+ }
1080
+ }
1081
+
1082
+ /** Serialise only the canonical v7 fields (no `salt`), after applying the decoder's validation. */
1083
+ export function encodeVaultInstructionsV7(i: VaultInstructionsV7): string {
1084
+ const s = JSON.stringify({
1085
+ v: 7,
1086
+ type: 'R1C',
1087
+ saltKeyId: i.saltKeyId,
1088
+ chain: i.chain,
1089
+ vaultId: i.vaultId,
1090
+ revision: i.revision,
1091
+ createdAt: i.createdAt,
1092
+ keys: i.keys.map(k => ({
1093
+ serial: k.serial,
1094
+ slot: k.slot,
1095
+ pubkey: k.pubkey,
1096
+ nickname: k.nickname,
1097
+ enrolledAt: k.enrolledAt
1098
+ }))
1099
+ })
1100
+ if (decodeVaultInstructionsV7(s) === null) throw invalid('encodeVaultInstructionsV7: record would not decode as canonical v7 vault metadata')
975
1101
  return s
976
1102
  }
1103
+
1104
+ /**
1105
+ * Union decoder: try the exact v6 shape (carries `salt`), then the exact v7
1106
+ * shape (no `salt`). The two decoders' exact-field checks and `v` gate make
1107
+ * the two shapes mutually exclusive, so this can never reinterpret one
1108
+ * version as the other.
1109
+ */
1110
+ export function decodeVaultInstructions(ci?: string): VaultInstructions | null {
1111
+ return decodeVaultInstructionsV6(ci) ?? decodeVaultInstructionsV7(ci)
1112
+ }
@@ -21,9 +21,22 @@
21
21
  * swallows several failure paths, so no delegate fix makes this redundant).
22
22
  */
23
23
  import { VaultDriver } from './driver'
24
- import { acquireVaultHardwareLease } from './hardwareLease'
24
+ import { acquireVaultHardwareLease, currentVaultHardwareGeneration, isCurrentVaultHardwareGeneration } from './hardwareLease'
25
25
  import { VaultError } from './types'
26
26
 
27
+ /**
28
+ * XR-004: `work()` is unbounded native work this function cannot cancel — a
29
+ * lost completion can still be running (and can still resolve much later)
30
+ * after the timeout/detach race below has already settled and released the
31
+ * lease for a retry. `work` receives this guard so it can refuse its own
32
+ * next mutation once a NEWER session has been acquired since, rather than
33
+ * racing that retry's writes to vaultStore/the card. Cheap and synchronous:
34
+ * safe to call as often as the existing per-step scope checks already do.
35
+ */
36
+ export interface VaultSessionGuard {
37
+ assertCurrent(): void
38
+ }
39
+
27
40
  interface Deferred<T> {
28
41
  promise: Promise<T>
29
42
  resolve: (v: T) => void
@@ -59,13 +72,21 @@ const DEFAULT_WORK_TIMEOUT_MS = 180_000
59
72
 
60
73
  export async function withKeySession<T>(
61
74
  driver: VaultDriver,
62
- work: () => Promise<T>,
75
+ work: (session: VaultSessionGuard) => Promise<T>,
63
76
  onWaiting?: () => void,
64
77
  opts?: { nfcMessage?: string; attachTimeoutMs?: number; workTimeoutMs?: number }
65
78
  ): Promise<T> {
66
79
  const releaseLease = acquireVaultHardwareLease()
80
+ const generation = currentVaultHardwareGeneration()
81
+ const session: VaultSessionGuard = {
82
+ assertCurrent(): void {
83
+ if (!isCurrentVaultHardwareGeneration(generation)) {
84
+ throw new VaultError('scope-changed', 'A newer Vault hardware session has started; this one was abandoned')
85
+ }
86
+ }
87
+ }
67
88
  try {
68
- if (!driver.sessionBased) return await work()
89
+ if (!driver.sessionBased) return await work(session)
69
90
 
70
91
  const connected = defer<void>()
71
92
  // Rejects when the key leaves before `work` has resolved; raced against it.
@@ -105,7 +126,7 @@ export async function withKeySession<T>(
105
126
  )
106
127
  ;(workWatchdog as { unref?: () => void }).unref?.()
107
128
  try {
108
- return await Promise.race([work(), detached.promise, stalled.promise])
129
+ return await Promise.race([work(session), detached.promise, stalled.promise])
109
130
  } finally {
110
131
  clearTimeout(workWatchdog)
111
132
  }