@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
@@ -3,17 +3,34 @@ import type { BsvExchangeRate } from '../toolboxTypes'
3
3
 
4
4
  // Shared with context/ExchangeRateContext.tsx so a single cache serves both the
5
5
  // fiat-display UI and the wallet-build seed. Same key + same { usdPerBsv } shape.
6
- const CACHE_KEY = 'cached_exchange_rate'
7
- const FALLBACK_RATE = 16.75
6
+ // Exported (misc-p2-05) so ExchangeRateContext no longer keeps its own,
7
+ // disagreeing copies of the cache key and the fallback rate.
8
+ export const CACHE_KEY = 'cached_exchange_rate'
9
+ export const FALLBACK_RATE = 16.75
8
10
  const REFRESH_TIMEOUT_MS = 4000
9
11
 
10
12
  /**
11
- * Fire-and-forget refresh of the cached BSV/USD rate. Timeout-guarded so it can
12
- * NEVER hang the JS thread or the wallet build — it is never awaited by callers.
13
- * The result is only persisted to AsyncStorage for the next cold start.
13
+ * `getExchangeRate()`'s own return, plus a handle on the SAME background
14
+ * refresh it kicks off — so a caller that wants the live rate once it lands
15
+ * (ExchangeRateContext) does not need a second fetch/timeout of its own.
16
+ * `refreshed` never rejects: every failure mode inside the refresh (network,
17
+ * abort, a malformed body) is caught and reported as `undefined`, exactly as
18
+ * `refreshExchangeRateCache` always resolved before this — a caller that
19
+ * ignores `refreshed` entirely (the wallet-build seed) sees no change at all.
14
20
  */
15
- function refreshExchangeRateCache(): void {
16
- ;(async () => {
21
+ export interface ExchangeRateSeed extends BsvExchangeRate {
22
+ refreshed: Promise<number | undefined>
23
+ }
24
+
25
+ /**
26
+ * Timeout-guarded refresh of the cached BSV/USD rate. NEVER hangs the JS
27
+ * thread or the wallet build: `getExchangeRate` does not await this before
28
+ * returning, only the promise it hands back for whoever wants to know when
29
+ * it lands. The live rate, once fetched, is persisted to AsyncStorage for the
30
+ * next cold start regardless of whether anyone is listening this session.
31
+ */
32
+ function refreshExchangeRateCache(): Promise<number | undefined> {
33
+ return (async () => {
17
34
  const controller = new AbortController()
18
35
  const timeout = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS)
19
36
  try {
@@ -24,9 +41,12 @@ function refreshExchangeRateCache(): void {
24
41
  const usdPerBsv = Number(data?.rate)
25
42
  if (Number.isFinite(usdPerBsv) && usdPerBsv > 0) {
26
43
  await AsyncStorage.setItem(CACHE_KEY, JSON.stringify({ usdPerBsv, timestamp: new Date().toISOString() }))
44
+ return usdPerBsv
27
45
  }
46
+ return undefined
28
47
  } catch (error) {
29
48
  console.error('Error refreshing exchange rate:', error)
49
+ return undefined
30
50
  } finally {
31
51
  clearTimeout(timeout)
32
52
  }
@@ -44,9 +64,10 @@ function refreshExchangeRateCache(): void {
44
64
  * CWI provider before page JS — so a cached/hardcoded seed is fully correct.
45
65
  *
46
66
  * Reads the shared cache (one fast AsyncStorage get), falls back to a hardcoded
47
- * value, and kicks off a background refresh for next time. Never hangs.
67
+ * value, and kicks off a background refresh for next time. Never hangs: the
68
+ * refresh itself is only awaited by a caller that chooses to await `refreshed`.
48
69
  */
49
- export async function getExchangeRate(): Promise<BsvExchangeRate> {
70
+ export async function getExchangeRate(): Promise<ExchangeRateSeed> {
50
71
  let rate = FALLBACK_RATE
51
72
  try {
52
73
  const cached = await AsyncStorage.getItem(CACHE_KEY)
@@ -57,7 +78,9 @@ export async function getExchangeRate(): Promise<BsvExchangeRate> {
57
78
  } catch (error) {
58
79
  console.error('Error reading cached exchange rate:', error)
59
80
  }
60
- // Refresh the cache in the background — never awaited, never blocks the build.
61
- refreshExchangeRateCache()
62
- return { timestamp: new Date(), rate, base: 'USD' }
81
+ // One fetch, kicked off here and never awaited by this function — the
82
+ // build seed above is already resolved. `refreshed` is the SAME promise,
83
+ // just handed to the caller instead of dropped.
84
+ const refreshed = refreshExchangeRateCache()
85
+ return { timestamp: new Date(), rate, base: 'USD', refreshed }
63
86
  }
@@ -1,4 +1,5 @@
1
1
  import { ADMIN_ORIGINATOR } from '../config'
2
+ import { isPrivateNetworkHost } from '../net/publicDestination'
2
3
 
3
4
  export interface ExternalOrigin {
4
5
  /** Canonical HTTPS origin used for relay discovery and persistence. */
@@ -38,5 +39,15 @@ export function parseExternalOrigin(raw: string): ExternalOrigin {
38
39
  if (hostname === 'invalid' || hostname.endsWith('.invalid') || originator === ADMIN_ORIGINATOR.toLowerCase()) {
39
40
  throw new Error('Origin is reserved for the wallet')
40
41
  }
42
+ // XR-024 (SEC2-055): TLS certificate validity gates WHO can claim a given
43
+ // hostname, not WHERE that hostname points -- a self-signed pairing payload
44
+ // naming a loopback/RFC1918/link-local literal directly gets a real fetch
45
+ // into the device's own local network with no DNS trickery needed. This is
46
+ // a floor, not a firewall: a public hostname that only *resolves* to such
47
+ // an address (DNS rebinding) needs a redirect/connect-time check on the
48
+ // platform's networking stack, which this codebase does not have.
49
+ if (isPrivateNetworkHost(url.hostname)) {
50
+ throw new Error('Origin must not name a loopback or private-network destination')
51
+ }
41
52
  return { origin: url.origin, originator }
42
53
  }
@@ -56,13 +56,35 @@ export function peekKek(): { kek: number[]; kekId: string } | null {
56
56
 
57
57
  /* ------------------------------- sentinel -------------------------------- */
58
58
 
59
- export async function readSentinel(): Promise<KekSentinel | null> {
59
+ /**
60
+ * `{ strict: true }` rethrows instead of swallowing to null — mirroring the
61
+ * same idiom `readLegacySecret`/`hasSecret` already use elsewhere in this
62
+ * package. `putSecret` (store.ts) needs this: it uses a null sentinel as
63
+ * its signal that no wallet was EVER stored, and takes that straight to
64
+ * `provisionKek()`, which unconditionally deletes both KEK keychain items
65
+ * first. A transient read failure must never be read as "no wallet ever" —
66
+ * that would delete a real KEK out from under an already-sealed envelope,
67
+ * orphaning it beyond recovery. The default (non-strict) callers here
68
+ * (`recordSecretName`/`forgetSecretName`) keep the swallow: they already
69
+ * no-op on a missing/unreadable sentinel, so there is nothing for them to
70
+ * protect by throwing.
71
+ */
72
+ export async function readSentinel(options?: { strict?: boolean }): Promise<KekSentinel | null> {
60
73
  try {
61
74
  const raw = await SecureStore.getItemAsync(SENTINEL_KEY, envOptions)
62
75
  if (!raw) return null
63
76
  const parsed = JSON.parse(raw) as KekSentinel
64
- return parsed?.v === 1 && typeof parsed.kekId === 'string' ? parsed : null
65
- } catch {
77
+ if (parsed?.v === 1 && typeof parsed.kekId === 'string') return parsed
78
+ // XR-109: the item exists and parses as JSON, but not into a committed
79
+ // sentinel's shape (a truncated write, a future/rolled-back version, ...).
80
+ // This must not be indistinguishable from "no sentinel" to a strict
81
+ // caller: putSecret takes a null sentinel as "provision a fresh KEK",
82
+ // which deletes both KEK keychain items before minting a new one —
83
+ // exactly the destructive path a merely-unreadable sentinel already
84
+ // guards against below.
85
+ throw new Error('sentinel: corrupt')
86
+ } catch (err) {
87
+ if (options?.strict) throw err
66
88
  return null
67
89
  }
68
90
  }
@@ -124,14 +146,25 @@ export async function provisionKek(): Promise<UnlockState> {
124
146
 
125
147
  // Delete-then-add, never blind-write: writing over an existing item takes
126
148
  // iOS's update path, which prompts a second time on an ACL item.
149
+ //
150
+ // XQ-013: this guarantees that on iOS ONLY. iOS's deleteValueWithKeyAsync
151
+ // issues SecItemDelete against every Keychain alias for the key, so the
152
+ // add really does start clean. Android's deleteItemImpl only strips the
153
+ // SharedPreferences ciphertext record — it never calls the AndroidKeyStore
154
+ // `keyStore.deleteEntry` that would drop the underlying hardware-backed
155
+ // wrapping key (that call is reachable only from setItemImpl's
156
+ // KeyPermanentlyInvalidatedException retry branch, never from a plain
157
+ // delete). So on Android, "destroy then re-provision" removes the stored
158
+ // value but silently REUSES the pre-existing hardware key to wrap the new
159
+ // one, rather than minting a fresh one. This is not a secret-exposure or
160
+ // spend-authorization gap — the KEK value itself is still freshly random
161
+ // and still gated by a fresh biometric prompt before use — but nothing in
162
+ // this file (or its callers) should assume "full key rotation on both
163
+ // platforms" from a delete-then-add cycle; only iOS gets that.
127
164
  await deleteBothKekItems()
128
165
 
129
166
  try {
130
- await SecureStore.setItemAsync(
131
- resolved.keyName,
132
- Utils.toHex(kek),
133
- kekOptions(resolved.requireAuthentication)
134
- )
167
+ await SecureStore.setItemAsync(resolved.keyName, Utils.toHex(kek), kekOptions(resolved.requireAuthentication))
135
168
  } catch (err) {
136
169
  return setState(classifyAuthError(err))
137
170
  }
@@ -200,10 +233,7 @@ async function doUnlock(promptMessage?: string): Promise<UnlockState> {
200
233
  const resolved = policyFor(sentinel.policy)
201
234
  let raw: string | null
202
235
  try {
203
- raw = await SecureStore.getItemAsync(
204
- resolved.keyName,
205
- kekOptions(resolved.requireAuthentication, promptMessage)
206
- )
236
+ raw = await SecureStore.getItemAsync(resolved.keyName, kekOptions(resolved.requireAuthentication, promptMessage))
207
237
  } catch (err) {
208
238
  return setState(classifyAuthError(err))
209
239
  }
@@ -212,47 +242,114 @@ async function doUnlock(promptMessage?: string): Promise<UnlockState> {
212
242
  // report that as a plain null, which is why the sentinel has to exist.
213
243
  if (raw === null) return setState({ status: 'lost' })
214
244
 
215
- cached = { kek: Utils.toArray(raw, 'hex') as number[], kekId: sentinel.kekId, policy: sentinel.policy }
245
+ // Held locally, NOT in the module-level `cached`, until any mandatory
246
+ // upgrade below has actually completed. Populating `cached` early (as this
247
+ // used to) makes `isUnlocked()`/`getSecret()` honour a non-biometric value
248
+ // even when the upgrade that was supposed to gate it fails or is refused.
249
+ const pending = { kek: Utils.toArray(raw, 'hex') as number[], kekId: sentinel.kekId, policy: sentinel.policy }
216
250
 
217
251
  // A production build must not keep running on a KEK that a development
218
- // build provisioned without OS enforcement.
252
+ // build (or a forged sentinel) provisioned without OS enforcement.
219
253
  if (await needsUpgrade(sentinel.policy)) {
220
- const upgraded = await upgradeToBiometric(sentinel)
221
- if (upgraded) return setState(upgraded)
254
+ const upgraded = await upgradeToBiometric(sentinel, pending)
255
+ if (!upgraded) {
256
+ // The mandatory rewrap did not happen: a declined/failed ceremony, a
257
+ // write failure, or (XR-108) a sentinel claiming a weaker policy than
258
+ // an identity this device already has. Never fall through to
259
+ // `unlocked` on the pre-upgrade value — that is exactly the bypass
260
+ // this gate exists to prevent. Nothing was cached, so the KEK stays
261
+ // locked; the next launch (or an explicit retry) tries again.
262
+ return setState({ status: 'cancelled' })
263
+ }
264
+ cached = { kek: pending.kek, kekId: pending.kekId, policy: 'biometric' }
265
+ return setState(upgraded)
222
266
  }
223
267
 
268
+ cached = pending
224
269
  return setState({ status: 'unlocked', kekId: sentinel.kekId, policy: cached.policy })
225
270
  }
226
271
 
227
272
  /**
228
- * Re-wrap the same KEK value under an authenticated item. The envelope blobs
229
- * are untouched because the KEK itself does not change.
273
+ * Re-wrap a KEK value under an authenticated item. The envelope blobs are
274
+ * untouched because the KEK itself does not change.
275
+ *
276
+ * Takes the pending KEK explicitly rather than reading module-level `cached`:
277
+ * this runs before the caller has decided the upgrade succeeded, so nothing
278
+ * should be globally visible as "the" KEK yet.
230
279
  */
231
- export async function upgradeToBiometric(sentinel: KekSentinel): Promise<UnlockState | null> {
232
- if (!cached) return null
280
+ export async function upgradeToBiometric(
281
+ sentinel: KekSentinel,
282
+ pending: { kek: number[]; kekId: string }
283
+ ): Promise<UnlockState | null> {
233
284
  try {
285
+ // XR-108: refuse to relegitimize a weaker (or forged) sentinel over an
286
+ // install that already has a genuine biometric-protected key. A value
287
+ // here means a real ceremony produced it at some point; any sentinel now
288
+ // claiming a non-biometric policy is stale at best, forged at worst —
289
+ // either way it must not get laundered into the authenticated slot.
290
+ // This read costs exactly the ceremony an honest upgrade needs anyway
291
+ // (the device has strong biometrics, or `needsUpgrade` would be false),
292
+ // and a thrown/cancelled read is treated the same as "found something":
293
+ // refuse, rather than assume empty and proceed.
294
+ let existingAuthKey: string | null
295
+ try {
296
+ existingAuthKey = await SecureStore.getItemAsync(KEK_AUTH_KEY, kekOptions(true))
297
+ } catch {
298
+ return null
299
+ }
300
+ if (existingAuthKey !== null) return null
301
+
234
302
  await SecureStore.deleteItemAsync(KEK_AUTH_KEY, kekOptions(true)).catch(() => {})
235
- await SecureStore.setItemAsync(KEK_AUTH_KEY, Utils.toHex(cached.kek), kekOptions(true))
303
+ await SecureStore.setItemAsync(KEK_AUTH_KEY, Utils.toHex(pending.kek), kekOptions(true))
236
304
  await writeSentinel({ ...sentinel, policy: 'biometric' })
237
305
  await SecureStore.deleteItemAsync(KEK_PLAIN_KEY, kekOptions(false)).catch(() => {})
238
- cached = { ...cached, policy: 'biometric' }
239
- return { status: 'unlocked', kekId: cached.kekId, policy: 'biometric' }
306
+ // XR-116: iOS's delete discards every OSStatus and never throws, so "it
307
+ // resolved" is not evidence the item is gone (same rationale as
308
+ // migration.ts's sweepLegacyKeys). Read it back before claiming the
309
+ // install is biometric-only: reporting success while the unauthenticated
310
+ // copy still exists would be exactly the false "protected by Face ID"
311
+ // promise this transition exists to keep true. The sentinel/KEK_AUTH_KEY
312
+ // writes above already stand — the next launch reads the committed
313
+ // 'biometric' policy directly and prompts normally — this only refuses to
314
+ // claim THIS session's transition fully succeeded.
315
+ const stalePlain = await SecureStore.getItemAsync(KEK_PLAIN_KEY, kekOptions(false)).catch(() => null)
316
+ if (stalePlain !== null) return null
317
+ return { status: 'unlocked', kekId: pending.kekId, policy: 'biometric' }
240
318
  } catch {
241
- // Leave the install exactly as it was; we still hold the KEK in memory for
242
- // this session and will retry the upgrade on the next launch.
319
+ // Leave the install exactly as it was; the caller does not cache
320
+ // anything on a null return, and will retry the upgrade on next launch.
243
321
  return null
244
322
  }
245
323
  }
246
324
 
247
325
  /* -------------------------------- teardown -------------------------------- */
248
326
 
249
- /** Prompt-free, and works while locked or lost — otherwise a user whose
250
- * biometrics changed could never log out. */
327
+ /**
328
+ * Prompt-free, and works while locked or lost — otherwise a user whose
329
+ * biometrics changed could never log out.
330
+ *
331
+ * KEK_AUTH_KEY stays a single blind delete: verifying it would require an
332
+ * authenticated read, i.e. exactly the live ceremony this function must never
333
+ * need. KEK_PLAIN_KEY and the sentinel are both unauthenticated, so verifying
334
+ * (and retrying) their removal is free — and matters more here, since a
335
+ * surviving KEK_PLAIN_KEY is the mnemonic-decrypting key sitting in
336
+ * cleartext, not merely an inert, harmless leftover (XR-111; same iOS
337
+ * silent-no-op-delete rationale as migration.ts's sweepLegacyKeys).
338
+ */
251
339
  export async function destroyKek(): Promise<void> {
252
340
  cached = null
253
341
  autoUnlockSpent = false
254
- await deleteBothKekItems()
255
- await SecureStore.deleteItemAsync(SENTINEL_KEY, envOptions).catch(() => {})
342
+ await SecureStore.deleteItemAsync(KEK_AUTH_KEY, kekOptions(true)).catch(() => {})
343
+
344
+ for (let attempt = 0; attempt < 2; attempt++) {
345
+ await SecureStore.deleteItemAsync(KEK_PLAIN_KEY, kekOptions(false)).catch(() => {})
346
+ await SecureStore.deleteItemAsync(SENTINEL_KEY, envOptions).catch(() => {})
347
+ const plainGone = (await SecureStore.getItemAsync(KEK_PLAIN_KEY, kekOptions(false)).catch(() => null)) === null
348
+ const sentinelGone = (await SecureStore.getItemAsync(SENTINEL_KEY, envOptions).catch(() => null)) === null
349
+ if (plainGone && sentinelGone) break
350
+ if (attempt === 1) console.warn('[secrets] plain KEK or sentinel survived deletion')
351
+ }
352
+
256
353
  setState({ status: 'absent' })
257
354
  }
258
355
 
@@ -29,7 +29,14 @@ const MAX_ATTEMPTS = 3
29
29
 
30
30
  export type MigrationResult =
31
31
  | { outcome: 'not-needed' }
32
- | { outcome: 'migrated'; names: SecretName[] }
32
+ /** XR-111: `legacyCleanupPending` is set when sweepLegacyKeys() could not
33
+ * verify every legacy item is gone (iOS's delete discards every OSStatus
34
+ * and never throws, so a resolved call is not evidence). The migration
35
+ * itself — envelope write, read-back, verify, sentinel commit — already
36
+ * fully succeeded either way; only the irreversible plaintext erasure did
37
+ * not, and it is retried on every subsequent launch via the `not-needed`
38
+ * branch above, which also sweeps. */
39
+ | { outcome: 'migrated'; names: SecretName[]; legacyCleanupPending?: true }
33
40
  | { outcome: 'failed'; stage: string; retryable: boolean }
34
41
 
35
42
  /** Reads a legacy plaintext item. Prompt-free — these were always written
@@ -181,9 +188,14 @@ export async function migrateLegacySecrets(): Promise<MigrationResult> {
181
188
  await recordSecretName(name)
182
189
  }
183
190
 
184
- // Step 7 — the irreversible bit.
185
- await sweepLegacyKeys()
191
+ // Step 7 — the irreversible bit. The boolean matters: a `false` here means
192
+ // a legacy plaintext survived verified deletion, and the caller must not
193
+ // be told cleanup is done when it is not (XR-111). The sweep itself
194
+ // already retries on every subsequent launch via the `not-needed` branch
195
+ // above, so this only affects what THIS call reports, not whether cleanup
196
+ // keeps being attempted.
197
+ const swept = await sweepLegacyKeys()
186
198
  await AsyncStorage.removeItem(FAILURE_COUNT_KEY).catch(() => {})
187
199
 
188
- return { outcome: 'migrated', names }
200
+ return swept ? { outcome: 'migrated', names } : { outcome: 'migrated', names, legacyCleanupPending: true }
189
201
  }
@@ -8,15 +8,8 @@
8
8
  */
9
9
  import * as SecureStore from 'expo-secure-store'
10
10
  import { openSecret, sealSecret, assertKekId } from './envelope'
11
- import {
12
- destroyKek,
13
- forgetSecretName,
14
- peekKek,
15
- provisionKek,
16
- readSentinel,
17
- recordSecretName,
18
- unlockKek
19
- } from './kek'
11
+ import { destroyKek, forgetSecretName, peekKek, provisionKek, readSentinel, recordSecretName, unlockKek } from './kek'
12
+ import { sweepLegacyKeys } from './migration'
20
13
  import { envKey, envOptions } from './storage'
21
14
  import { EnvelopeBlob, EnvelopeError, SECRET_NAMES, SecretName } from './types'
22
15
 
@@ -79,12 +72,31 @@ export async function getSecret(name: SecretName): Promise<string | null> {
79
72
  * Seal and store. Provisions a KEK on first use, which is the only moment a
80
73
  * write can prompt (and only on Android, where minting an auth-bound key
81
74
  * requires a ceremony).
75
+ *
76
+ * The sentinel read here is `{ strict: true }` (P2-store-transient-sentinel):
77
+ * a null sentinel means "provision a fresh KEK", and provisionKek() deletes
78
+ * both KEK keychain items unconditionally before minting a new one. A
79
+ * transient read failure must never be read the same way as a genuinely
80
+ * absent sentinel — that would delete a real KEK out from under an
81
+ * already-sealed envelope, orphaning it beyond recovery. Refusing the write
82
+ * (same externally-visible shape as a declined biometric prompt) is the safe
83
+ * failure here, not a silent re-provision.
82
84
  */
83
85
  export async function putSecret(name: SecretName, value: string): Promise<boolean> {
84
86
  let held = peekKek()
85
87
 
86
88
  if (!held) {
87
- const sentinel = await readSentinel()
89
+ let sentinel: Awaited<ReturnType<typeof readSentinel>>
90
+ try {
91
+ sentinel = await readSentinel({ strict: true })
92
+ } catch (err) {
93
+ console.warn(
94
+ '[secrets] sentinel read failed; refusing to write rather than re-provision',
95
+ name,
96
+ (err as Error)?.message
97
+ )
98
+ return false
99
+ }
88
100
  const result = sentinel ? await unlockKek() : await provisionKek()
89
101
  if (result.status !== 'unlocked') return false
90
102
  held = peekKek()
@@ -113,15 +125,31 @@ export async function deleteSecret(name: SecretName): Promise<void> {
113
125
  }
114
126
  }
115
127
 
116
- /** Removes every wrapped secret and the KEK itself, so the next launch reads
117
- * as a clean install rather than prompting for a wallet that no longer exists. */
118
- export async function deleteAllSecrets(): Promise<void> {
128
+ /**
129
+ * Removes every wrapped secret and the KEK itself, so the next launch reads
130
+ * as a clean install rather than prompting for a wallet that no longer exists.
131
+ *
132
+ * Returns whether the legacy plaintext namespace was actually verified gone.
133
+ * XR-107: sweepLegacyKeys() read-back-verifies its own deletes, so `false`
134
+ * here is real evidence — not a guess — that a mnemonic/recoveredKey/password
135
+ * item survived. The caller (Delete Wallet) must not report success or
136
+ * navigate away as though the wallet were fully erased when this is false;
137
+ * it must fail closed and let the user retry.
138
+ */
139
+ export async function deleteAllSecrets(): Promise<boolean> {
119
140
  for (const name of SECRET_NAMES) {
120
141
  try {
121
142
  await SecureStore.deleteItemAsync(envKey(name), envOptions)
122
143
  } catch {
123
- /* best effort — destroyKek below is what matters */
144
+ /* best effort: these are ciphertext, and the unconditional destroyKek()
145
+ * below is what actually renders any surviving blob unreadable. */
124
146
  }
125
147
  }
148
+ // XR-107: a pre-envelope legacy plaintext (mnemonic/recoveredKey/password)
149
+ // is a separate keychain namespace from the envelope above and survives it
150
+ // untouched otherwise, letting a later holder of this device rebuild full
151
+ // spend authority after the user believes "Delete Wallet" erased everything.
152
+ const legacyErased = await sweepLegacyKeys()
126
153
  await destroyKek()
154
+ return legacyErased
127
155
  }