@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,152 +0,0 @@
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
- }
@@ -1,287 +0,0 @@
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
- }