@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,125 @@
1
+ /**
2
+ * Read/write wallet secrets through the envelope.
3
+ *
4
+ * Every operation here except the first unlock is prompt-free, because the
5
+ * ciphertexts are unauthenticated items and the KEK is already in memory.
6
+ *
7
+ * SECURITY: never log values passed through these functions.
8
+ */
9
+ import * as SecureStore from 'expo-secure-store'
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'
20
+ import { envKey, envOptions } from './storage'
21
+ import { EnvelopeBlob, EnvelopeError, SECRET_NAMES, SecretName } from './types'
22
+
23
+ /**
24
+ * Is there a wrapped secret of this name? Prompt-free and works while locked.
25
+ *
26
+ * Note this is not strictly side-effect-free on Android: reading a blob whose
27
+ * unauthenticated Keystore alias has gone missing makes the native module drop
28
+ * the stale ciphertext. Harmless — it was already unopenable — but don't call
29
+ * it speculatively in a hot path.
30
+ */
31
+ export async function hasSecret(name: SecretName): Promise<boolean> {
32
+ try {
33
+ return (await SecureStore.getItemAsync(envKey(name), envOptions)) !== null
34
+ } catch {
35
+ return false
36
+ }
37
+ }
38
+
39
+ export async function hasAnySecret(): Promise<boolean> {
40
+ for (const name of SECRET_NAMES) {
41
+ if (await hasSecret(name)) return true
42
+ }
43
+ return false
44
+ }
45
+
46
+ /**
47
+ * Returns null when locked. It deliberately does NOT unlock implicitly — the
48
+ * one automatic unlock per process is initiated from the wallet-build effect,
49
+ * where a prompt is expected, not from whichever screen happens to read a
50
+ * secret first.
51
+ */
52
+ export async function getSecret(name: SecretName): Promise<string | null> {
53
+ const held = peekKek()
54
+ if (!held) return null
55
+
56
+ let raw: string | null
57
+ try {
58
+ raw = await SecureStore.getItemAsync(envKey(name), envOptions)
59
+ } catch (err) {
60
+ console.warn('[secrets] read failed', name, (err as Error)?.message)
61
+ return null
62
+ }
63
+ if (!raw) return null
64
+
65
+ try {
66
+ const blob = JSON.parse(raw) as EnvelopeBlob
67
+ assertKekId(blob, held.kekId)
68
+ return openSecret(held.kek, name, blob)
69
+ } catch (err) {
70
+ const code = err instanceof EnvelopeError ? err.code : 'corrupt'
71
+ console.warn('[secrets] could not open envelope', name, code)
72
+ return null
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Seal and store. Provisions a KEK on first use, which is the only moment a
78
+ * write can prompt (and only on Android, where minting an auth-bound key
79
+ * requires a ceremony).
80
+ */
81
+ export async function putSecret(name: SecretName, value: string): Promise<boolean> {
82
+ let held = peekKek()
83
+
84
+ if (!held) {
85
+ const sentinel = await readSentinel()
86
+ const result = sentinel ? await unlockKek() : await provisionKek()
87
+ if (result.status !== 'unlocked') return false
88
+ held = peekKek()
89
+ if (!held) return false
90
+ }
91
+
92
+ try {
93
+ const blob = sealSecret(held.kek, held.kekId, name, value)
94
+ await SecureStore.setItemAsync(envKey(name), JSON.stringify(blob), envOptions)
95
+ await recordSecretName(name)
96
+ return true
97
+ } catch (err) {
98
+ console.warn('[secrets] write failed', name, (err as Error)?.message)
99
+ return false
100
+ }
101
+ }
102
+
103
+ /** Prompt-free, and works while locked or lost: deleting ciphertext needs no
104
+ * key. This is what makes logout possible for a user whose biometrics changed. */
105
+ export async function deleteSecret(name: SecretName): Promise<void> {
106
+ try {
107
+ await SecureStore.deleteItemAsync(envKey(name), envOptions)
108
+ await forgetSecretName(name)
109
+ } catch (err) {
110
+ console.warn('[secrets] delete failed', name, (err as Error)?.message)
111
+ }
112
+ }
113
+
114
+ /** Removes every wrapped secret and the KEK itself, so the next launch reads
115
+ * as a clean install rather than prompting for a wallet that no longer exists. */
116
+ export async function deleteAllSecrets(): Promise<void> {
117
+ for (const name of SECRET_NAMES) {
118
+ try {
119
+ await SecureStore.deleteItemAsync(envKey(name), envOptions)
120
+ } catch {
121
+ /* best effort — destroyKek below is what matters */
122
+ }
123
+ }
124
+ await destroyKek()
125
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Wallet-secret domain types — shared by the envelope crypto, the KEK holder,
3
+ * the store and the migration. No React, no I/O.
4
+ *
5
+ * Threat model in one line: the mnemonic must be undecryptable without a live
6
+ * OS biometric ceremony, so that patching JavaScript buys an attacker nothing.
7
+ */
8
+
9
+ /** The secrets that are wrapped under the KEK. `password` is deliberately
10
+ * absent — it had no consumers and is swept, not migrated. */
11
+ export type SecretName = 'mnemonic' | 'recoveredKey'
12
+
13
+ export const SECRET_NAMES: SecretName[] = ['mnemonic', 'recoveredKey']
14
+
15
+ /**
16
+ * A wrapped secret. Mirrors the vault's SealedBlob conventions
17
+ * (services/vault/types.ts): version-as-literal, all binary as hex.
18
+ *
19
+ * The blob is stored unauthenticated and is inert on its own — opening it
20
+ * requires the KEK, which only the Secure Enclave / Keystore can release.
21
+ */
22
+ export interface EnvelopeBlob {
23
+ v: 1
24
+ /** hex(8B) — which KEK sealed this, so a stale blob fails loudly. */
25
+ kekId: string
26
+ /** hex(32B) — per-blob HKDF salt. */
27
+ salt: string
28
+ /** AES-256-GCM ciphertext (SymmetricKey wire format: iv||ct||tag), hex. */
29
+ c: string
30
+ }
31
+
32
+ /**
33
+ * How the KEK is protected on this install.
34
+ * - `biometric` — SecureStore item with requireAuthentication: OS-enforced.
35
+ * - `degraded` — production device with no strong biometrics; keystore-only.
36
+ * - `dev-plain` — development builds without biometrics. Never valid in prod.
37
+ */
38
+ export type KekPolicy = 'biometric' | 'degraded' | 'dev-plain'
39
+
40
+ /**
41
+ * Non-secret marker recording that an envelope exists.
42
+ *
43
+ * Its only jobs are to distinguish "key destroyed by the OS" from "no wallet
44
+ * here" and to select the KEK key name. It is NOT a security control: no
45
+ * sentinel value can cause an authenticated item to be read without auth.
46
+ *
47
+ * Stored in SecureStore (unauthenticated), NOT AsyncStorage, so its lifetime
48
+ * matches the blobs' on both platforms — an iOS reinstall keeps keychain items
49
+ * but wipes AsyncStorage, which would otherwise desynchronise the two.
50
+ */
51
+ export interface KekSentinel {
52
+ v: 1
53
+ kekId: string
54
+ policy: KekPolicy
55
+ provisionedAt: number
56
+ names: SecretName[]
57
+ }
58
+
59
+ export type UnavailableReason = 'no-hardware' | 'not-enrolled' | 'lockout' | 'not-foregrounded'
60
+
61
+ export type UnlockState =
62
+ /** No sentinel: nothing has ever been stored on this device. */
63
+ | { status: 'absent' }
64
+ /** Sentinel present, KEK not yet released this process. */
65
+ | { status: 'locked' }
66
+ | { status: 'unlocking' }
67
+ | { status: 'unlocked'; kekId: string; policy: KekPolicy }
68
+ /** User dismissed the sheet. Retryable, nothing was touched. */
69
+ | { status: 'cancelled' }
70
+ | { status: 'unavailable'; reason: UnavailableReason }
71
+ /** Sentinel present but the KEK is gone — the OS destroyed it. Unrecoverable
72
+ * on-device; the user must restore from their recovery phrase. */
73
+ | { status: 'lost' }
74
+
75
+ export type EnvelopeErrorCode = 'bad-version' | 'kek-mismatch' | 'corrupt'
76
+
77
+ export class EnvelopeError extends Error {
78
+ constructor(
79
+ public readonly code: EnvelopeErrorCode,
80
+ message: string
81
+ ) {
82
+ super(message)
83
+ this.name = 'EnvelopeError'
84
+ }
85
+ }
@@ -0,0 +1,101 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage'
2
+ import { FALLBACK_USD_FX, FRANKFURTER_RATES_URL } from '../displayCurrencies'
3
+
4
+ export const FX_CACHE_KEY = 'cached_usd_fx_rates'
5
+ export const FX_TTL_MS = 24 * 60 * 60 * 1000
6
+ export const FX_FETCH_TIMEOUT_MS = 4000
7
+
8
+ export type UsdFxCache = { rates: Record<string, number>; timestamp: string }
9
+
10
+ export type FxStorage = {
11
+ getItem(key: string): Promise<string | null>
12
+ setItem(key: string, value: string): Promise<void>
13
+ }
14
+
15
+ const snapshotRates = (): Record<string, number> => ({ USD: 1, ...FALLBACK_USD_FX })
16
+
17
+ export function parseFrankfurterResponse(json: unknown): Record<string, number> | null {
18
+ if (!Array.isArray(json)) return null
19
+ const rates: Record<string, number> = {}
20
+ for (const row of json) {
21
+ if (!row || typeof row !== 'object') continue
22
+ const quote = (row as { quote?: unknown }).quote
23
+ const rate = Number((row as { rate?: unknown }).rate)
24
+ if (typeof quote !== 'string' || quote.length === 0) continue
25
+ if (!Number.isFinite(rate) || rate <= 0) continue
26
+ rates[quote] = rate
27
+ }
28
+ return Object.keys(rates).length > 0 ? rates : null
29
+ }
30
+
31
+ export function fxCacheIsFresh(timestamp: string, now: number): boolean {
32
+ const t = Date.parse(timestamp)
33
+ if (!Number.isFinite(t)) return false
34
+ return now - t < FX_TTL_MS
35
+ }
36
+
37
+ export function resolveUsdFxRates(
38
+ cached: UsdFxCache | null,
39
+ now: number
40
+ ): { rates: Record<string, number>; shouldFetch: boolean } {
41
+ const fallback = snapshotRates()
42
+ if (!cached?.rates) return { rates: fallback, shouldFetch: true }
43
+ const rates = { ...fallback, ...cached.rates, USD: 1 }
44
+ const shouldFetch = !cached.timestamp || !fxCacheIsFresh(cached.timestamp, now)
45
+ return { rates, shouldFetch }
46
+ }
47
+
48
+ function readCache(raw: string | null): UsdFxCache | null {
49
+ if (!raw) return null
50
+ try {
51
+ const parsed = JSON.parse(raw) as { rates?: unknown; timestamp?: unknown }
52
+ if (!parsed || typeof parsed !== 'object' || !parsed.rates || typeof parsed.rates !== 'object') {
53
+ return null
54
+ }
55
+ const rates: Record<string, number> = {}
56
+ for (const [code, value] of Object.entries(parsed.rates as Record<string, unknown>)) {
57
+ const n = Number(value)
58
+ if (Number.isFinite(n) && n > 0) rates[code] = n
59
+ }
60
+ if (Object.keys(rates).length === 0) return null
61
+ return { rates, timestamp: typeof parsed.timestamp === 'string' ? parsed.timestamp : '' }
62
+ } catch {
63
+ return null
64
+ }
65
+ }
66
+
67
+ export async function loadUsdFxRates(
68
+ deps: {
69
+ storage?: FxStorage
70
+ fetchImpl?: typeof fetch
71
+ now?: number
72
+ } = {}
73
+ ): Promise<Record<string, number>> {
74
+ const storage = deps.storage ?? AsyncStorage
75
+ const fetchImpl = deps.fetchImpl ?? fetch
76
+ const now = deps.now ?? Date.now()
77
+
78
+ const cached = readCache(await storage.getItem(FX_CACHE_KEY))
79
+ const { rates, shouldFetch } = resolveUsdFxRates(cached, now)
80
+ if (!shouldFetch) return rates
81
+
82
+ const controller = new AbortController()
83
+ const timeout = setTimeout(() => controller.abort(), FX_FETCH_TIMEOUT_MS)
84
+ try {
85
+ const res = await fetchImpl(FRANKFURTER_RATES_URL, { signal: controller.signal })
86
+ if (!res.ok) return rates
87
+ const parsed = parseFrankfurterResponse(await res.json())
88
+ if (!parsed) return rates
89
+ const next = { ...rates, ...parsed, USD: 1 }
90
+ await storage.setItem(
91
+ FX_CACHE_KEY,
92
+ JSON.stringify({ rates: parsed, timestamp: new Date(now).toISOString() })
93
+ )
94
+ return next
95
+ } catch (error) {
96
+ console.error('Error fetching USD FX rates from Frankfurter:', error)
97
+ return rates
98
+ } finally {
99
+ clearTimeout(timeout)
100
+ }
101
+ }
@@ -0,0 +1,312 @@
1
+ /**
2
+ * VaultKeyService — enrollment, recovery, and teardown of the vault key.
3
+ *
4
+ * The vault key V is derived from the SAME mnemonic as the main wallet,
5
+ * domain-separated by a non-empty vault passphrase (BIP39 toSeed). The user
6
+ * therefore backs up ONE phrase, not two. See vaultDerivation.ts.
7
+ *
8
+ * The YubiKey is now an UNWRAP ORACLE, not a signing device: its PIV slot
9
+ * 0x82 holds a P-256 key used only for on-token ECDH (see sealing.ts).
10
+ * Enrollment's job is to derive the 64-byte vault seed, seal it to that
11
+ * card's public key, and store the result — a SealedBlob plus a bare
12
+ * `nextKeyIndex` counter (vaultStore's v4 meta). Nothing about the vault is
13
+ * ever public at rest: there is no xpub, no r1PublicKey, nothing that lets
14
+ * anyone reach a vault address without either the physical card or the
15
+ * mnemonic + passphrase.
16
+ *
17
+ * Because deposit addresses are BIP32 children of the PRIVATE vault HD node
18
+ * — there is no public xpub to derive them from anymore — a tap is now
19
+ * needed to hand out a fresh deposit address too. Deposits and withdrawals
20
+ * both go through the same unseal; neither is free of the YubiKey. (An
21
+ * earlier design cached 64 key hashes ahead of time so deposits never
22
+ * touched the card; that cache and its refill ceremony are gone along with
23
+ * the xpub that made it possible.)
24
+ *
25
+ * Recovery paths, and there are exactly two:
26
+ * 1. YubiKey unseal (the ceremony's on-token ECDH) — recovers the seed
27
+ * directly, nothing to type
28
+ * 2. main mnemonic + passphrase — deriveVaultSeed/deriveVaultHD, offline
29
+ * There is no third path.
30
+ *
31
+ * SECURITY: never log V, the seed, the mnemonic, or the passphrase.
32
+ */
33
+ import { HD } from '@bsv/sdk'
34
+ import { getVaultDriver } from './driver'
35
+ import { withKeySession } from './session'
36
+ import { vaultStore, VaultMetaV4 } from './vaultStore'
37
+ import { VaultError, SealedBlob } from './types'
38
+ import { deriveVaultSeed, deriveVaultHD, randomDepositStartIndex } from './vaultDerivation'
39
+ import { checkVaultPassphrase } from './vaultPassphrase'
40
+ import { sealVaultKey } from './sealing'
41
+
42
+ /** An enrollment that has touched the key but not yet disk. */
43
+ export interface PendingEnrollment {
44
+ meta: VaultMetaV4
45
+ seal: SealedBlob
46
+ }
47
+
48
+ export const VAULT_SLOT = 0x82
49
+ const DEFAULT_PIV_PIN = '123456'
50
+
51
+ export async function enrollVault(args: {
52
+ nickname: string
53
+ /** The MAIN wallet mnemonic. Wallets restored from backup shares do not have
54
+ * one and cannot enroll — callers must gate on this before calling. */
55
+ mnemonic: string
56
+ /** Non-empty vault passphrase. Must pass checkVaultPassphrase. */
57
+ passphrase: string
58
+ /**
59
+ * Enroll against the key ALREADY in the PIV slot instead of refusing it.
60
+ *
61
+ * This is how one YubiKey serves the same vault on several devices. The slot
62
+ * key is the ECDH unwrap oracle (see this file's header), i.e. the wrap
63
+ * TARGET a seal is built against — so adopting it seals THIS device's own
64
+ * copy of the vault seed to the card the user already carries, and the one
65
+ * physical tap then opens either device's blob.
66
+ *
67
+ * Generating instead is the destructive move: it would overwrite the slot's
68
+ * private key and strand the FIRST device's seal, which was wrapped to the
69
+ * key being replaced — that device would be left with a blob no tap can
70
+ * open, recoverable only via mnemonic + passphrase. Adoption generates
71
+ * nothing.
72
+ *
73
+ * The seed is re-derived here, never copied between devices, so both reach
74
+ * the SAME vault key the same two ways: the physical card (its ECDH unwraps
75
+ * whichever seal that device wrote) or the mnemonic + passphrase
76
+ * (deriveVaultSeed, offline). Every output the first device created stays
77
+ * spendable.
78
+ *
79
+ * Only ever set from an explicit user choice: 0x82 is a *retired* PIV slot,
80
+ * so the key sitting there may belong to something else entirely (an
81
+ * age-plugin-yubikey identity, say), and adopting it silently would quietly
82
+ * couple that key to the vault. An empty slot with this set generates
83
+ * normally — the flag permits adoption, it does not require it.
84
+ */
85
+ adoptExisting?: boolean
86
+ onPhase: (p: 'connecting' | 'pin-check' | 'generating' | 'adopting' | 'done') => void
87
+ getPin: () => Promise<string>
88
+ /** Called when the key still has the factory-default PIV PIN; must return a
89
+ * new PIN the user chose. If omitted, enrollment proceeds on the default PIN
90
+ * (dev/test convenience). */
91
+ requestPinChange?: (retries: number) => Promise<{ oldPin: string; newPin: string }>
92
+ }): Promise<{ pending: PendingEnrollment }> {
93
+ const driver = getVaultDriver()
94
+ if (!driver) throw new VaultError('driver-unavailable')
95
+
96
+ // Validate the passphrase BEFORE any key contact, so a rejected passphrase
97
+ // never costs the user an NFC tap. An empty one would make V identical to
98
+ // the main wallet's master key.
99
+ const policy = checkVaultPassphrase(args.passphrase)
100
+ if (!policy.ok) throw new VaultError('bad-passphrase', policy.reason)
101
+
102
+ // ── ALL user input up front, BEFORE any key contact ──
103
+ // On NFC the scan sheet is a modal that covers the app, so every prompt (the
104
+ // PIN, and a replacement PIN if the key is on the factory default) must be
105
+ // gathered before the tap; the whole enrollment then runs in one tap.
106
+ args.onPhase('pin-check')
107
+ const pin0 = await args.getPin()
108
+ let pin = pin0
109
+ let pinChange: { oldPin: string; newPin: string } | null = null
110
+ if (pin0 === DEFAULT_PIV_PIN && args.requestPinChange) {
111
+ // Factory-default detection is exactly "the PIN the user entered is the
112
+ // default" — no side probe against '123456' (fix #5).
113
+ pinChange = await args.requestPinChange(3)
114
+ pin = pinChange.newPin
115
+ }
116
+
117
+ // ── Token phase: one session / one NFC tap ──
118
+ const { info, publicKey, adopted } = await withKeySession(
119
+ driver,
120
+ async () => {
121
+ const info = await driver.getKeyInfo()
122
+ // A blocked PIN can't be enrolled — surface it before burning anything.
123
+ if (info.pinRetries === 0) throw new VaultError('pin-locked', 'PIN is blocked')
124
+ // Never silently overwrite an occupied slot: generating into a used PIV
125
+ // slot destroys the existing key, and retired slots 82-95 are what
126
+ // age-plugin-yubikey uses. Refuse and let the user decide — the wizard
127
+ // turns this refusal into the adopt-or-cancel choice that comes back as
128
+ // `adoptExisting`.
129
+ const occupant = await driver.readVaultPublicKey(VAULT_SLOT)
130
+ if (occupant && !args.adoptExisting) {
131
+ throw new VaultError('slot-occupied', `PIV slot ${VAULT_SLOT.toString(16)} already holds a key`)
132
+ }
133
+ if (pinChange) await driver.changePin(pinChange.oldPin, pinChange.newPin)
134
+ const verified = await driver.verifyPin(pin)
135
+ if (!verified.ok) throw new VaultError('pin-invalid', 'PIN not accepted', verified.retriesLeft)
136
+ // Adoption still verifies the PIN above: it proves the holder can
137
+ // actually sign with the key they are about to lock funds to.
138
+ if (occupant) {
139
+ args.onPhase('adopting')
140
+ return { info, publicKey: occupant.publicKey, adopted: true }
141
+ }
142
+ args.onPhase('generating')
143
+ const { publicKey } = await driver.generateVaultKey(VAULT_SLOT)
144
+ return { info, publicKey, adopted: false }
145
+ },
146
+ () => args.onPhase('connecting')
147
+ )
148
+
149
+ // The vault seed comes from the user's EXISTING wallet mnemonic plus their
150
+ // passphrase — no second phrase, nothing new to write down. It never leaves
151
+ // this function: only the SEALED blob is persisted. The `finally` below
152
+ // zeroes it on every exit, including a sealVaultKey throw on malformed card
153
+ // key material — the seed must never survive this function on ANY path.
154
+ const seed = deriveVaultSeed(args.mnemonic, args.passphrase)
155
+ let meta: VaultMetaV4
156
+ let seal: SealedBlob
157
+ try {
158
+ try {
159
+ seal = sealVaultKey(seed, publicKey, { slot: VAULT_SLOT, serial: info.serial })
160
+ } catch {
161
+ // sealVaultKey's ECDH throws a raw @noble/curves error (no .code) on a
162
+ // malformed SEC1 point — a card bug or a foreign PIV slot's key.
163
+ // Recode it so callers get a stable, coded failure; never forward the
164
+ // underlying message, which could echo the bad key material back out.
165
+ throw new VaultError('template-invalid', 'YubiKey returned invalid key material')
166
+ }
167
+ // Sealing is done with the seed — zero it now rather than waiting for
168
+ // the outer `finally`, which stays as a backstop for every other exit.
169
+ seed.fill(0)
170
+ meta = {
171
+ v: 4,
172
+ enrolledAt: Date.now(),
173
+ yubiSerial: info.serial,
174
+ nickname: args.nickname,
175
+ slot: VAULT_SLOT,
176
+ // An adopted key is already in use by another device whose deposit
177
+ // counter this one cannot see, so starting at zero would reissue that
178
+ // device's addresses. See randomDepositStartIndex.
179
+ nextKeyIndex: adopted ? randomDepositStartIndex() : 0
180
+ }
181
+ } finally {
182
+ seed.fill(0)
183
+ }
184
+
185
+ args.onPhase('done')
186
+ return { pending: { meta, seal } }
187
+ }
188
+
189
+ /** Commit an enrollment produced by enrollVault. Only here does anything reach
190
+ * disk. The seal is written first: if the process dies between the two
191
+ * writes, `isEnrolled()` (which requires BOTH) still reads false either way,
192
+ * so a half-committed enrollment never looks complete. */
193
+ export async function finalizeEnrollment(pending: PendingEnrollment): Promise<void> {
194
+ await vaultStore.setSeal(pending.seal)
195
+ await vaultStore.setMeta(pending.meta)
196
+ }
197
+
198
+ /**
199
+ * Recover the vault HD node from the MAIN wallet mnemonic plus the vault
200
+ * passphrase — the second of the two recovery paths (see this file's header).
201
+ *
202
+ * BIP39 passphrases have no checksum, so a mistyped one silently derives a
203
+ * different, valid, EMPTY vault node rather than throwing. There used to be a
204
+ * stored xpub here to catch that early; v4 meta stores no key material at
205
+ * all, so that check now happens where it can actually verify something —
206
+ * the spend path's pkh match (transfers.ts) — rather than here.
207
+ */
208
+ export async function recoverVaultHD(mnemonic: string, passphrase: string): Promise<HD> {
209
+ return deriveVaultHD(mnemonic, passphrase) // throws on empty/invalid
210
+ }
211
+
212
+ /** Re-enroll an existing vault to a fresh YubiKey, e.g. after a lost key.
213
+ *
214
+ * The seal always wraps the 64-byte seed, so reseal re-derives the seed from
215
+ * the mnemonic + passphrase itself (rather than taking an already-derived HD
216
+ * node) and seals it fresh to the new card's public key. Preserves
217
+ * nextKeyIndex so deposit indices are never reissued, and zeroizes the seed
218
+ * as soon as sealing succeeds, with `finally` as a backstop for every other
219
+ * exit — exactly like enrollVault.
220
+ *
221
+ * `verifyHD`, if given, gates the whole operation: BIP39 passphrases carry no
222
+ * checksum, so a mistyped one derives a different, valid, EMPTY vault node
223
+ * with no error of its own. Without a check, that typo would overwrite the
224
+ * ONLY seal that opens the real vault with one nobody can ever unwrap back to
225
+ * the real funds — the old physical key is gone (that is the point of
226
+ * resealing) and the new seal is wrong. The check therefore runs as early as
227
+ * the tap flow allows: seed and HD are derived first (no card needed for
228
+ * that), verified BEFORE `driver.getKeyInfo()` — i.e. before the tap begins
229
+ * at all — so a failed verification never burns a PIN attempt, never risks
230
+ * the slot-occupied refusal, and above all never reaches `generateVaultKey`
231
+ * (which would irreversibly overwrite the slot) or the `vaultStore` writes.
232
+ * A caller that omits `verifyHD` keeps today's behavior: it is on the caller
233
+ * to verify the passphrase itself before calling this, whenever the vault
234
+ * may hold funds (the recover UI wires this in a later task).
235
+ *
236
+ * Outputs created under the OLD key stay spendable, and this is the whole
237
+ * point of the K1-only custody model: there is ONE vault key reached two
238
+ * ways, so the replacement card unwraps the SAME seed the old one did and
239
+ * every existing output's child key derives from it exactly as before. No
240
+ * sweep is required after replacing a YubiKey. (The old physical card stops
241
+ * working nonetheless — the ceremony's serial check in
242
+ * armViaReader/openTapSession, ceremony.ts, refuses any card whose serial
243
+ * does not match the newly-stored yubiSerial.)
244
+ *
245
+ * What protects against resealing to a node that is NOT this vault's is
246
+ * `verifyHD` above, plus the per-input pkh comparison in transfers.ts's
247
+ * prepareSpends: each output's locking script is rebuilt from the key
248
+ * actually in hand and compared against the real script out of the listed
249
+ * BEEF, so a wrong key or a mistyped passphrase fails loudly before anything
250
+ * is reserved or signed.
251
+ */
252
+ export async function resealToNewKey(
253
+ mnemonic: string,
254
+ passphrase: string,
255
+ nickname: string,
256
+ getPin: () => Promise<string>,
257
+ verifyHD?: (hd: HD) => Promise<boolean>
258
+ ): Promise<void> {
259
+ const driver = getVaultDriver()
260
+ if (!driver) throw new VaultError('driver-unavailable')
261
+
262
+ const seed = deriveVaultSeed(mnemonic, passphrase)
263
+ try {
264
+ // Fail closed BEFORE any card interaction: see this function's doc
265
+ // comment for why this has to be the earliest possible point.
266
+ if (verifyHD && !(await verifyHD(HD.fromSeed(seed)))) {
267
+ throw new VaultError('bad-passphrase', 'Passphrase does not match this vault')
268
+ }
269
+
270
+ const info = await driver.getKeyInfo()
271
+ if (info.pinRetries === 0) throw new VaultError('pin-locked', 'PIN is blocked')
272
+ if (await driver.readVaultPublicKey(VAULT_SLOT)) {
273
+ throw new VaultError('slot-occupied', `PIV slot ${VAULT_SLOT.toString(16)} already holds a key`)
274
+ }
275
+ const pin = await getPin()
276
+ const verified = await driver.verifyPin(pin)
277
+ if (!verified.ok) throw new VaultError('pin-invalid', 'PIN not accepted', verified.retriesLeft)
278
+ const { publicKey } = await driver.generateVaultKey(VAULT_SLOT)
279
+
280
+ let seal: SealedBlob
281
+ try {
282
+ seal = sealVaultKey(seed, publicKey, { slot: VAULT_SLOT, serial: info.serial })
283
+ } catch {
284
+ // See enrollVault's identical wrap: never forward the raw error text.
285
+ throw new VaultError('template-invalid', 'YubiKey returned invalid key material')
286
+ }
287
+ // Sealing is done with the seed — zero it now; `finally` is a backstop.
288
+ seed.fill(0)
289
+
290
+ // Preserve nextKeyIndex across the re-enrollment so deposit indices are
291
+ // never reissued to a second address.
292
+ const prev = await vaultStore.getMeta()
293
+ const meta: VaultMetaV4 = {
294
+ v: 4,
295
+ enrolledAt: Date.now(),
296
+ yubiSerial: info.serial,
297
+ nickname,
298
+ slot: VAULT_SLOT,
299
+ nextKeyIndex: prev?.nextKeyIndex ?? 0
300
+ }
301
+ await vaultStore.setSeal(seal)
302
+ await vaultStore.setMeta(meta)
303
+ } finally {
304
+ seed.fill(0)
305
+ }
306
+ }
307
+
308
+ /** Remove all vault state. Callers must sweep funds to the default basket
309
+ * BEFORE calling this — see transfers.sweepVaultWithHD. */
310
+ export async function disableVault(): Promise<void> {
311
+ await vaultStore.clear()
312
+ }