@bsv/expo-wallet-toolbox 0.1.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 (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,274 @@
1
+ /**
2
+ * The key-encryption key: the one thing on this device that the OS refuses to
3
+ * hand over without a biometric match.
4
+ *
5
+ * Everything else — the mnemonic, the recovered WIF — is AES-256-GCM
6
+ * ciphertext sitting in ordinary unauthenticated storage. Reading those costs
7
+ * zero prompts. Reading the KEK costs exactly one, once per process, because
8
+ * the value is cached in memory afterwards. That is what buys "one Face ID
9
+ * check at wallet instantiation, held until the process dies" without making
10
+ * the check ceremonial: patching JavaScript now yields ciphertext.
11
+ *
12
+ * SECURITY: never log the KEK, and never re-export peekKek outside this
13
+ * directory.
14
+ */
15
+ import * as SecureStore from 'expo-secure-store'
16
+ import { Utils } from '@bsv/sdk'
17
+ import { generateKek, generateKekId } from './envelope'
18
+ import { KEK_AUTH_KEY, KEK_PLAIN_KEY, needsUpgrade, policyFor, resolveProvisioningPolicy } from './policy'
19
+ import { ENV_SERVICE, envOptions, kekOptions, SENTINEL_KEY } from './storage'
20
+ import { KekPolicy, KekSentinel, SecretName, UnavailableReason, UnlockState } from './types'
21
+
22
+ let cached: { kek: number[]; kekId: string; policy: KekPolicy } | null = null
23
+ let inFlight: Promise<UnlockState> | null = null
24
+ let state: UnlockState = { status: 'locked' }
25
+ let listeners: ((s: UnlockState) => void)[] = []
26
+
27
+ /** Latches once the user cancels or the device cannot authenticate, so we
28
+ * never re-prompt on our own initiative. Only an explicit UI act clears it. */
29
+ let autoUnlockSpent = false
30
+
31
+ function setState(next: UnlockState): UnlockState {
32
+ state = next
33
+ for (const fn of listeners) fn(next)
34
+ return next
35
+ }
36
+
37
+ export function getUnlockState(): UnlockState {
38
+ return state
39
+ }
40
+
41
+ export function subscribeUnlockState(fn: (s: UnlockState) => void): () => void {
42
+ listeners.push(fn)
43
+ return () => {
44
+ listeners = listeners.filter(l => l !== fn)
45
+ }
46
+ }
47
+
48
+ export function isUnlocked(): boolean {
49
+ return cached !== null
50
+ }
51
+
52
+ /** Internal to services/secrets. */
53
+ export function peekKek(): { kek: number[]; kekId: string } | null {
54
+ return cached ? { kek: cached.kek, kekId: cached.kekId } : null
55
+ }
56
+
57
+ /* ------------------------------- sentinel -------------------------------- */
58
+
59
+ export async function readSentinel(): Promise<KekSentinel | null> {
60
+ try {
61
+ const raw = await SecureStore.getItemAsync(SENTINEL_KEY, envOptions)
62
+ if (!raw) return null
63
+ const parsed = JSON.parse(raw) as KekSentinel
64
+ return parsed?.v === 1 && typeof parsed.kekId === 'string' ? parsed : null
65
+ } catch {
66
+ return null
67
+ }
68
+ }
69
+
70
+ async function writeSentinel(s: KekSentinel): Promise<void> {
71
+ await SecureStore.setItemAsync(SENTINEL_KEY, JSON.stringify(s), envOptions)
72
+ }
73
+
74
+ export async function recordSecretName(name: SecretName): Promise<void> {
75
+ const s = await readSentinel()
76
+ if (!s || s.names.includes(name)) return
77
+ await writeSentinel({ ...s, names: [...s.names, name] })
78
+ }
79
+
80
+ export async function forgetSecretName(name: SecretName): Promise<void> {
81
+ const s = await readSentinel()
82
+ if (!s || !s.names.includes(name)) return
83
+ await writeSentinel({ ...s, names: s.names.filter(n => n !== name) })
84
+ }
85
+
86
+ /* ----------------------------- error mapping ------------------------------ */
87
+
88
+ /**
89
+ * Neither platform gives us a usable numeric code through this module — iOS
90
+ * drops the OSStatus from its message and Android collapses distinct failures
91
+ * into shared strings — so this is string matching, and it is brittle by
92
+ * necessity. Re-check it whenever expo-secure-store is bumped.
93
+ *
94
+ * The default is deliberately benign. An unrecognised error becomes
95
+ * `cancelled`, which renders as a retry button; classifying an unknown as
96
+ * `unavailable` would show a dead-end "this device can't do this" screen for
97
+ * something as ordinary as the app being backgrounded mid-sheet.
98
+ */
99
+ export function classifyAuthError(err: unknown): UnlockState {
100
+ const msg = String((err as Error)?.message ?? err ?? '')
101
+ const unavailable = (reason: UnavailableReason): UnlockState => ({ status: 'unavailable', reason })
102
+
103
+ if (/cancel/i.test(msg)) return { status: 'cancelled' }
104
+ if (/lockout|too many attempts/i.test(msg)) return unavailable('lockout')
105
+ if (/no biometrics|not currently enrolled|no user authentication method|passcode/i.test(msg)) {
106
+ return unavailable('not-enrolled')
107
+ }
108
+ if (/no hardware|not available|unsupported/i.test(msg)) return unavailable('no-hardware')
109
+ if (/foreground|FragmentActivity/i.test(msg)) return unavailable('not-foregrounded')
110
+ return { status: 'cancelled' }
111
+ }
112
+
113
+ /* ------------------------------ provisioning ------------------------------ */
114
+
115
+ /**
116
+ * Mint a KEK for a device that has none. Returns it already cached — we never
117
+ * read back what we just wrote, because on an authenticated item that would be
118
+ * a second prompt.
119
+ */
120
+ export async function provisionKek(): Promise<UnlockState> {
121
+ const resolved = await resolveProvisioningPolicy()
122
+ const kek = generateKek()
123
+ const kekId = generateKekId()
124
+
125
+ // Delete-then-add, never blind-write: writing over an existing item takes
126
+ // iOS's update path, which prompts a second time on an ACL item.
127
+ await deleteBothKekItems()
128
+
129
+ try {
130
+ await SecureStore.setItemAsync(
131
+ resolved.keyName,
132
+ Utils.toHex(kek),
133
+ kekOptions(resolved.requireAuthentication)
134
+ )
135
+ } catch (err) {
136
+ return setState(classifyAuthError(err))
137
+ }
138
+
139
+ await writeSentinel({
140
+ v: 1,
141
+ kekId,
142
+ policy: resolved.policy,
143
+ provisionedAt: Date.now(),
144
+ names: []
145
+ })
146
+
147
+ cached = { kek, kekId, policy: resolved.policy }
148
+ return setState({ status: 'unlocked', kekId, policy: resolved.policy })
149
+ }
150
+
151
+ async function deleteBothKekItems(): Promise<void> {
152
+ // Deletion never prompts on either platform.
153
+ await SecureStore.deleteItemAsync(KEK_AUTH_KEY, kekOptions(true)).catch(() => {})
154
+ await SecureStore.deleteItemAsync(KEK_PLAIN_KEY, kekOptions(false)).catch(() => {})
155
+ }
156
+
157
+ /* --------------------------------- unlock --------------------------------- */
158
+
159
+ /**
160
+ * Release the KEK, prompting at most once per process.
161
+ *
162
+ * Never mints a key: if a sentinel exists and the KEK does not, the OS
163
+ * destroyed it (biometric re-enrolment, screen-lock removal, reinstall) and the
164
+ * honest answer is `lost`, not a silent fresh start that would strand the
165
+ * user's coins behind an envelope nobody can open.
166
+ */
167
+ export async function unlockKek(promptMessage?: string): Promise<UnlockState> {
168
+ if (cached) {
169
+ return setState({ status: 'unlocked', kekId: cached.kekId, policy: cached.policy })
170
+ }
171
+ // Single-flight: Android throws outright on a concurrent prompt.
172
+ if (inFlight) return inFlight
173
+
174
+ inFlight = doUnlock(promptMessage).finally(() => {
175
+ inFlight = null
176
+ })
177
+ return inFlight
178
+ }
179
+
180
+ /** Auto-unlock at most once per process. After a cancellation or an
181
+ * unavailable device we stop initiating, so the user is never trapped in a
182
+ * prompt loop — but the first cold-start unlock stays implicit, which is what
183
+ * keeps the existing UX (one sheet, no extra tap). */
184
+ export async function autoUnlockKek(promptMessage?: string): Promise<UnlockState> {
185
+ if (cached) return unlockKek(promptMessage)
186
+ if (autoUnlockSpent) return state
187
+ autoUnlockSpent = true
188
+ return unlockKek(promptMessage)
189
+ }
190
+
191
+ async function doUnlock(promptMessage?: string): Promise<UnlockState> {
192
+ const sentinel = await readSentinel()
193
+ // No sentinel: nothing was ever stored. Touch SecureStore at all here and a
194
+ // brand-new user would get a biometric sheet on the welcome screen.
195
+ if (!sentinel) return setState({ status: 'absent' })
196
+ if (sentinel.names.length === 0) return setState({ status: 'absent' })
197
+
198
+ setState({ status: 'unlocking' })
199
+
200
+ const resolved = policyFor(sentinel.policy)
201
+ let raw: string | null
202
+ try {
203
+ raw = await SecureStore.getItemAsync(
204
+ resolved.keyName,
205
+ kekOptions(resolved.requireAuthentication, promptMessage)
206
+ )
207
+ } catch (err) {
208
+ return setState(classifyAuthError(err))
209
+ }
210
+
211
+ // A sentinel with no key means the OS threw the key away. Both platforms
212
+ // report that as a plain null, which is why the sentinel has to exist.
213
+ if (raw === null) return setState({ status: 'lost' })
214
+
215
+ cached = { kek: Utils.toArray(raw, 'hex') as number[], kekId: sentinel.kekId, policy: sentinel.policy }
216
+
217
+ // A production build must not keep running on a KEK that a development
218
+ // build provisioned without OS enforcement.
219
+ if (await needsUpgrade(sentinel.policy)) {
220
+ const upgraded = await upgradeToBiometric(sentinel)
221
+ if (upgraded) return setState(upgraded)
222
+ }
223
+
224
+ return setState({ status: 'unlocked', kekId: sentinel.kekId, policy: cached.policy })
225
+ }
226
+
227
+ /**
228
+ * Re-wrap the same KEK value under an authenticated item. The envelope blobs
229
+ * are untouched because the KEK itself does not change.
230
+ */
231
+ export async function upgradeToBiometric(sentinel: KekSentinel): Promise<UnlockState | null> {
232
+ if (!cached) return null
233
+ try {
234
+ await SecureStore.deleteItemAsync(KEK_AUTH_KEY, kekOptions(true)).catch(() => {})
235
+ await SecureStore.setItemAsync(KEK_AUTH_KEY, Utils.toHex(cached.kek), kekOptions(true))
236
+ await writeSentinel({ ...sentinel, policy: 'biometric' })
237
+ await SecureStore.deleteItemAsync(KEK_PLAIN_KEY, kekOptions(false)).catch(() => {})
238
+ cached = { ...cached, policy: 'biometric' }
239
+ return { status: 'unlocked', kekId: cached.kekId, policy: 'biometric' }
240
+ } 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.
243
+ return null
244
+ }
245
+ }
246
+
247
+ /* -------------------------------- teardown -------------------------------- */
248
+
249
+ /** Prompt-free, and works while locked or lost — otherwise a user whose
250
+ * biometrics changed could never log out. */
251
+ export async function destroyKek(): Promise<void> {
252
+ cached = null
253
+ autoUnlockSpent = false
254
+ await deleteBothKekItems()
255
+ await SecureStore.deleteItemAsync(SENTINEL_KEY, envOptions).catch(() => {})
256
+ setState({ status: 'absent' })
257
+ }
258
+
259
+ /** Drop the in-memory copy without touching storage (e.g. explicit re-lock). */
260
+ export function lockKek(): void {
261
+ cached = null
262
+ autoUnlockSpent = false
263
+ setState({ status: 'locked' })
264
+ }
265
+
266
+ export function __resetForTests(): void {
267
+ cached = null
268
+ inFlight = null
269
+ listeners = []
270
+ autoUnlockSpent = false
271
+ state = { status: 'locked' }
272
+ }
273
+
274
+ export { ENV_SERVICE }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * One-time migration of the plaintext-in-SecureStore wallet keys into the
3
+ * envelope.
4
+ *
5
+ * Ordering is the whole design here. The only irreversible step is deleting the
6
+ * legacy plaintext, and it happens strictly after the ciphertexts have been
7
+ * written AND read back AND decrypted successfully. There is no window in which
8
+ * the plaintext is gone and the envelope is unproven, so a crash or a denied
9
+ * prompt at any point leaves the user on the old scheme rather than bricked.
10
+ */
11
+ import AsyncStorage from '@react-native-async-storage/async-storage'
12
+ import * as SecureStore from 'expo-secure-store'
13
+ import { openSecret, sealSecret } from './envelope'
14
+ import { destroyKek, peekKek, provisionKek, readSentinel, recordSecretName } from './kek'
15
+ import { envKey, envOptions } from './storage'
16
+ import { EnvelopeBlob, SECRET_NAMES, SecretName } from './types'
17
+
18
+ /** Keys written by the pre-envelope LocalStorageProvider. */
19
+ const LEGACY_KEYS: Record<SecretName, string> = {
20
+ mnemonic: 'mnemonic',
21
+ recoveredKey: 'recoveredKey'
22
+ }
23
+ /** Had no consumers anywhere in the app: swept, never migrated. */
24
+ const LEGACY_PASSWORD_KEY = 'password'
25
+ const LEGACY_HAS_KEYS_FLAG = 'hasWalletKeys'
26
+
27
+ const FAILURE_COUNT_KEY = 'secrets.migration.failures'
28
+ const MAX_ATTEMPTS = 3
29
+
30
+ export type MigrationResult =
31
+ | { outcome: 'not-needed' }
32
+ | { outcome: 'migrated'; names: SecretName[] }
33
+ | { outcome: 'failed'; stage: string; retryable: boolean }
34
+
35
+ /** Reads a legacy plaintext item. Prompt-free — these were always written
36
+ * unauthenticated. Kept exported so the provider can still serve a session
37
+ * whose migration failed, instead of showing the user an empty wallet. */
38
+ export async function readLegacySecret(name: SecretName): Promise<string | null> {
39
+ try {
40
+ return await SecureStore.getItemAsync(LEGACY_KEYS[name])
41
+ } catch {
42
+ return null
43
+ }
44
+ }
45
+
46
+ export async function hasLegacySecrets(): Promise<boolean> {
47
+ for (const name of SECRET_NAMES) {
48
+ if (await readLegacySecret(name)) return true
49
+ }
50
+ return false
51
+ }
52
+
53
+ /**
54
+ * Delete the legacy items and verify they are actually gone.
55
+ *
56
+ * iOS's delete discards every OSStatus and never throws, so "it returned" is
57
+ * not evidence. If a legacy plaintext survived here the whole migration would
58
+ * be cosmetic — the old unauthenticated item shadows the new one on read.
59
+ */
60
+ export async function sweepLegacyKeys(): Promise<boolean> {
61
+ const keys = [...Object.values(LEGACY_KEYS), LEGACY_PASSWORD_KEY]
62
+
63
+ for (let attempt = 0; attempt < 2; attempt++) {
64
+ for (const key of keys) {
65
+ await SecureStore.deleteItemAsync(key).catch(() => {})
66
+ }
67
+ let remaining = 0
68
+ for (const key of keys) {
69
+ try {
70
+ if ((await SecureStore.getItemAsync(key)) !== null) remaining++
71
+ } catch {
72
+ /* unreadable is as good as gone */
73
+ }
74
+ }
75
+ if (remaining === 0) {
76
+ await AsyncStorage.removeItem(LEGACY_HAS_KEYS_FLAG).catch(() => {})
77
+ return true
78
+ }
79
+ }
80
+ console.warn('[secrets] legacy plaintext survived deletion')
81
+ return false
82
+ }
83
+
84
+ async function rollback(written: SecretName[]): Promise<void> {
85
+ for (const name of written) {
86
+ await SecureStore.deleteItemAsync(envKey(name), envOptions).catch(() => {})
87
+ }
88
+ // Removes the KEK and the sentinel; the legacy plaintext is untouched.
89
+ await destroyKek()
90
+ }
91
+
92
+ async function bumpFailures(): Promise<number> {
93
+ const raw = await AsyncStorage.getItem(FAILURE_COUNT_KEY)
94
+ const next = (Number(raw) || 0) + 1
95
+ await AsyncStorage.setItem(FAILURE_COUNT_KEY, String(next))
96
+ return next
97
+ }
98
+
99
+ export async function migrationAttemptsExhausted(): Promise<boolean> {
100
+ const raw = await AsyncStorage.getItem(FAILURE_COUNT_KEY)
101
+ return (Number(raw) || 0) >= MAX_ATTEMPTS
102
+ }
103
+
104
+ export async function migrateLegacySecrets(): Promise<MigrationResult> {
105
+ // Step 0 — idempotence. A committed sentinel means we already migrated;
106
+ // sweeping here is what makes a crash between commit and delete harmless.
107
+ const existing = await readSentinel()
108
+ if (existing && existing.names.length > 0) {
109
+ await sweepLegacyKeys()
110
+ return { outcome: 'not-needed' }
111
+ }
112
+
113
+ // Step 1 — read the legacy plaintext. Zero prompts: these are unauthenticated.
114
+ const legacy: Partial<Record<SecretName, string>> = {}
115
+ for (const name of SECRET_NAMES) {
116
+ const value = await readLegacySecret(name)
117
+ if (value) legacy[name] = value
118
+ }
119
+ const names = Object.keys(legacy) as SecretName[]
120
+
121
+ // Step 2 — nothing to migrate. Provisioning happens naturally at onboarding.
122
+ if (names.length === 0) {
123
+ await sweepLegacyKeys()
124
+ return { outcome: 'not-needed' }
125
+ }
126
+
127
+ if (await migrationAttemptsExhausted()) {
128
+ return { outcome: 'failed', stage: 'attempts-exhausted', retryable: false }
129
+ }
130
+
131
+ // Step 3 — mint the KEK. Costs one prompt on Android, none on iOS.
132
+ const provisioned = await provisionKek()
133
+ if (provisioned.status !== 'unlocked') {
134
+ await bumpFailures()
135
+ return {
136
+ outcome: 'failed',
137
+ stage: 'provision',
138
+ retryable: provisioned.status === 'cancelled'
139
+ }
140
+ }
141
+ const held = peekKek()
142
+ if (!held) {
143
+ await bumpFailures()
144
+ return { outcome: 'failed', stage: 'provision', retryable: true }
145
+ }
146
+
147
+ // Step 4 — seal and write.
148
+ const written: SecretName[] = []
149
+ try {
150
+ for (const name of names) {
151
+ const blob = sealSecret(held.kek, held.kekId, name, legacy[name] as string)
152
+ await SecureStore.setItemAsync(envKey(name), JSON.stringify(blob), envOptions)
153
+ written.push(name)
154
+ }
155
+ } catch (err) {
156
+ console.warn('[secrets] migration write failed', (err as Error)?.message)
157
+ await rollback(written)
158
+ await bumpFailures()
159
+ return { outcome: 'failed', stage: 'write', retryable: true }
160
+ }
161
+
162
+ // Step 5 — prove the envelope before trusting it.
163
+ try {
164
+ for (const name of names) {
165
+ const raw = await SecureStore.getItemAsync(envKey(name), envOptions)
166
+ if (!raw) throw new Error(`blob missing for ${name}`)
167
+ const opened = openSecret(held.kek, name, JSON.parse(raw) as EnvelopeBlob)
168
+ if (opened !== legacy[name]) throw new Error(`round-trip mismatch for ${name}`)
169
+ }
170
+ } catch (err) {
171
+ console.warn('[secrets] migration verification failed', (err as Error)?.message)
172
+ await rollback(written)
173
+ await bumpFailures()
174
+ return { outcome: 'failed', stage: 'verify', retryable: true }
175
+ }
176
+
177
+ // Step 6 — commit. A sentinel only counts once it names a secret, so this is
178
+ // the point of no return, and it comes after verification.
179
+ for (const name of names) {
180
+ await recordSecretName(name)
181
+ }
182
+
183
+ // Step 7 — the irreversible bit.
184
+ await sweepLegacyKeys()
185
+ await AsyncStorage.removeItem(FAILURE_COUNT_KEY).catch(() => {})
186
+
187
+ return { outcome: 'migrated', names }
188
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Which protection class the KEK gets on this device and this build.
3
+ *
4
+ * expo-local-authentication is used here as a *capability probe only*. It must
5
+ * never be used to gate access to a secret: its authenticateAsync builds a
6
+ * throwaway LAContext that is never handed to Security.framework, and on
7
+ * Android it authenticates with no CryptoObject, so it unlocks no Keystore key.
8
+ * A passed LocalAuthentication check proves nothing about the enclave. The only
9
+ * ceremony that counts is the one SecureStore itself triggers when reading an
10
+ * item written with requireAuthentication.
11
+ */
12
+ import * as LocalAuthentication from 'expo-local-authentication'
13
+ import { KekPolicy } from './types'
14
+
15
+ /** ALWAYS written with requireAuthentication: true. */
16
+ export const KEK_AUTH_KEY = 'kekAuthV1'
17
+ /** ALWAYS written with requireAuthentication: false. */
18
+ export const KEK_PLAIN_KEY = 'kekPlainV1'
19
+
20
+ export interface ResolvedPolicy {
21
+ policy: KekPolicy
22
+ keyName: string
23
+ requireAuthentication: boolean
24
+ /** Show the "no biometric protection on this device" disclosure. */
25
+ disclose: boolean
26
+ }
27
+
28
+ const BIOMETRIC: ResolvedPolicy = {
29
+ policy: 'biometric',
30
+ keyName: KEK_AUTH_KEY,
31
+ requireAuthentication: true,
32
+ disclose: false
33
+ }
34
+
35
+ const DEGRADED: ResolvedPolicy = {
36
+ policy: 'degraded',
37
+ keyName: KEK_PLAIN_KEY,
38
+ requireAuthentication: false,
39
+ disclose: true
40
+ }
41
+
42
+ const DEV_PLAIN: ResolvedPolicy = {
43
+ policy: 'dev-plain',
44
+ keyName: KEK_PLAIN_KEY,
45
+ requireAuthentication: false,
46
+ disclose: true
47
+ }
48
+
49
+ export function policyFor(policy: KekPolicy): ResolvedPolicy {
50
+ switch (policy) {
51
+ case 'biometric':
52
+ return BIOMETRIC
53
+ case 'degraded':
54
+ return DEGRADED
55
+ case 'dev-plain':
56
+ return DEV_PLAIN
57
+ }
58
+ }
59
+
60
+ /**
61
+ * True when the device can actually satisfy an OS biometric ceremony.
62
+ *
63
+ * getEnrolledLevelAsync is the only correct probe here. hasHardwareAsync
64
+ * returns true on an unenrolled simulator, and isEnrolledAsync returns true
65
+ * under biometric lockout on iOS and only checks the *weak* class on Android —
66
+ * while the Keystore key we mint requires BIOMETRIC_STRONG, so a weak-only
67
+ * device would hard-fail provisioning.
68
+ */
69
+ export async function hasStrongBiometrics(): Promise<boolean> {
70
+ try {
71
+ const level = await LocalAuthentication.getEnrolledLevelAsync()
72
+ return level === LocalAuthentication.SecurityLevel.BIOMETRIC_STRONG
73
+ } catch {
74
+ return false
75
+ }
76
+ }
77
+
78
+ /** Copy helper: "Face ID" vs "Touch ID" vs "fingerprint". */
79
+ export async function biometricKind(): Promise<'face' | 'fingerprint' | 'iris' | 'unknown'> {
80
+ try {
81
+ const types = await LocalAuthentication.supportedAuthenticationTypesAsync()
82
+ if (types.includes(LocalAuthentication.AuthenticationType.FACIAL_RECOGNITION)) return 'face'
83
+ if (types.includes(LocalAuthentication.AuthenticationType.FINGERPRINT)) return 'fingerprint'
84
+ if (types.includes(LocalAuthentication.AuthenticationType.IRIS)) return 'iris'
85
+ return 'unknown'
86
+ } catch {
87
+ return 'unknown'
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Policy for minting a NEW KEK.
93
+ *
94
+ * Production with strong biometrics is the only path that yields `biometric`;
95
+ * everything else degrades, and degradation is always disclosed. Development
96
+ * builds without biometrics get `dev-plain` so simulators and CI still work —
97
+ * that branch lives behind __DEV__, which Metro folds out of release bundles,
98
+ * so it is not merely unreachable in production, it is not present.
99
+ */
100
+ export async function resolveProvisioningPolicy(): Promise<ResolvedPolicy> {
101
+ const strong = await hasStrongBiometrics()
102
+ if (strong) return BIOMETRIC
103
+ return __DEV__ ? DEV_PLAIN : DEGRADED
104
+ }
105
+
106
+ /**
107
+ * Whether an EXISTING install's recorded policy is still acceptable.
108
+ *
109
+ * This closes a hole that needs no attacker: a dev build and a release build
110
+ * share a bundle id, hence one keychain. A developer or internal tester who
111
+ * runs a dev build first legitimately provisions `dev-plain`, and the release
112
+ * build installed over it would otherwise read that unauthenticated KEK with
113
+ * no prompt at all. In production, any non-biometric policy on a device that
114
+ * *can* do biometrics must be re-wrapped before the KEK is honoured.
115
+ */
116
+ export async function needsUpgrade(current: KekPolicy): Promise<boolean> {
117
+ if (current === 'biometric') return false
118
+ if (__DEV__) return false
119
+ return hasStrongBiometrics()
120
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * SecureStore placement for the envelope scheme.
3
+ *
4
+ * Two separate keychain services, deliberately:
5
+ *
6
+ * - `bsvb.kek.v1` holds only the KEK. On Android this bounds the blast
7
+ * radius of the module's own invalidation cleanup, which
8
+ * wipes entries under a keychainService.
9
+ * - `bsvb.secrets.v1` holds the inert ciphertexts and the sentinel, always
10
+ * unauthenticated so reading them never shows a prompt.
11
+ *
12
+ * Never change these constants. Changing keychainService orphans existing
13
+ * items, and changing keychainAccessible on an existing item is a silent no-op
14
+ * on iOS — the update path writes only the value.
15
+ */
16
+ import * as SecureStore from 'expo-secure-store'
17
+
18
+ export const KEK_SERVICE = 'bsvb.kek.v1'
19
+ export const ENV_SERVICE = 'bsvb.secrets.v1'
20
+
21
+ export const SENTINEL_KEY = 'secretsSentinelV1'
22
+
23
+ export const envKey = (name: string) => `envV1.${name}`
24
+
25
+ /**
26
+ * Options for the KEK item.
27
+ *
28
+ * WHEN_UNLOCKED_THIS_DEVICE_ONLY rather than AFTER_FIRST_UNLOCK: a biometric
29
+ * sheet cannot run on a locked device anyway, so the weaker class buys nothing.
30
+ * ALWAYS* would throw when combined with an access-control flag.
31
+ */
32
+ export function kekOptions(
33
+ requireAuthentication: boolean,
34
+ authenticationPrompt?: string
35
+ ): SecureStore.SecureStoreOptions {
36
+ return {
37
+ keychainService: KEK_SERVICE,
38
+ requireAuthentication,
39
+ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
40
+ ...(authenticationPrompt ? { authenticationPrompt } : {})
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Options for ciphertexts and the sentinel. requireAuthentication is false and
46
+ * must stay false — these are useless without the KEK, and making them
47
+ * authenticated would cost a prompt per read, which is the whole thing we are
48
+ * avoiding.
49
+ */
50
+ export const envOptions: SecureStore.SecureStoreOptions = {
51
+ keychainService: ENV_SERVICE,
52
+ requireAuthentication: false,
53
+ keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY
54
+ }