@bsv/expo-wallet-toolbox 0.4.0 → 0.5.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 (118) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +0 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +9 -1
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +409 -20
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +97 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/storage/StorageExpoSQLite.ts +382 -56
  54. package/core/storage/dbImage.ts +48 -0
  55. package/core/storage/methods/findSql.ts +0 -54
  56. package/core/storage/methods/listOutputsSql.ts +7 -3
  57. package/core/storage/methods/offlineActions.ts +15 -0
  58. package/core/storage/methods/processOfflineActions.ts +263 -6
  59. package/core/storage/methods/walletBalanceSql.ts +16 -4
  60. package/core/storage/schema/createTables.ts +123 -0
  61. package/core/storage/sqlUpdateValue.ts +24 -0
  62. package/core/toolboxConfig.ts +112 -1
  63. package/core/walletRepair/runWalletCheck.ts +19 -2
  64. package/package.json +25 -24
  65. package/ui/components/QRScanner.tsx +1 -1
  66. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  67. package/ui/components/pay/AssetPicker.tsx +184 -0
  68. package/ui/components/pay/AvailableBalance.tsx +33 -2
  69. package/ui/components/pay/HandleReceive.tsx +213 -50
  70. package/ui/components/pay/NearbyFlow.tsx +616 -69
  71. package/ui/components/pay/PayForm.tsx +73 -8
  72. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  73. package/ui/components/pay/RecipientField.tsx +49 -4
  74. package/ui/components/pay/RequestHub.tsx +68 -8
  75. package/ui/components/pay/ResultBanner.tsx +41 -4
  76. package/ui/components/pay/UniversalSend.tsx +534 -30
  77. package/ui/components/pay/tokenSendCopy.ts +116 -0
  78. package/ui/components/pay/useRecipientInput.ts +36 -7
  79. package/ui/components/ui/PermissionSheet.tsx +65 -4
  80. package/ui/components/ui/Sheet.tsx +9 -2
  81. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  82. package/ui/components/vault/KeyChooser.tsx +96 -0
  83. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  84. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  85. package/ui/components/wallet/ActivityRow.tsx +101 -17
  86. package/ui/components/wallet/AmountInput.tsx +77 -25
  87. package/ui/components/wallet/AssetAmount.tsx +95 -0
  88. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  89. package/ui/components/wallet/tokenEviction.ts +65 -0
  90. package/ui/hooks/useExportWalletData.ts +39 -0
  91. package/ui/hooks/useMandala.ts +303 -0
  92. package/ui/hooks/useVaultBalance.ts +105 -7
  93. package/ui/hooks/useVaultCoverage.ts +52 -0
  94. package/ui/importDatabases.ts +7 -3
  95. package/ui/index.ts +50 -7
  96. package/ui/screens/ConnectionsScreen.tsx +46 -29
  97. package/ui/screens/PairScreen.tsx +12 -12
  98. package/ui/screens/PayScreen.tsx +130 -10
  99. package/ui/screens/SettingsScreen.tsx +18 -9
  100. package/ui/screens/VaultScreen.tsx +925 -171
  101. package/ui/screens/VaultTransferScreen.tsx +376 -123
  102. package/ui/screens/WalletCheckScreen.tsx +10 -1
  103. package/ui/screens/WalletConfigScreen.tsx +38 -16
  104. package/ui/screens/WalletHomeScreen.tsx +417 -86
  105. package/ui/screens/homeBadges.ts +9 -1
  106. package/ui/screens/tokenRowTitle.ts +68 -0
  107. package/ui/tokenFormat.ts +108 -0
  108. package/ui/tokenSeen.ts +75 -0
  109. package/ui/tokenStatus.ts +79 -0
  110. package/assets/sounds/vault-close.wav +0 -0
  111. package/assets/sounds/vault-open.wav +0 -0
  112. package/core/services/vault/k1.ts +0 -75
  113. package/core/services/vault/sealing.ts +0 -84
  114. package/core/services/vault/vaultDerivation.ts +0 -152
  115. package/core/services/vault/vaultPassphrase.ts +0 -287
  116. package/ui/components/vault/PassphraseField.tsx +0 -306
  117. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  118. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -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
- }
@@ -1,306 +0,0 @@
1
- /**
2
- * Vault passphrase entry with a live strength meter.
3
- *
4
- * Two things this component exists to prevent:
5
- *
6
- * 1. A weak passphrase. The vault key comes from the wallet mnemonic plus this
7
- * passphrase via BIP39 PBKDF2 at 2048 rounds, so anyone holding the
8
- * mnemonic can grind a typeable password in hours. The meter shows the
9
- * honest crack time rather than a vague "weak/strong" badge.
10
- *
11
- * 2. A typo. BIP39 passphrases carry no checksum, so a mistyped passphrase
12
- * silently opens a different, valid, EMPTY vault. Hence the confirm field.
13
- *
14
- * Colour discipline: chroma here is STATUS (the meter), never an action. The
15
- * primary action keeps the achromatic accent fill, per the app's token pairing.
16
- */
17
- import React, { useMemo, useState } from 'react'
18
- import { View, Text, TextInput, StyleSheet, Pressable } from 'react-native'
19
- import PressableScale from '../ui/PressableScale'
20
- import { showToast } from '../ui/Toast'
21
- import {
22
- useTheme,
23
- spacing,
24
- radii,
25
- typography,
26
- passphraseStrength,
27
- generatePassphrase,
28
- normalizeVaultPassphrase,
29
- MINIMUM_WORD_COUNT,
30
- RECOMMENDED_WORD_COUNT,
31
- type PassphraseTier
32
- } from '@bsv/expo-wallet-toolbox'
33
-
34
- /**
35
- * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
36
- * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
37
- * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
38
- * Ionicons is loaded lazily, only when actually rendering, same pattern as
39
- * this package's other native-module-boundary fixes (expo-router, expo-blur).
40
- */
41
- type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
42
- let ioniconsComponent: IoniconsComponent | undefined
43
- function loadIonicons(): IoniconsComponent {
44
- if (!ioniconsComponent) {
45
- // eslint-disable-next-line @typescript-eslint/no-require-imports
46
- ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
47
- }
48
- return ioniconsComponent
49
- }
50
-
51
- /**
52
- * expo-clipboard ships an untransformed ESM build (its Clipboard.js imports
53
- * from expo-modules-core with a bare `import` statement) that Jest cannot
54
- * parse when eagerly pulled in via the `ui` package barrel. Required lazily,
55
- * only when a handler actually copies something, same pattern as this
56
- * package's other native-module-boundary fixes (@react-native-clipboard,
57
- * expo-router, expo-blur).
58
- */
59
- type ExpoClipboardModule = typeof import('expo-clipboard')
60
- let expoClipboardModule: ExpoClipboardModule | undefined
61
- function loadExpoClipboard(): ExpoClipboardModule {
62
- if (!expoClipboardModule) {
63
- // eslint-disable-next-line @typescript-eslint/no-require-imports
64
- expoClipboardModule = require('expo-clipboard') as ExpoClipboardModule
65
- }
66
- return expoClipboardModule
67
- }
68
-
69
- export interface PassphraseFieldProps {
70
- value: string
71
- onChangeText: (v: string) => void
72
- confirm: string
73
- onChangeConfirm: (v: string) => void
74
- /** Called with the normalised passphrase whenever validity changes. */
75
- onValidityChange?: (ok: boolean) => void
76
- }
77
-
78
- /** Meter colour by tier. Status chroma only — never used for actions. */
79
- function tierColor(tier: PassphraseTier, colors: Record<string, string>): string {
80
- switch (tier) {
81
- case 'empty':
82
- return colors.separator
83
- case 'weak':
84
- return colors.error
85
- case 'fair':
86
- return colors.warning
87
- default:
88
- return colors.success
89
- }
90
- }
91
-
92
- const TIER_LABEL: Record<PassphraseTier, string> = {
93
- empty: '',
94
- weak: 'Too weak',
95
- fair: 'Still too weak',
96
- strong: 'Strong',
97
- excellent: 'Excellent'
98
- }
99
-
100
- export function PassphraseField({
101
- value,
102
- onChangeText,
103
- confirm,
104
- onChangeConfirm,
105
- onValidityChange
106
- }: PassphraseFieldProps) {
107
- const { colors } = useTheme()
108
- const [reveal, setReveal] = useState(false)
109
- const Ionicons = loadIonicons()
110
-
111
- const strength = useMemo(() => passphraseStrength(value), [value])
112
- // Compare normalised, so a stray trailing space is not reported as a
113
- // mismatch when BIP39 would treat both the same after our normalisation.
114
- const confirmed =
115
- confirm.length > 0 && normalizeVaultPassphrase(confirm) === normalizeVaultPassphrase(value)
116
- const mismatch = confirm.length > 0 && !confirmed
117
- const ok = strength.ok && confirmed
118
-
119
- React.useEffect(() => {
120
- onValidityChange?.(ok)
121
- }, [ok, onValidityChange])
122
-
123
- const onGenerate = () => {
124
- const generated = generatePassphrase()
125
- onChangeText(generated)
126
- onChangeConfirm(generated)
127
- setReveal(true) // they must be able to read what they now have to keep
128
- }
129
-
130
- const onCopy = async () => {
131
- await loadExpoClipboard().setStringAsync(value)
132
- showToast('Passphrase copied', { type: 'info' })
133
- }
134
-
135
- const meterColor = tierColor(strength.tier, colors as unknown as Record<string, string>)
136
-
137
- return (
138
- <View style={styles.wrap}>
139
- {/* ── passphrase ─────────────────────────────────────────────── */}
140
- <View
141
- style={[
142
- styles.field,
143
- { backgroundColor: colors.backgroundElevated, borderColor: colors.separator }
144
- ]}
145
- >
146
- <TextInput
147
- value={value}
148
- onChangeText={onChangeText}
149
- secureTextEntry={!reveal}
150
- autoCapitalize="none"
151
- autoCorrect={false}
152
- spellCheck={false}
153
- // A password manager offering to save this is fine, but iOS strong-
154
- // password suggestions would propose a short random string, which is
155
- // exactly the wrong shape for a 2048-round KDF.
156
- textContentType="none"
157
- style={[styles.input, { color: colors.textPrimary }]}
158
- accessibilityLabel="Vault passphrase"
159
- />
160
- {value.length === 0 && (
161
- <Text
162
- pointerEvents="none"
163
- style={[styles.placeholder, { color: colors.textTertiary }]}
164
- >{`${MINIMUM_WORD_COUNT} or more random words`}</Text>
165
- )}
166
- <Pressable
167
- onPress={() => setReveal(r => !r)}
168
- hitSlop={8}
169
- accessibilityRole="button"
170
- accessibilityLabel={reveal ? 'Hide passphrase' : 'Show passphrase'}
171
- >
172
- <Ionicons name={reveal ? 'eye-off' : 'eye'} size={20} color={colors.textSecondary} />
173
- </Pressable>
174
- </View>
175
-
176
- {/* ── strength meter ─────────────────────────────────────────── */}
177
- <View style={styles.meterBlock}>
178
- <View style={[styles.meterTrack, { backgroundColor: colors.separator }]}>
179
- <View
180
- style={[
181
- styles.meterFill,
182
- { width: `${Math.round(strength.fraction * 100)}%`, backgroundColor: meterColor }
183
- ]}
184
- />
185
- </View>
186
- <View style={styles.meterRow}>
187
- <Text style={[styles.tier, { color: meterColor }]}>{TIER_LABEL[strength.tier]}</Text>
188
- {value.length > 0 && (
189
- <Text style={[styles.crack, { color: colors.textSecondary }]} numberOfLines={1}>
190
- Cracked in {strength.crackTime}
191
- </Text>
192
- )}
193
- </View>
194
- {value.length > 0 && !strength.ok && strength.reason && (
195
- <Text style={[styles.hint, { color: colors.textSecondary }]}>{strength.reason}</Text>
196
- )}
197
- </View>
198
-
199
- {/* ── generate ───────────────────────────────────────────────── */}
200
- <View style={styles.genRow}>
201
- <PressableScale
202
- haptic="confirm"
203
- onPress={onGenerate}
204
- style={[styles.ghost, { borderColor: colors.separator }]}
205
- >
206
- <Ionicons name="dice-outline" size={16} color={colors.info} />
207
- <Text style={[styles.ghostLabel, { color: colors.info }]}>
208
- Generate {RECOMMENDED_WORD_COUNT} random words
209
- </Text>
210
- </PressableScale>
211
- {value.length > 0 && (
212
- <PressableScale
213
- onPress={onCopy}
214
- style={[styles.ghost, { borderColor: colors.separator }]}
215
- >
216
- <Ionicons name="copy-outline" size={16} color={colors.info} />
217
- <Text style={[styles.ghostLabel, { color: colors.info }]}>Copy</Text>
218
- </PressableScale>
219
- )}
220
- </View>
221
-
222
- {/* ── confirm ────────────────────────────────────────────────── */}
223
- <View
224
- style={[
225
- styles.field,
226
- {
227
- backgroundColor: colors.backgroundElevated,
228
- borderColor: mismatch ? colors.error : colors.separator
229
- }
230
- ]}
231
- >
232
- <TextInput
233
- value={confirm}
234
- onChangeText={onChangeConfirm}
235
- secureTextEntry={!reveal}
236
- autoCapitalize="none"
237
- autoCorrect={false}
238
- spellCheck={false}
239
- textContentType="none"
240
- style={[styles.input, { color: colors.textPrimary }]}
241
- accessibilityLabel="Confirm vault passphrase"
242
- />
243
- {confirm.length === 0 && (
244
- <Text pointerEvents="none" style={[styles.placeholder, { color: colors.textTertiary }]}>
245
- Type it again
246
- </Text>
247
- )}
248
- {confirm.length > 0 && (
249
- <Ionicons
250
- name={confirmed ? 'checkmark-circle' : 'close-circle'}
251
- size={20}
252
- color={confirmed ? colors.success : colors.error}
253
- />
254
- )}
255
- </View>
256
- {mismatch && (
257
- <Text style={[styles.hint, { color: colors.error }]}>
258
- These do not match. A mistyped passphrase opens a different, empty vault — there is no way
259
- to detect it later.
260
- </Text>
261
- )}
262
- </View>
263
- )
264
- }
265
-
266
- const styles = StyleSheet.create({
267
- wrap: { gap: spacing.md },
268
- field: {
269
- flexDirection: 'row',
270
- alignItems: 'center',
271
- gap: spacing.sm,
272
- borderRadius: radii.md,
273
- borderWidth: StyleSheet.hairlineWidth,
274
- paddingHorizontal: spacing.lg,
275
- paddingVertical: spacing.md
276
- },
277
- input: { flex: 1, ...typography.body },
278
- // Sits exactly where the input's own text starts, so swapping between them
279
- // as the user types does not shift anything.
280
- placeholder: {
281
- ...typography.body,
282
- position: 'absolute',
283
- left: spacing.lg,
284
- right: spacing.lg
285
- },
286
- meterBlock: { gap: spacing.xs },
287
- meterTrack: { height: 4, borderRadius: 2, overflow: 'hidden' },
288
- meterFill: { height: 4, borderRadius: 2 },
289
- meterRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
290
- tier: { ...typography.footnote, fontWeight: '600' },
291
- crack: { ...typography.footnote, flexShrink: 1 },
292
- hint: { ...typography.footnote },
293
- genRow: { flexDirection: 'row', gap: spacing.sm },
294
- ghost: {
295
- flexDirection: 'row',
296
- alignItems: 'center',
297
- gap: spacing.xs,
298
- borderRadius: radii.md,
299
- borderWidth: StyleSheet.hairlineWidth,
300
- paddingHorizontal: spacing.md,
301
- paddingVertical: spacing.sm
302
- },
303
- ghostLabel: { ...typography.footnote, fontWeight: '600' }
304
- })
305
-
306
- export default PassphraseField