@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  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/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -5,9 +5,13 @@
5
5
  * There is no sealed private YubiKey material or seed-derived spending
6
6
  * authority: the enrolled YubiKeys are the spending keys. The wallet root
7
7
  * derives deterministic HMAC salts from the ordered serial list.
8
- * Each output carries its salt in the locking script; customInstructions
9
- * mirror it for indexed discovery and are accepted only after exact script and
10
- * salt-derivation verification.
8
+ * The locking script commits only to HASH160(salt||table) — a set of 20-byte
9
+ * commitments, one per enrolled key. The salt itself never appears in the
10
+ * lock; it is supplied only in the spending witness (buildUnlock, r1comb.ts)
11
+ * and is mirrored into customInstructions purely so the wallet can index and
12
+ * re-derive it locally. customInstructions are accepted only after they are
13
+ * shown to rebuild the exact baked commitment set
14
+ * (verifyInstructionsAgainstLock, transfers.ts).
11
15
  */
12
16
 
13
17
  export type VaultErrorCode =
@@ -75,8 +79,13 @@ export type VaultErrorCode =
75
79
  /** Restored metadata exists, but this serial has not yet passed the fresh
76
80
  * possession challenge on this device. */
77
81
  | 'key-not-adopted'
78
- /** VAULT_MAX_KEYS keys already enrolled. */
82
+ /** VAULT_MAX_ACTIVE_KEYS keys already enrolled (one more than a lock holds). */
79
83
  | 'too-many-keys'
84
+ /** The key list holds more keys than a lock can commit (VAULT_MAX_KEYS): a
85
+ * replacement was added and the key it replaces is not removed yet. Nothing
86
+ * that creates a Vault output (deposit, re-lock, partial-withdrawal
87
+ * remainder) runs until a removal brings the list back to VAULT_MAX_KEYS. */
88
+ | 'too-many-active-keys'
80
89
  /** Removing this key would leave fewer than VAULT_MIN_KEYS. */
81
90
  | 'last-keys'
82
91
  /** Removing this key would orphan an output only it can open — re-lock first.
@@ -100,6 +109,12 @@ export type VaultErrorCode =
100
109
  /** The signable transaction is not consensus-bound version 1 — refused
101
110
  * before any signature. */
102
111
  | 'bad-version'
112
+ /** recoverVaultFromChain's bounded scan hit
113
+ * VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS consecutive marker-derivation
114
+ * or chain-lookup failures (a persistent outage, or a bug) and aborted
115
+ * rather than looping forever. Distinct from 'no-transaction': nothing
116
+ * about a specific transfer failed, the scan itself could not complete. */
117
+ | 'chain-scan-failed'
103
118
 
104
119
  export class VaultError extends Error {
105
120
  code: VaultErrorCode
@@ -13,11 +13,25 @@ import { VaultError } from './types'
13
13
 
14
14
  const META_KEY_PREFIX = 'vault_meta_v6'
15
15
  const ENROLLMENT_DRAFT_KEY_PREFIX = 'vault_enrollment_draft_v1'
16
+ /** XR-002: the wallet-root-authenticated integrity tag for this scope's
17
+ * VaultMeta, kept BESIDE the record rather than inside its JSON — the tag
18
+ * covers a canonical encoding computed by metaAuthority.ts, and mixing it
19
+ * into VaultMeta's own strict, allowlisted schema (isVaultMeta) would be a
20
+ * needless coupling between storage-format and authentication concerns. */
21
+ const META_TAG_KEY_PREFIX = 'vault_meta_authority_tag_v1'
22
+ /** XR-001: one wallet-root-authenticated tag per `ready` enrollment-draft
23
+ * record, keyed by serial. Only `ready` drafts are ever tagged — see
24
+ * metaAuthority.ts's header for why lower assurance levels need none. */
25
+ const DRAFT_TAG_KEY_PREFIX = 'vault_enrollment_draft_tag_v1'
16
26
  const SECURE_OPTIONS: SecureStore.SecureStoreOptions = {
17
27
  keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY
18
28
  }
19
29
  const MIN_KEYS = 2
20
30
  const MAX_KEYS = 5
31
+ /** VaultKeyService.VAULT_MAX_ACTIVE_KEYS: one key beyond the lock's ceiling,
32
+ * held only while a replacement waits for the removal of the key it replaces.
33
+ * Keep in step with VaultKeyService.ts (which imports this module). */
34
+ const MAX_ACTIVE_KEYS = MAX_KEYS + 1
21
35
  const VAULT_SLOT = 0x82
22
36
 
23
37
  export type VaultScopeChain = 'main' | 'test' | 'teratest'
@@ -124,6 +138,17 @@ let activeScope: VaultStoreScope | null = null
124
138
  let scopeGeneration = 0
125
139
  let mutationTail: Promise<void> = Promise.resolve()
126
140
 
141
+ /** INT-08: subscribers notified whenever configureScope/clearScope actually
142
+ * runs, so a reader started before the wallet-build chain reaches
143
+ * configureScope (VaultContext's boot-time hasVaultMeta check, structurally
144
+ * guaranteed to settle to `false` first — see INT-08) can react to the scope
145
+ * becoming available instead of latching a stale answer for the rest of the
146
+ * session. Mirrors ceremony.subscribe's plain listener-set shape. */
147
+ const scopeListeners = new Set<() => void>()
148
+ function notifyScopeChange(): void {
149
+ for (const listener of scopeListeners) listener()
150
+ }
151
+
127
152
  /** Serialize every scoped write so two callers cannot both read revision N and
128
153
  * then last-write competing N+1 states. A rejected mutation never poisons the
129
154
  * queue. Each operation captures its scope before joining and rechecks it when
@@ -165,6 +190,98 @@ function enrollmentDraftKey(token: VaultScopeToken): string {
165
190
  return `${ENROLLMENT_DRAFT_KEY_PREFIX}_${match[1]}_${match[2]}`
166
191
  }
167
192
 
193
+ function metaTagKey(token: VaultScopeToken): string {
194
+ const match = SCOPE_KEY_PATTERN.exec(token.storageKey)
195
+ if (!match) throw new VaultError('template-invalid', 'Invalid captured vault scope')
196
+ return `${META_TAG_KEY_PREFIX}_${match[1]}_${match[2]}`
197
+ }
198
+
199
+ function draftTagStoreKey(token: VaultScopeToken): string {
200
+ const match = SCOPE_KEY_PATTERN.exec(token.storageKey)
201
+ if (!match) throw new VaultError('template-invalid', 'Invalid captured vault scope')
202
+ return `${DRAFT_TAG_KEY_PREFIX}_${match[1]}_${match[2]}`
203
+ }
204
+
205
+ /**
206
+ * XR-002: computes and returns the integrity tag for the meta a write is
207
+ * about to persist, given the EXACT object about to be written (never a
208
+ * separately re-read copy — that would open a TOCTOU window between what was
209
+ * authenticated and what lands in storage). Every caller must derive this
210
+ * from `wallet.createHmac` under the admin-reserved 'vault meta' protocol
211
+ * (metaAuthority.ts / guard.ts's VAULT_PROTOCOL_NAMES); vaultStore itself
212
+ * has no wallet access and trusts the returned string as-is. A tagger that
213
+ * throws aborts the whole write: writeMeta only runs after the tag is in
214
+ * hand, so a wallet-side failure never leaves an updated-but-untagged
215
+ * record on disk.
216
+ *
217
+ * Deliberately OPTIONAL: a write made without one (every plain storage-level
218
+ * test, and any future maintenance path that has no wallet handy) simply
219
+ * leaves the on-file tag exactly as it was — which the next
220
+ * output-creating operation's verification (transfers.ts's
221
+ * requireAuthenticatedMeta) will then correctly treat as stale/absent and
222
+ * refuse to trust, never as though nothing had happened.
223
+ */
224
+ export type VaultMetaTagger = (
225
+ next: Pick<VaultMeta, 'vaultId' | 'revision' | 'createdAt' | 'keys' | 'pendingRemoval'>
226
+ ) => Promise<string>
227
+
228
+ /** XR-001: same contract as VaultMetaTagger, for one `ready` draft record. */
229
+ export type VaultDraftTagger = (record: VaultKeyRecord) => Promise<string>
230
+
231
+ async function readMetaTag(token: VaultScopeToken): Promise<string | null> {
232
+ return (await SecureStore.getItemAsync(metaTagKey(token), SECURE_OPTIONS)) || null
233
+ }
234
+
235
+ async function writeMetaTag(token: VaultScopeToken, tag: string): Promise<void> {
236
+ if (typeof tag !== 'string' || tag.length === 0) {
237
+ throw new VaultError('template-invalid', 'Invalid vault meta authority tag')
238
+ }
239
+ await SecureStore.setItemAsync(metaTagKey(token), tag, SECURE_OPTIONS)
240
+ }
241
+
242
+ async function clearMetaTag(token: VaultScopeToken): Promise<void> {
243
+ await SecureStore.deleteItemAsync(metaTagKey(token), SECURE_OPTIONS)
244
+ }
245
+
246
+ /** Write `meta` and, when a tagger is supplied, its fresh authority tag —
247
+ * atomically within the caller's enqueueMutation critical section. The tag
248
+ * is computed BEFORE writeMeta so a tagger failure (a rejected wallet call)
249
+ * leaves storage completely untouched rather than updated-but-untagged. */
250
+ async function writeMetaAndTag(
251
+ token: VaultScopeToken,
252
+ meta: VaultMeta,
253
+ tagger?: VaultMetaTagger
254
+ ): Promise<void> {
255
+ const tag = tagger ? await tagger(meta) : undefined
256
+ await writeMeta(token, meta)
257
+ if (tag !== undefined) await writeMetaTag(token, tag)
258
+ }
259
+
260
+ async function readDraftTags(token: VaultScopeToken): Promise<Record<string, string>> {
261
+ const raw = await SecureStore.getItemAsync(draftTagStoreKey(token), SECURE_OPTIONS)
262
+ if (!raw) return {}
263
+ try {
264
+ const parsed = JSON.parse(raw)
265
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
266
+ const out: Record<string, string> = {}
267
+ for (const [serial, tag] of Object.entries(parsed as Record<string, unknown>)) {
268
+ if (isVaultSerial(serial) && typeof tag === 'string' && tag.length > 0) out[serial] = tag
269
+ }
270
+ return out
271
+ } catch {
272
+ // Corrupt draft-tag bookkeeping is never fatal: it only ever narrows what
273
+ // gets trusted as 'ready' (see VaultKeyService's verifyVaultDraftAuthorityTag
274
+ // use), never widens it.
275
+ return {}
276
+ }
277
+ }
278
+
279
+ async function writeDraftTags(token: VaultScopeToken, tags: Record<string, string>): Promise<void> {
280
+ const entries = Object.entries(tags)
281
+ if (entries.length === 0) await SecureStore.deleteItemAsync(draftTagStoreKey(token), SECURE_OPTIONS)
282
+ else await SecureStore.setItemAsync(draftTagStoreKey(token), JSON.stringify(tags), SECURE_OPTIONS)
283
+ }
284
+
168
285
  /** The wallet identity a captured scope belongs to, without its chain half. */
169
286
  function identityKeyFromToken(token: VaultScopeToken): string {
170
287
  const match = SCOPE_KEY_PATTERN.exec(token.storageKey)
@@ -302,7 +419,7 @@ export function isVaultMeta(value: unknown): value is VaultMeta {
302
419
  if (m.v !== 6 || typeof m.vaultId !== 'string' || !/^[0-9a-f]{64}$/.test(m.vaultId)) return false
303
420
  if (typeof m.revision !== 'number' || !Number.isSafeInteger(m.revision) || m.revision < 1) return false
304
421
  if (!isSafeTime(m.createdAt)) return false
305
- if (!Array.isArray(m.keys) || m.keys.length < MIN_KEYS || m.keys.length > MAX_KEYS) return false
422
+ if (!Array.isArray(m.keys) || m.keys.length < MIN_KEYS || m.keys.length > MAX_ACTIVE_KEYS) return false
306
423
  if (!m.keys.every(isVaultKeyRecord)) return false
307
424
  const keys = m.keys as VaultKeyRecord[]
308
425
  if (new Set(keys.map(k => k.serial)).size !== keys.length) return false
@@ -464,12 +581,23 @@ export const vaultStore = {
464
581
  configureScope(scope: VaultStoreScope): void {
465
582
  activeScope = normalizeScope(scope)
466
583
  scopeGeneration++
584
+ notifyScopeChange()
467
585
  },
468
586
 
469
587
  /** Drop the in-memory authority during logout, wallet rebuild or teardown. */
470
588
  clearScope(): void {
471
589
  activeScope = null
472
590
  scopeGeneration++
591
+ notifyScopeChange()
592
+ },
593
+
594
+ /** INT-08: notified after every configureScope/clearScope. Returns an
595
+ * unsubscribe function, matching ceremony.subscribe's shape. */
596
+ onScopeChange(cb: () => void): () => void {
597
+ scopeListeners.add(cb)
598
+ return () => {
599
+ scopeListeners.delete(cb)
600
+ }
473
601
  },
474
602
 
475
603
  getScope(): VaultStoreScope | null {
@@ -503,10 +631,21 @@ export const vaultStore = {
503
631
  /** Preserve a generated key under the wallet+chain captured before token
504
632
  * contact. Unlike authority writes, this may finish after the active scope
505
633
  * changes: it can write only the separate draft key encoded in `scopeToken`.
506
- * Assurance is monotonic and same-serial/pubkey conflicts fail closed. */
634
+ * Assurance is monotonic and same-serial/pubkey conflicts fail closed.
635
+ *
636
+ * XR-001: when the SAVED entry (after the monotonic-rank comparison below)
637
+ * ends up `ready` and a `tagger` is supplied, this also computes and stores
638
+ * that record's wallet-root authority tag — atomically, before the draft
639
+ * write, for the same TOCTOU reason writeMetaAndTag documents. A `ready`
640
+ * write with no tagger (a caller that has no wallet handy, or every
641
+ * pre-existing storage-level test) simply leaves the record untagged; the
642
+ * only place that ever matters is requireReadyEnrollmentDrafts /
643
+ * resumeEnrollmentDraft's fast path, which then correctly refuses to trust
644
+ * it as sufficient authority on its own. */
507
645
  async preserveEnrollmentDraft(
508
646
  entry: VaultEnrollmentDraftEntry,
509
- scopeToken: VaultScopeToken
647
+ scopeToken: VaultScopeToken,
648
+ tagger?: VaultDraftTagger
510
649
  ): Promise<VaultEnrollmentDraftEntry> {
511
650
  if (
512
651
  !isVaultKeyRecord(entry.record) ||
@@ -545,16 +684,32 @@ export const vaultStore = {
545
684
  const retainedQuarantines = quarantines.filter(item => item.serial !== entry.record.serial)
546
685
  const updatedAt = Date.now()
547
686
  if (!isSafeTime(updatedAt)) throw new VaultError('template-invalid', 'Invalid enrollment draft time')
687
+ const tag = tagger && saved.assurance === 'ready' ? await tagger(saved.record) : undefined
548
688
  await writeCapturedEnrollmentDraft(scopeToken, {
549
689
  v: 1,
550
690
  updatedAt,
551
691
  entries,
552
692
  quarantines: retainedQuarantines
553
693
  })
694
+ if (tag !== undefined) {
695
+ const tags = await readDraftTags(scopeToken)
696
+ tags[saved.record.serial] = tag
697
+ await writeDraftTags(scopeToken, tags)
698
+ }
554
699
  return { ...saved, record: { ...saved.record } }
555
700
  })
556
701
  },
557
702
 
703
+ /** XR-001: the wallet-root authority tag for a `ready` draft's serial, or
704
+ * null if none is on file (never tagged, or tagged under an assurance the
705
+ * caller's write path did not supply a tagger for). */
706
+ async getEnrollmentDraftTag(serial: string, scopeToken?: VaultScopeToken): Promise<string | null> {
707
+ const token = scopeToken ?? captureScope(true)
708
+ if (!isVaultSerial(serial)) throw new VaultError('template-invalid', 'Invalid enrollment draft serial')
709
+ const tags = await readDraftTags(token)
710
+ return tags[serial] ?? null
711
+ },
712
+
558
713
  /** Persist the no-secret intent marker BEFORE the first irreversible PIV
559
714
  * command for this serial. A process death while the APDU is in flight then
560
715
  * leaves a durable quarantine instead of making the next launch retry it as
@@ -647,6 +802,20 @@ export const vaultStore = {
647
802
  quarantines: current.quarantines
648
803
  })
649
804
  }
805
+ // XR-001: a consumed/discarded serial's tag must not linger — a later,
806
+ // unrelated draft that happens to reuse the same serial (a different
807
+ // physical card whose ratcheted serial format collides, or the same
808
+ // card re-enrolled) must never inherit a stale authority tag it never
809
+ // earned.
810
+ const tags = await readDraftTags(token)
811
+ let tagsChanged = false
812
+ for (const serial of consumed) {
813
+ if (serial in tags) {
814
+ delete tags[serial]
815
+ tagsChanged = true
816
+ }
817
+ }
818
+ if (tagsChanged) await writeDraftTags(token, tags)
650
819
  assertScope(token)
651
820
  })
652
821
  },
@@ -682,6 +851,7 @@ export const vaultStore = {
682
851
  return enqueueMutation(async () => {
683
852
  assertScope(token)
684
853
  await writeCapturedEnrollmentDraft(token, null)
854
+ await writeDraftTags(token, {})
685
855
  assertScope(token)
686
856
  })
687
857
  },
@@ -733,13 +903,21 @@ export const vaultStore = {
733
903
  return [...serials]
734
904
  },
735
905
 
736
- async setMeta(meta: VaultMeta, scopeToken?: VaultScopeToken): Promise<void> {
906
+ /** Raw meta write with no `current`-vs-`next` relationship at all (no
907
+ * production code path uses this — it exists for test fixtures). Since
908
+ * there is no `current` to launder, a tagger here is always safe to trust
909
+ * for whatever `meta` the caller supplies. */
910
+ async setMeta(meta: VaultMeta, scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<void> {
737
911
  const token = scopeToken ?? captureScope(true)
738
- return enqueueMutation(() => writeMeta(token, meta))
912
+ return enqueueMutation(() => writeMetaAndTag(token, meta, tagger))
739
913
  },
740
914
 
741
- /** Create one enrollment without a read/write scope-switch window. */
742
- async createEnrollment(meta: VaultMeta, scopeToken?: VaultScopeToken): Promise<void> {
915
+ /** Create one enrollment without a read/write scope-switch window.
916
+ *
917
+ * XR-002: a fresh enrollment has no prior authority to launder — this
918
+ * refuses outright whenever one already exists — so `tagger` is always
919
+ * safe to trust for whatever `meta` the caller (finalizeEnrollment) built. */
920
+ async createEnrollment(meta: VaultMeta, scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<void> {
743
921
  const token = scopeToken ?? captureScope(true)
744
922
  return enqueueMutation(async () => {
745
923
  const existing = await readMeta(token)
@@ -751,7 +929,7 @@ export const vaultStore = {
751
929
  { serial: existing.keys[0].serial }
752
930
  )
753
931
  }
754
- await writeMeta(token, meta)
932
+ await writeMetaAndTag(token, meta, tagger)
755
933
  })
756
934
  },
757
935
 
@@ -760,8 +938,20 @@ export const vaultStore = {
760
938
  * spendable output's real R1C lock. The caller performs that lock check;
761
939
  * this boundary performs strict schema validation and refuses to replace a
762
940
  * different live enrollment.
763
- */
764
- async restoreVerifiedMeta(meta: VaultMeta, scopeToken?: VaultScopeToken): Promise<void> {
941
+ *
942
+ * XR-002: this is the "safer route" requireAuthenticatedMeta
943
+ * (transfers.ts) falls back to for meta whose wallet-root tag is missing
944
+ * or invalid — never a silent trust-on-first-use. It is safe to tag
945
+ * whatever `restored` ends up being here without first re-verifying
946
+ * `current`'s own tag: in the same-revision branch, `restored`'s
947
+ * authority fields (vaultId/createdAt/revision/keys) come from `current`
948
+ * ONLY after the equality check just above already proved them identical
949
+ * to `checked` — itself independently authenticated against a real,
950
+ * chain-verified R1C lock by the caller; in the higher-revision branch
951
+ * they are taken from `checked` directly, never from `current`. Either
952
+ * way `current`'s own (possibly forged, possibly absent) tag never
953
+ * "launders" into the fresh one. */
954
+ async restoreVerifiedMeta(meta: VaultMeta, scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<void> {
765
955
  const token = scopeToken ?? captureScope(true)
766
956
  const checked = checkedMeta(meta)
767
957
  return enqueueMutation(async () => {
@@ -793,7 +983,7 @@ export const vaultStore = {
793
983
  const restored: VaultMeta = { ...current }
794
984
  if (pendingRemoval) restored.pendingRemoval = pendingRemoval
795
985
  else delete restored.pendingRemoval
796
- await writeMeta(token, restored)
986
+ await writeMetaAndTag(token, restored, tagger)
797
987
  return
798
988
  }
799
989
 
@@ -817,7 +1007,7 @@ export const vaultStore = {
817
1007
  restored.lastUsedAt = current.lastUsedAt
818
1008
  restored.lastUsedSerial = current.lastUsedSerial
819
1009
  }
820
- await writeMeta(token, restored)
1010
+ await writeMetaAndTag(token, restored, tagger)
821
1011
  })
822
1012
  },
823
1013
 
@@ -846,25 +1036,39 @@ export const vaultStore = {
846
1036
  }
847
1037
  },
848
1038
 
849
- async addKey(k: VaultKeyRecord, scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1039
+ /**
1040
+ * XR-002: `next` here is built by APPENDING to `meta.keys` — never
1041
+ * replacing it — so a forged `meta` (a substituted key set the caller
1042
+ * never authenticated) would otherwise "launder" straight through into a
1043
+ * freshly, validly tagged `next` merely because the user added one more,
1044
+ * genuinely their own, key. Callers MUST verify `meta`'s own existing tag
1045
+ * (or run it through the chain-authenticated recovery path) BEFORE calling
1046
+ * this with a `tagger` — see VaultKeyService.addVaultKey's
1047
+ * requireTaggedMeta call, which does exactly that.
1048
+ */
1049
+ async addKey(k: VaultKeyRecord, scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
850
1050
  const token = scopeToken ?? captureScope(true)
851
1051
  if (!isVaultKeyRecord(k)) throw new VaultError('template-invalid', 'Invalid vault key record')
852
1052
  return enqueueMutation(async () => {
853
1053
  const meta = await requireMeta(token)
854
1054
  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`)
1055
+ if (meta.keys.length >= MAX_ACTIVE_KEYS) {
1056
+ throw new VaultError('too-many-keys', `The vault already has ${MAX_ACTIVE_KEYS} keys`)
857
1057
  }
858
1058
  if (meta.keys.some(x => x.serial === k.serial || x.pubkey === k.pubkey)) {
859
1059
  throw new VaultError('key-already-enrolled', k.serial, undefined, { serial: k.serial })
860
1060
  }
861
1061
  const next: VaultMeta = { ...meta, revision: meta.revision + 1, keys: [...meta.keys, k] }
862
- await writeMeta(token, next)
1062
+ await writeMetaAndTag(token, next, tagger)
863
1063
  return next
864
1064
  })
865
1065
  },
866
1066
 
867
- async beginKeyRemoval(serial: string, scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1067
+ /** Same laundering caveat as addKey: `meta` must already be established as
1068
+ * trustworthy by the caller (transfers.ts's beginVaultKeyRemoval gates its
1069
+ * whole flow on requireAuthenticatedMeta before reaching here) before a
1070
+ * `tagger` is supplied. */
1071
+ async beginKeyRemoval(serial: string, scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
868
1072
  const token = scopeToken ?? captureScope(true)
869
1073
  return enqueueMutation(async () => {
870
1074
  const meta = await requireMeta(token)
@@ -893,12 +1097,12 @@ export const vaultStore = {
893
1097
  delete next.lastUsedSerial
894
1098
  delete next.lastUsedAt
895
1099
  }
896
- await writeMeta(token, next)
1100
+ await writeMetaAndTag(token, next, tagger)
897
1101
  return next
898
1102
  })
899
1103
  },
900
1104
 
901
- async markKeyRemovalBroadcast(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1105
+ async markKeyRemovalBroadcast(scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
902
1106
  const token = scopeToken ?? captureScope(true)
903
1107
  return enqueueMutation(async () => {
904
1108
  const meta = await requireMeta(token)
@@ -909,7 +1113,7 @@ export const vaultStore = {
909
1113
  ...meta,
910
1114
  pendingRemoval: { ...pending, state: 'broadcast' }
911
1115
  }
912
- await writeMeta(token, next)
1116
+ await writeMetaAndTag(token, next, tagger)
913
1117
  return next
914
1118
  })
915
1119
  },
@@ -917,7 +1121,7 @@ export const vaultStore = {
917
1121
  /** Caller must establish from authenticated action history and two complete
918
1122
  * output scans that no spendable lock still authorizes the removed key and
919
1123
  * that no relevant action is pending before invoking. */
920
- async finalizeProvenKeyRemoval(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1124
+ async finalizeProvenKeyRemoval(scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
921
1125
  const token = scopeToken ?? captureScope(true)
922
1126
  return enqueueMutation(async () => {
923
1127
  const meta = await requireMeta(token)
@@ -927,18 +1131,19 @@ export const vaultStore = {
927
1131
  }
928
1132
  const next: VaultMeta = { ...meta }
929
1133
  delete next.pendingRemoval
930
- await writeMeta(token, next)
1134
+ await writeMetaAndTag(token, next, tagger)
931
1135
  return next
932
1136
  })
933
1137
  },
934
1138
 
935
1139
  /**
936
1140
  * Complete a removal when the authoritative preflight and postflight scans
937
- * both prove there were no vault outputs to relock. The transfer layer owns
1141
+ * both prove no vault output commits the key, so there is nothing to
1142
+ * relock (an empty vault, or a key never locked to). The transfer layer owns
938
1143
  * those scans and serializes them with deposits; this method only permits
939
1144
  * the corresponding untouched, unbroadcast state transition.
940
1145
  */
941
- async finalizeEmptyKeyRemoval(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1146
+ async finalizeEmptyKeyRemoval(scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
942
1147
  const token = scopeToken ?? captureScope(true)
943
1148
  return enqueueMutation(async () => {
944
1149
  const meta = await requireMeta(token)
@@ -948,7 +1153,7 @@ export const vaultStore = {
948
1153
  }
949
1154
  const next: VaultMeta = { ...meta }
950
1155
  delete next.pendingRemoval
951
- await writeMeta(token, next)
1156
+ await writeMetaAndTag(token, next, tagger)
952
1157
  return next
953
1158
  })
954
1159
  },
@@ -957,7 +1162,7 @@ export const vaultStore = {
957
1162
  * Restore a prepared key only after the caller has proved no transaction was
958
1163
  * broadcast (for example, its reserved action was successfully aborted).
959
1164
  */
960
- async cancelUnbroadcastKeyRemoval(scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1165
+ async cancelUnbroadcastKeyRemoval(scopeToken?: VaultScopeToken, tagger?: VaultMetaTagger): Promise<VaultMeta> {
961
1166
  const token = scopeToken ?? captureScope(true)
962
1167
  return enqueueMutation(async () => {
963
1168
  const meta = await requireMeta(token)
@@ -969,12 +1174,20 @@ export const vaultStore = {
969
1174
  keys.splice(pending.keyIndex, 0, pending.key)
970
1175
  const next: VaultMeta = { ...meta, revision: meta.revision + 1, keys }
971
1176
  delete next.pendingRemoval
972
- await writeMeta(token, next)
1177
+ await writeMetaAndTag(token, next, tagger)
973
1178
  return next
974
1179
  })
975
1180
  },
976
1181
 
977
- async renameKey(serial: string, nickname: string, scopeToken?: VaultScopeToken): Promise<VaultMeta> {
1182
+ /** Same laundering caveat as addKey: the caller (VaultScreen's rename
1183
+ * action) must establish `meta` is trustworthy via requireAuthenticatedMeta
1184
+ * before supplying a `tagger`. */
1185
+ async renameKey(
1186
+ serial: string,
1187
+ nickname: string,
1188
+ scopeToken?: VaultScopeToken,
1189
+ tagger?: VaultMetaTagger
1190
+ ): Promise<VaultMeta> {
978
1191
  const token = scopeToken ?? captureScope(true)
979
1192
  return enqueueMutation(async () => {
980
1193
  const meta = await requireMeta(token)
@@ -988,7 +1201,7 @@ export const vaultStore = {
988
1201
  revision: meta.revision + 1,
989
1202
  keys: meta.keys.map(x => (x.serial === serial ? { ...x, nickname: clean } : x))
990
1203
  }
991
- await writeMeta(token, next)
1204
+ await writeMetaAndTag(token, next, tagger)
992
1205
  return next
993
1206
  })
994
1207
  },
@@ -1013,9 +1226,23 @@ export const vaultStore = {
1013
1226
  if (meta?.pendingRemoval) throw new VaultError('relock-required', 'Finish the pending key removal first')
1014
1227
  assertScope(token)
1015
1228
  await SecureStore.deleteItemAsync(token.storageKey, SECURE_OPTIONS)
1229
+ await clearMetaTag(token)
1016
1230
  assertScope(token)
1017
1231
  await writeCapturedEnrollmentDraft(token, null)
1232
+ await writeDraftTags(token, {})
1018
1233
  assertScope(token)
1019
1234
  })
1235
+ },
1236
+
1237
+ /** XR-002: the wallet-root authority tag on file for this scope's VaultMeta,
1238
+ * or null if none exists (never tagged — every enrollment created before
1239
+ * this fix shipped — or explicitly cleared). Read by
1240
+ * transfers.ts's requireAuthenticatedMeta and by every meta-mutating
1241
+ * caller that must verify `current` before trusting it as the basis for a
1242
+ * freshly tagged `next` (see addKey/beginKeyRemoval/renameKey's laundering
1243
+ * caveat above). */
1244
+ async getMetaTag(scopeToken?: VaultScopeToken): Promise<string | null> {
1245
+ const token = scopeToken ?? captureScope(true)
1246
+ return readMetaTag(token)
1020
1247
  }
1021
1248
  }
@@ -54,6 +54,13 @@ export interface WalletArgLimits {
54
54
  internalizeTx: number
55
55
  /** One output's customInstructions string. */
56
56
  customInstructions: number
57
+ /** One byte-array field of encrypt/decrypt/createHmac/verifyHmac/
58
+ * createSignature/verifySignature (plaintext, ciphertext, data, hmac,
59
+ * signature, hashToDirectlySign, hashToDirectlyVerify). These carry small,
60
+ * bounded payloads in every legitimate use (a hash, a short ciphertext) —
61
+ * nothing like a transaction — so this is set far below the raw transport
62
+ * ceiling (MAX_RPC_PLAINTEXT_BYTES) rather than sized to it. */
63
+ cryptoPayload: number
57
64
  }
58
65
 
59
66
  const MB = 1024 * 1024
@@ -68,7 +75,8 @@ const BASE: WalletArgLimits = {
68
75
  unlockingScript: 100_000,
69
76
  inputBEEF: 2 * MB,
70
77
  internalizeTx: 1 * MB,
71
- customInstructions: 4096
78
+ customInstructions: 4096,
79
+ cryptoPayload: 1 * MB
72
80
  }
73
81
 
74
82
  /**
@@ -80,7 +88,9 @@ const BASE: WalletArgLimits = {
80
88
  * observed traffic, not to the memory budget.
81
89
  */
82
90
  export function limitsForTier(tier: DeviceTier): WalletArgLimits {
83
- return tier === 'low' ? { ...BASE, aggregate: BASE.aggregate / 2 } : { ...BASE }
91
+ return tier === 'low'
92
+ ? { ...BASE, aggregate: BASE.aggregate / 2, cryptoPayload: BASE.cryptoPayload / 2 }
93
+ : { ...BASE }
84
94
  }
85
95
 
86
96
  export interface ArgRefusal {
@@ -93,6 +103,25 @@ export interface ArgRefusal {
93
103
  /** Calls that can carry transaction bytes. Everything else passes untouched. */
94
104
  const SIZED_CALLS = new Set(['createAction', 'signAction', 'internalizeAction'])
95
105
 
106
+ /**
107
+ * XR-026: these carry only small byte-array fields (a hash, a short
108
+ * ciphertext) in every legitimate use, but previously had NO per-call size
109
+ * cap at all beyond the raw 5 MiB transport ceiling shared with every other
110
+ * paired-RPC method.
111
+ */
112
+ const CRYPTO_CALLS = new Set(['encrypt', 'decrypt', 'createHmac', 'verifyHmac', 'createSignature', 'verifySignature'])
113
+ /** The byte-array fields these calls can carry. Checked by name rather than
114
+ * per-call, since each call only ever supplies a subset of them. */
115
+ const CRYPTO_PAYLOAD_FIELDS = [
116
+ 'plaintext',
117
+ 'ciphertext',
118
+ 'data',
119
+ 'hmac',
120
+ 'signature',
121
+ 'hashToDirectlySign',
122
+ 'hashToDirectlyVerify'
123
+ ] as const
124
+
96
125
  const refuse = (field: string, actual: number, limit: number, why?: string): ArgRefusal => ({
97
126
  field,
98
127
  limit,
@@ -127,6 +156,20 @@ const startsWithInvalidOpcode = (script: unknown): boolean =>
127
156
  * surface as an opaque wallet error instead of a size refusal.
128
157
  */
129
158
  export function checkWalletArgs(call: string, args: unknown, limits: WalletArgLimits): ArgRefusal | null {
159
+ if (CRYPTO_CALLS.has(call)) {
160
+ const a = asRecord(args)
161
+ if (!a) return null
162
+ try {
163
+ for (const field of CRYPTO_PAYLOAD_FIELDS) {
164
+ const bytes = arrayBytes(a[field])
165
+ if (bytes > limits.cryptoPayload) return refuse(field, bytes, limits.cryptoPayload)
166
+ }
167
+ return null
168
+ } catch {
169
+ return null
170
+ }
171
+ }
172
+
130
173
  if (!SIZED_CALLS.has(call)) return null
131
174
  const a = asRecord(args)
132
175
  if (!a) return null