@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,109 @@
1
+ /**
2
+ * Vault domain types — shared by the sealing crypto, the store, the ceremony
3
+ * controller, and the UI. No React, no I/O.
4
+ */
5
+
6
+ /** Persisted seal: everything needed to recover the vault key EXCEPT the
7
+ * on-token ECDH. The blob alone is useless without the physical YubiKey. */
8
+ export interface SealedBlob {
9
+ v: 1
10
+ /** PIV slot holding the P-256 key (0x82, first "retired" slot). */
11
+ slot: number
12
+ /** Ephemeral P-256 public key, hex, 65-byte uncompressed SEC1 point. */
13
+ ePub: string
14
+ /** HKDF salt, hex, 32 bytes. */
15
+ salt: string
16
+ /** AES-256-GCM ciphertext of the vault key (SymmetricKey wire format), hex. */
17
+ c: string
18
+ /** Serial of the enrolled YubiKey — ceremony rejects other keys early. */
19
+ yubiSerial: string
20
+ /** sha256 of the token public key, hex — sanity check against slot rewrites. */
21
+ yubiPubSha256: string
22
+ }
23
+
24
+ export type VaultErrorCode =
25
+ | 'unsupported-platform'
26
+ | 'no-key'
27
+ | 'wrong-key'
28
+ | 'pin-required'
29
+ | 'pin-invalid'
30
+ | 'pin-locked'
31
+ | 'touch-timeout'
32
+ | 'key-removed-mid-op'
33
+ | 'mgmt-key-custom'
34
+ | 'slot-occupied'
35
+ /** unsealVaultKey could not open a SealedBlob — wrong shared secret,
36
+ * tampered ciphertext, or a malformed blob. Never distinguishes which. */
37
+ | 'seal-corrupt'
38
+ /** A vault key digest or key material failed a structural check. Usually a
39
+ * corrupted dependency or a native bug, but a user CAN cause this: choosing
40
+ * to adopt a foreign PIV slot (VaultKeyService's `adoptExisting`) whose key
41
+ * material isn't a compatible EC point makes sealVaultKey's ECDH reject it
42
+ * the same way. Distinct from 'wrong-key', which vaultErrorFromNative may
43
+ * reclassify to 'nfc-lost'. */
44
+ | 'template-invalid'
45
+ | 'serial-mismatch'
46
+ | 'user-cancelled'
47
+ | 'not-enrolled'
48
+ | 'driver-unavailable'
49
+ | 'vault-empty'
50
+ | 'amount-exceeds-balance'
51
+ | 'below-dust'
52
+ | 'no-transaction'
53
+ | 'nfc-lost'
54
+ /** Vault passphrase missing or empty — an empty one would collide with the
55
+ * main wallet's master key. */
56
+ | 'bad-passphrase'
57
+ /** Main wallet recovery phrase failed BIP39 validation. */
58
+ | 'bad-mnemonic'
59
+ /** Deposit index outside the non-hardened BIP32 range. */
60
+ | 'bad-derivation-index'
61
+ /** No backup attestation for this wallet — depositing would create funds
62
+ * with no recovery path. Advisory gate, not a security control. */
63
+ | 'backup-required'
64
+ /** More vault inputs would be needed than one transaction may safely carry.
65
+ * See VAULT_MAX_INPUTS — the remedy is a smaller withdrawal, which also
66
+ * consolidates the vault. */
67
+ | 'too-many-inputs'
68
+ /** The device is offline. Vault transfers never enter the offline queue — see
69
+ * VaultTransferOptions.isOnline. */
70
+ | 'requires-online'
71
+
72
+ export class VaultError extends Error {
73
+ code: VaultErrorCode
74
+ /** PIN attempts remaining, present on pin-invalid. */
75
+ retriesLeft?: number
76
+
77
+ constructor(code: VaultErrorCode, message?: string, retriesLeft?: number) {
78
+ super(message ?? code)
79
+ this.name = 'VaultError'
80
+ this.code = code
81
+ this.retriesLeft = retriesLeft
82
+ }
83
+ }
84
+
85
+ /** Native YubiKit description substrings for a dropped NFC field mid-command
86
+ * (the phone moved a hair off the key, or the key was lifted). This is
87
+ * transient and retryable — never a wrong key, but older/currently-installed
88
+ * builds' Swift `mapError` falls through to its `wrong-key` default for any
89
+ * description it doesn't specifically recognize, which includes this one. */
90
+ const NFC_LOST_PATTERN = /tag response error|no response|tag connection lost|session invalidated/i
91
+
92
+ /** Parse a native-module rejection (`VAULT_ERR:<code>:<detail>`) into a
93
+ * VaultError; anything unrecognized becomes a generic driver failure. */
94
+ export function vaultErrorFromNative(e: unknown): VaultError {
95
+ const msg = e instanceof Error ? e.message : String(e)
96
+ const m = /^VAULT_ERR:([a-z-]+):?(.*)$/.exec(msg)
97
+ if (m) {
98
+ let code = m[1] as VaultErrorCode
99
+ const detailMatch = /retries=(\d+)/.exec(m[2])
100
+ // Reclassify a native `wrong-key` whose detail is really an NFC dropout —
101
+ // see NFC_LOST_PATTERN. Safe to keep even after the native side is fixed
102
+ // to classify this correctly at the source: this simply never matches then.
103
+ if (code === 'wrong-key' && NFC_LOST_PATTERN.test(m[2])) {
104
+ code = 'nfc-lost'
105
+ }
106
+ return new VaultError(code, m[2] || undefined, detailMatch ? Number(detailMatch[1]) : undefined)
107
+ }
108
+ return new VaultError('driver-unavailable', msg)
109
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Vault key derivation — pure functions, no I/O, no logging.
3
+ *
4
+ * V comes from the SAME mnemonic as the main wallet, domain-separated by a
5
+ * non-empty BIP39 passphrase, and deposit addresses are plain BIP32 children:
6
+ *
7
+ * main wallet : HD.fromSeed(Mnemonic.toSeed(''))
8
+ * vault HD node : HD.fromSeed(Mnemonic.toSeed(passphrase))
9
+ * deposit addr n : vaultHD.deriveChild(n)
10
+ *
11
+ * This replaces two earlier designs at once:
12
+ * - the second random 24-word mnemonic (the user now backs up ONE phrase)
13
+ * - the precomputed queue of 64 deposit key hashes in vault meta
14
+ *
15
+ * There is no xpub anywhere in this design, and nothing about the vault is
16
+ * ever public at rest: the vault stores a YubiKey-sealed seed and a bare
17
+ * `nextKeyIndex` counter, nothing else. Deposit address n derives from the
18
+ * private HD node, which exists only transiently, after one of the two
19
+ * recovery routes below reaches it.
20
+ *
21
+ * Recovery paths, and there are exactly two:
22
+ * 1. YubiKey-unseal of the sealed seed — the YubiKey unwraps the seed,
23
+ * which reconstructs this same HD node; nothing to type.
24
+ * 2. main mnemonic + passphrase — via this file; the same
25
+ * mnemonic and passphrase reconstruct the same HD node offline.
26
+ * Both routes reach the identical HD node. There is no third path. Nobody
27
+ * can reset it. Deposit address n derives on demand from that node, once
28
+ * per unseal, however many indices are needed — unlike the old 64-key
29
+ * queue, which failed closed until a privileged ceremony refilled it.
30
+ *
31
+ * SECURITY: never log the seed, the HD node, the mnemonic, or the passphrase.
32
+ */
33
+ import { PrivateKey, HD, Mnemonic, Hash } from '@bsv/sdk'
34
+ import { normalizeVaultPassphrase } from './vaultPassphrase'
35
+ import { randomBytes } from './random'
36
+ import { VaultError } from './types'
37
+
38
+ /** BIP32 hardened-index boundary. Deposit indices stay below this so the
39
+ * derivation path is uniform and predictable across every call site. */
40
+ const HARDENED = 0x80000000
41
+
42
+ function assertNonHardened(index: number): void {
43
+ if (!Number.isInteger(index) || index < 0 || index >= HARDENED) {
44
+ throw new VaultError(
45
+ 'bad-derivation-index',
46
+ `Deposit index must be a non-hardened BIP32 index (0..${HARDENED - 1})`
47
+ )
48
+ }
49
+ }
50
+
51
+ /**
52
+ * The vault's 64-byte BIP39 seed.
53
+ *
54
+ * @throws VaultError if the passphrase is empty — an empty passphrase would
55
+ * make the vault seed identical to the main wallet's, letting the hot wallet
56
+ * spend the vault.
57
+ */
58
+ export function deriveVaultSeed(mnemonic: string, passphrase: string): number[] {
59
+ const pass = normalizeVaultPassphrase(passphrase)
60
+ if (pass.length === 0) {
61
+ throw new VaultError('bad-passphrase', 'A vault passphrase is required and must not be empty')
62
+ }
63
+ const phrase = mnemonic.trim().replace(/\s+/g, ' ')
64
+ if (!Mnemonic.isValid(phrase)) {
65
+ throw new VaultError('bad-mnemonic', 'Invalid recovery phrase')
66
+ }
67
+ return Mnemonic.fromString(phrase).toSeed(pass)
68
+ }
69
+
70
+ /**
71
+ * Prefix marking a keyID as a BIP32 child index.
72
+ *
73
+ * Legacy v1 outputs carry BRC-42 key ids of the form 'vault/<n>'. The two must
74
+ * stay distinguishable: a signer that mistook one for the other would sign
75
+ * with the wrong key and produce an invalid spend.
76
+ */
77
+ export const BIP32_KEYID_PREFIX = 'bip32/'
78
+
79
+ export const bip32KeyID = (index: number): string => `${BIP32_KEYID_PREFIX}${index}`
80
+
81
+ /** Index for a BIP32 keyID, or null if this is not one (e.g. a v1 keyID). */
82
+ export function indexFromKeyID(keyID: string): number | null {
83
+ if (!keyID.startsWith(BIP32_KEYID_PREFIX)) return null
84
+ const raw = keyID.slice(BIP32_KEYID_PREFIX.length)
85
+ if (!/^\d+$/.test(raw)) return null
86
+ const n = Number(raw)
87
+ return Number.isSafeInteger(n) && n < HARDENED ? n : null
88
+ }
89
+
90
+ /** Floor for an adopted vault's first deposit index — above any counter a
91
+ * device that started at zero could plausibly have reached. */
92
+ const ADOPT_INDEX_MIN = 1 << 20
93
+ /** Width of the random span above that floor. Keeps every index well below the
94
+ * hardened boundary, so a lifetime of increments can never reach it. */
95
+ const ADOPT_INDEX_SPAN = 1 << 28
96
+
97
+ /**
98
+ * A random, non-hardened starting deposit index.
99
+ *
100
+ * Used when a device adopts a YubiKey that is already enrolled elsewhere: both
101
+ * devices reach the SAME HD node (via the same mnemonic+passphrase, or the
102
+ * same unsealed seed), and a device-local counter is the only thing choosing
103
+ * indices, so two devices starting at zero would hand out the same deposit
104
+ * addresses. Reusing an address does not risk funds — it links
105
+ * two deposits and confuses the history — and coordinating counters across
106
+ * devices would need a channel the vault deliberately does not have. A random
107
+ * start in a 2^28-wide span makes a collision negligible instead.
108
+ */
109
+ export function randomDepositStartIndex(): number {
110
+ const b = randomBytes(4)
111
+ const r = ((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]) >>> 0
112
+ return ADOPT_INDEX_MIN + (r % ADOPT_INDEX_SPAN)
113
+ }
114
+
115
+ /**
116
+ * The vault's private HD node.
117
+ *
118
+ * The seed derived here is this function's OWN copy — enrollVault and
119
+ * resealToNewKey zeroize the separate arrays they derive for sealing, and
120
+ * neither of them can reach this one. Without the wipe below, every call
121
+ * (recoverVaultHD, the sweep path, the spend-proof script) would hand a live
122
+ * 64-byte seed to the garbage collector instead of overwriting it.
123
+ *
124
+ * Wiping is safe because `HD.fromSeed` does not retain the array: it
125
+ * immediately HMAC-SHA512s it into the chain code and private key
126
+ * (@bsv/sdk's compat/HD `fromSeed`) and keeps no reference. The `finally`
127
+ * covers the throwing path too — `HD.fromSeed` rejects a seed outside
128
+ * 16..64 bytes, and a seed must not survive that refusal either.
129
+ */
130
+ export function deriveVaultHD(mnemonic: string, passphrase: string): HD {
131
+ const seed = deriveVaultSeed(mnemonic, passphrase)
132
+ try {
133
+ return HD.fromSeed(seed)
134
+ } finally {
135
+ seed.fill(0)
136
+ }
137
+ }
138
+
139
+ /** Private key for deposit index n. Requires the private node. */
140
+ export function depositPrivKey(hd: HD, index: number): PrivateKey {
141
+ assertNonHardened(index)
142
+ return hd.deriveChild(index).privKey
143
+ }
144
+
145
+ /**
146
+ * Deposit address hash160 for index n. Requires the private node — there is
147
+ * no xpub to derive this from without it.
148
+ */
149
+ export function depositPubKeyHash(hd: HD, index: number): number[] {
150
+ assertNonHardened(index)
151
+ return Hash.hash160(hd.deriveChild(index).pubKey.encode(true) as number[])
152
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Vault passphrase strength policy.
3
+ *
4
+ * The vault key is derived from the main wallet mnemonic plus a user-chosen
5
+ * passphrase through BIP39 `Mnemonic.toSeed(passphrase)` — PBKDF2-HMAC-SHA512
6
+ * at 2048 rounds (see @bsv/sdk compat/Mnemonic mnemonic2Seed). 2048 rounds is
7
+ * essentially no work factor by modern standards, so an attacker who obtains
8
+ * the main mnemonic can grind candidate passphrases offline very cheaply.
9
+ *
10
+ * Measured on a single CPU core here: ~2,400 guesses/sec. A commodity GPU rig
11
+ * is comfortably 10^7/sec. Against that:
12
+ *
13
+ * 8 lowercase letters ~1.2 hours
14
+ * 8 mixed alphanumeric ~53 days
15
+ * 5 random BIP39 words ~57 years (55 bits — the floor)
16
+ * 6 random BIP39 words ~117,000 years (66 bits — what we generate)
17
+ *
18
+ * Hence the gate is expressed in guessing entropy rather than character-class
19
+ * rules, which add almost nothing against offline search. Note the word model
20
+ * credits 11 bits/word (BIP39's 2048-word list), not diceware's 12.9.
21
+ *
22
+ * SECURITY: never log the passphrase or anything derived from it. These
23
+ * functions deliberately return only a bit estimate and a verdict.
24
+ */
25
+
26
+ /**
27
+ * Minimum guessing entropy, in bits, accepted for a vault passphrase.
28
+ *
29
+ * 55 bits is exactly five words drawn uniformly from the BIP39 list, which is
30
+ * the floor the security review set for this KDF.
31
+ */
32
+ import { Mnemonic } from '@bsv/sdk'
33
+ import { randomBytes } from './random'
34
+
35
+ export const VAULT_PASSPHRASE_MIN_BITS = 55
36
+
37
+ /**
38
+ * Bits per word, from the BIP39 English wordlist: 2048 words = 11 bits.
39
+ *
40
+ * Deliberately NOT diceware's 7776 (12.9 bits). Generated passphrases come
41
+ * from the BIP39 list, and user-chosen words are not uniform over any list, so
42
+ * crediting 12.9 would overstate real strength by roughly two bits per word.
43
+ */
44
+ const BITS_PER_WORD = Math.log2(2048)
45
+
46
+ /**
47
+ * Words offered by the generator. Six gives 66 bits — comfortable margin over
48
+ * the 55-bit floor, which five words only just reaches.
49
+ */
50
+ export const RECOMMENDED_WORD_COUNT = 6
51
+
52
+ /** The floor, in words: five random words is exactly VAULT_PASSPHRASE_MIN_BITS. */
53
+ export const MINIMUM_WORD_COUNT = 5
54
+
55
+ /**
56
+ * Assumed offline guess rate, in guesses/sec, for an attacker who already
57
+ * holds the main mnemonic and is grinding the passphrase.
58
+ *
59
+ * Measured here: ~2,400/sec on one CPU core against PBKDF2-SHA512 at 2048
60
+ * rounds. 10^7 is a modest GPU rig — deliberately conservative, so the number
61
+ * shown to the user understates rather than overstates their safety.
62
+ */
63
+ const ATTACKER_GUESSES_PER_SEC = 1e7
64
+
65
+ /** Entropy at which the meter bar reads full. */
66
+ const METER_FULL_BITS = 80
67
+
68
+ const SECONDS_PER_YEAR = 31557600
69
+
70
+ /**
71
+ * Generate a passphrase of uniformly random BIP39 words.
72
+ *
73
+ * An app-generated phrase is strictly stronger than a user-invented one: human
74
+ * choices cluster hard, which is exactly what a cracking rule set exploits.
75
+ */
76
+ export function generatePassphrase(words: number = RECOMMENDED_WORD_COUNT): string {
77
+ if (!Number.isInteger(words) || words < MINIMUM_WORD_COUNT) {
78
+ throw new Error(`Refusing to generate fewer than ${MINIMUM_WORD_COUNT} words`)
79
+ }
80
+ const out: string[] = []
81
+ // 32 bytes of entropy yields 24 words; loop for unusually long requests.
82
+ while (out.length < words) {
83
+ out.push(...new Mnemonic().entropy2Mnemonic(randomBytes(32)).toString().split(' '))
84
+ }
85
+ return out.slice(0, words).join(' ')
86
+ }
87
+
88
+ export interface PassphraseVerdict {
89
+ ok: boolean
90
+ bits: number
91
+ reason?: string
92
+ }
93
+
94
+ export type PassphraseTier = 'empty' | 'weak' | 'fair' | 'strong' | 'excellent'
95
+
96
+ export interface PassphraseStrength {
97
+ ok: boolean
98
+ bits: number
99
+ /** 0..1, for driving a meter bar. */
100
+ fraction: number
101
+ tier: PassphraseTier
102
+ /** Human-readable time to crack, e.g. "about 44,000 years". */
103
+ crackTime: string
104
+ reason?: string
105
+ }
106
+
107
+ /**
108
+ * Normalise a passphrase for both checking and derivation.
109
+ *
110
+ * BIP39 applies NFKD but does NOT trim, so " abc" and "abc" derive different
111
+ * seeds. Callers MUST run the passphrase through this before `toSeed`, so a
112
+ * stray leading space can never silently produce a different (empty) vault.
113
+ */
114
+ export function normalizeVaultPassphrase(passphrase: string): string {
115
+ return passphrase.normalize('NFKD').trim().replace(/\s+/g, ' ')
116
+ }
117
+
118
+ /** Size of the character space the passphrase appears to be drawn from. */
119
+ function charsetSize(s: string): number {
120
+ let size = 0
121
+ if (/[a-z]/.test(s)) size += 26
122
+ if (/[A-Z]/.test(s)) size += 26
123
+ if (/[0-9]/.test(s)) size += 10
124
+ if (/\s/.test(s)) size += 1
125
+ if (/[^a-zA-Z0-9\s]/.test(s)) size += 33
126
+ return size
127
+ }
128
+
129
+ /** Collapse runs of the same character so "aaaa" counts as one choice. */
130
+ function collapseRuns(s: string): string {
131
+ return s.replace(/(.)\1+/g, '$1')
132
+ }
133
+
134
+ /**
135
+ * Common password bases, after leet-normalisation and affix stripping.
136
+ *
137
+ * Character-class variety is not entropy when the base word is guessable: a
138
+ * naive charset^length model rates "P@ssw0rd123" at ~66 bits, which would sail
139
+ * past the gate. Any attacker grinding this KDF tries these first.
140
+ */
141
+ const COMMON_BASES = new Set([
142
+ 'password', 'passwd', 'pass', 'qwerty', 'qwertyuiop', 'asdf', 'asdfgh', 'zxcvbn',
143
+ 'letmein', 'iloveyou', 'monkey', 'admin', 'administrator', 'welcome', 'login',
144
+ 'troubador', 'troubadour', 'dragon', 'sunshine', 'princess', 'football',
145
+ 'baseball', 'basketball', 'master', 'shadow', 'superman', 'batman', 'starwars',
146
+ 'michael', 'jennifer', 'jordan', 'hunter', 'trustno', 'whatever', 'freedom',
147
+ 'ninja', 'access', 'flower', 'secret', 'summer', 'winter', 'google', 'abc',
148
+ 'test', 'guest', 'root', 'user', 'changeme', 'default', 'bitcoin', 'satoshi'
149
+ ])
150
+
151
+ const LEET: Record<string, string> = {
152
+ '@': 'a', '0': 'o', '3': 'e', '$': 's', '4': 'a',
153
+ '7': 't', '5': 's', '8': 'b', '+': 't', '(': 'c'
154
+ }
155
+
156
+ /**
157
+ * Reduce a passphrase to its likely base word, the way a cracking rule set
158
+ * would: drop leading/trailing digit and punctuation affixes first (those are
159
+ * suffixes, not leet), then map leet substitutions in what remains.
160
+ *
161
+ * '1' is ambiguous (i or l), so both readings are returned.
162
+ */
163
+ function baseCandidates(s: string): string[] {
164
+ const stripped = s.replace(/^[^a-zA-Z@$0-9]+|[\d\W_]+$/g, '')
165
+ const map = (oneAs: string): string =>
166
+ stripped
167
+ .split('')
168
+ .map(c => (c === '1' ? oneAs : (LEET[c] ?? c)))
169
+ .join('')
170
+ .toLowerCase()
171
+ .replace(/[^a-z]/g, '')
172
+ return [map('i'), map('l')]
173
+ }
174
+
175
+ /** True if the passphrase is a common password wearing a disguise. */
176
+ function isCommonPassword(s: string): boolean {
177
+ if (s.includes(' ')) return false // multi-word phrases are handled by the word model
178
+ return baseCandidates(s).some(b => b.length >= 3 && COMMON_BASES.has(b))
179
+ }
180
+
181
+ /** Entropy credited to a recognised common password, in bits. Deliberately
182
+ * near zero: it is in the first million guesses of any attack. */
183
+ const COMMON_PASSWORD_BITS = 12
184
+
185
+ /**
186
+ * Conservative guessing-entropy estimate, in bits.
187
+ *
188
+ * Two models are computed and the SMALLER is returned, so a passphrase is
189
+ * only credited with strength both models agree on.
190
+ */
191
+ export function passphraseEntropyBits(passphrase: string): number {
192
+ const s = normalizeVaultPassphrase(passphrase)
193
+ if (s.length === 0) return 0
194
+ if (isCommonPassword(s)) return COMMON_PASSWORD_BITS
195
+
196
+ const charBits = collapseRuns(s).length * Math.log2(charsetSize(s) || 1)
197
+
198
+ // Word model only applies to an actual multi-word alphabetic phrase;
199
+ // applying it to a single random-looking token would wrongly reject a
200
+ // genuinely strong 16-char password.
201
+ const tokens = s.split(' ')
202
+ const isWordPhrase = tokens.length >= 2 && tokens.every(t => /^[a-zA-Z]+$/.test(t))
203
+ if (!isWordPhrase) return charBits
204
+
205
+ const uniqueWords = new Set(tokens.map(t => t.toLowerCase())).size
206
+ const wordBits = uniqueWords * BITS_PER_WORD
207
+ return Math.min(charBits, wordBits)
208
+ }
209
+
210
+ /** Apply the vault passphrase policy. */
211
+ export function checkVaultPassphrase(passphrase: string): PassphraseVerdict {
212
+ const s = normalizeVaultPassphrase(passphrase)
213
+ if (s.length === 0) {
214
+ return { ok: false, bits: 0, reason: 'A vault passphrase is required.' }
215
+ }
216
+
217
+ const bits = passphraseEntropyBits(s)
218
+ if (bits < VAULT_PASSPHRASE_MIN_BITS) {
219
+ return {
220
+ ok: false,
221
+ bits,
222
+ reason:
223
+ 'This passphrase is too weak. Use five or more unrelated words — anyone who obtains your recovery phrase can guess a short passphrase in hours.'
224
+ }
225
+ }
226
+ return { ok: true, bits }
227
+ }
228
+
229
+ /**
230
+ * Average seconds to crack, assuming the attacker already has the main
231
+ * mnemonic and must only guess the passphrase. Average, not worst case, so
232
+ * half the search space.
233
+ */
234
+ export function crackTimeSeconds(bits: number): number {
235
+ if (bits <= 0) return 0
236
+ return Math.pow(2, bits) / 2 / ATTACKER_GUESSES_PER_SEC
237
+ }
238
+
239
+ /** "1 hour" / "2 hours" — never "1 hours". */
240
+ function qty(n: number, unit: string): string {
241
+ const r = Math.round(n)
242
+ return `${r.toLocaleString('en-US')} ${unit}${r === 1 ? '' : 's'}`
243
+ }
244
+
245
+ /** Short, readable crack time for a meter caption. Never exponent notation. */
246
+ export function formatCrackTime(bits: number): string {
247
+ if (bits <= 0) return 'instantly'
248
+ const s = crackTimeSeconds(bits)
249
+ if (s < 1) return 'under a second'
250
+ if (s < 60) return qty(s, 'second')
251
+ if (s < 3600) return qty(s / 60, 'minute')
252
+ if (s < 86400) return qty(s / 3600, 'hour')
253
+ if (s < 2592000) return qty(s / 86400, 'day')
254
+ if (s < SECONDS_PER_YEAR) return qty(s / 2592000, 'month')
255
+
256
+ const years = s / SECONDS_PER_YEAR
257
+ if (years < 1000) return qty(years, 'year')
258
+ if (years < 1e6) return `${Math.round(years / 1000).toLocaleString('en-US')} thousand years`
259
+ if (years < 1e9) return `${Math.round(years / 1e6).toLocaleString('en-US')} million years`
260
+ if (years < 1e12) return `${Math.round(years / 1e9).toLocaleString('en-US')} billion years`
261
+ return 'longer than the universe has existed'
262
+ }
263
+
264
+ function tierFor(bits: number): PassphraseTier {
265
+ if (bits <= 0) return 'empty'
266
+ if (bits < 50) return 'weak'
267
+ if (bits < VAULT_PASSPHRASE_MIN_BITS) return 'fair'
268
+ if (bits < METER_FULL_BITS) return 'strong'
269
+ return 'excellent'
270
+ }
271
+
272
+ /**
273
+ * Everything the passphrase field needs to render live as the user types:
274
+ * the verdict, a 0..1 bar, a tier for colour, and the crack time in words.
275
+ */
276
+ export function passphraseStrength(passphrase: string): PassphraseStrength {
277
+ const verdict = checkVaultPassphrase(passphrase)
278
+ const { bits } = verdict
279
+ return {
280
+ ok: verdict.ok,
281
+ bits,
282
+ fraction: Math.max(0, Math.min(1, bits / METER_FULL_BITS)),
283
+ tier: tierFor(bits),
284
+ crackTime: formatCrackTime(bits),
285
+ reason: verdict.reason
286
+ }
287
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Vault persistence.
3
+ *
4
+ * - Sealed blob → expo-secure-store ('vault_seal_v1'), same Keychain
5
+ * accessibility class as the wallet mnemonic. The seal alone is useless
6
+ * without the physical YubiKey; SecureStore here is defense-in-depth, and
7
+ * it is deliberately NOT behind LocalStorageProvider's biometric latch —
8
+ * the YubiKey ceremony is the gate for anything the seal protects.
9
+ * - UI metadata (serial, nickname, deposit-index counter) → AsyncStorage
10
+ * ('vault_meta_v1'). Nothing secret lives here, and no key material either:
11
+ * v4 carries no xpub and no card public key. The only thing that can
12
+ * produce a vault address is the private HD node, which exists solely for
13
+ * the length of a ceremony (or a mnemonic + passphrase recovery).
14
+ *
15
+ * v1-v3 records are not readable — `getMeta` returns null for anything whose
16
+ * `v` isn't 4, so an un-migrated install reads as "not enrolled" rather than
17
+ * deserialising into something this code would misuse.
18
+ */
19
+ import AsyncStorage from '@react-native-async-storage/async-storage'
20
+ import * as SecureStore from 'expo-secure-store'
21
+ import { SealedBlob } from './types'
22
+
23
+ const SEAL_KEY = 'vault_seal_v1'
24
+ const META_KEY = 'vault_meta_v1'
25
+
26
+ /**
27
+ * Current enrollment.
28
+ *
29
+ * K1-only vault: at rest this is just the sealed blob plus this plaintext
30
+ * counter. No xpub and no card public key: the one secret at rest is the
31
+ * seed inside the sealed blob, and nothing here narrows the search for it.
32
+ */
33
+ export interface VaultMetaV4 {
34
+ v: 4
35
+ enrolledAt: number
36
+ yubiSerial: string
37
+ nickname: string
38
+ /** PIV slot holding the card's P-256 ECDH key (0x82). */
39
+ slot: number
40
+ /** Next unused deposit index — monotonic, never reused. */
41
+ nextKeyIndex: number
42
+ lastUsedAt?: number
43
+ }
44
+
45
+ export type VaultMeta = VaultMetaV4
46
+
47
+ const secureOpts = { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY }
48
+
49
+ export const vaultStore = {
50
+ async isEnrolled(): Promise<boolean> {
51
+ const [meta, seal] = await Promise.all([vaultStore.getMeta(), vaultStore.getSeal()])
52
+ return meta != null && seal != null
53
+ },
54
+
55
+ async getSeal(): Promise<SealedBlob | null> {
56
+ const raw = await SecureStore.getItemAsync(SEAL_KEY, secureOpts)
57
+ if (!raw) return null
58
+ try {
59
+ return JSON.parse(raw) as SealedBlob
60
+ } catch {
61
+ return null
62
+ }
63
+ },
64
+
65
+ async setSeal(b: SealedBlob): Promise<void> {
66
+ await SecureStore.setItemAsync(SEAL_KEY, JSON.stringify(b), secureOpts)
67
+ },
68
+
69
+ async getMeta(): Promise<VaultMeta | null> {
70
+ const raw = await AsyncStorage.getItem(META_KEY)
71
+ if (!raw) return null
72
+ try {
73
+ const parsed = JSON.parse(raw) as { v?: unknown }
74
+ return parsed?.v === 4 ? (parsed as VaultMeta) : null
75
+ } catch {
76
+ return null
77
+ }
78
+ },
79
+
80
+ async setMeta(m: VaultMeta): Promise<void> {
81
+ await AsyncStorage.setItem(META_KEY, JSON.stringify(m))
82
+ },
83
+
84
+ /**
85
+ * Reserve the next deposit index and advance the counter.
86
+ *
87
+ * Persisted before returning: a crash between deposits must never reissue an
88
+ * index, since two deposits to the same K1 key are linkable and confusing.
89
+ */
90
+ async takeNextIndex(): Promise<number | null> {
91
+ const meta = await vaultStore.getMeta()
92
+ if (!meta) return null
93
+ const index = meta.nextKeyIndex
94
+ await vaultStore.setMeta({ ...meta, nextKeyIndex: index + 1 })
95
+ return index
96
+ },
97
+
98
+ /** Remove everything, including the sealed blob — used by disable +
99
+ * recovery flows. */
100
+ async clear(): Promise<void> {
101
+ await SecureStore.deleteItemAsync(SEAL_KEY).catch(() => {})
102
+ await AsyncStorage.removeItem(META_KEY)
103
+ }
104
+ }