@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,46 @@
1
+ /**
2
+ * The process-wide ceremony singleton.
3
+ *
4
+ * Constructed once against the live driver + store so the vault transfer flow
5
+ * and the React vault context drive the SAME ceremony. Kept out of any React
6
+ * module so importing it never pulls in the component graph.
7
+ */
8
+ import { CeremonyController, VaultKeyHandle, VaultProgress } from './ceremony'
9
+ import { getVaultDriver } from './driver'
10
+ import { vaultStore } from './vaultStore'
11
+
12
+ /** How long an armed session stays usable before it relocks — and, since the
13
+ * ceremony now holds the unwrapped vault key rather than a signing session,
14
+ * how long that key may live in memory. */
15
+ export const VAULT_RETENTION_MS = 120_000
16
+
17
+ export const ceremony = new CeremonyController({
18
+ getDriver: getVaultDriver,
19
+ store: {
20
+ // Only what the ceremony needs to run the tap: which slot to talk to and
21
+ // which card is allowed to answer. v4 meta holds no key material at all —
22
+ // everything spendable lives inside the seal.
23
+ getMeta: async () => {
24
+ const m = await vaultStore.getMeta()
25
+ return m ? { slot: m.slot, yubiSerial: m.yubiSerial } : null
26
+ },
27
+ getSeal: () => vaultStore.getSeal()
28
+ },
29
+ retentionMs: VAULT_RETENTION_MS
30
+ })
31
+
32
+ /** Tap the YubiKey to unwrap the vault key for one operation. Callers MUST
33
+ * release() in a finally — that is what drops the key and dismisses the NFC
34
+ * sheet. */
35
+ export function requestVaultKey(reason: string): Promise<VaultKeyHandle> {
36
+ return ceremony.requestKey(reason)
37
+ }
38
+
39
+ /** Report post-arm progress (preparing / broadcasting) so the ceremony sheet
40
+ * can show activity through the seconds-long stretches where the JS thread or
41
+ * the network is busy, and so the retention window tracks a live operation
42
+ * instead of expiring underneath it. A no-op when nothing is armed, which is
43
+ * what keeps the K1 recovery sweep from raising a sheet. */
44
+ export function noteVaultProgress(p: VaultProgress): void {
45
+ ceremony.noteProgress(p)
46
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * DEV-only convenience: run the whole vault stack against the software mock
3
+ * YubiKey without hardware. Toggled from wallet-config (DEV builds only).
4
+ *
5
+ * In-session only — installs a MockYubiKey with a key already "inserted" and
6
+ * a non-default PIN so enrollment does not force a PIN change. Clearing it
7
+ * reverts getVaultDriver() to null (or the real native module, if present).
8
+ * Kept in its own module so driver.ts never imports the mock.
9
+ */
10
+ import { setMockDriver } from './driver'
11
+ import { MockYubiKey } from './mockYubiKey'
12
+
13
+ export function setMockDriverEnabled(on: boolean): void {
14
+ if (on) {
15
+ const mock = new MockYubiKey()
16
+ mock.setPin('123456')
17
+ mock.insertKey('MOCK-DEV-1')
18
+ setMockDriver(mock)
19
+ } else {
20
+ setMockDriver(null)
21
+ }
22
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The single hardware surface the rest of the vault talks to.
3
+ *
4
+ * `VaultDriver` is deliberately declared here structurally (not imported from
5
+ * the native package) so the entire TS layer — ceremony, service, tests —
6
+ * compiles and runs without the `react-native-yubikey` native module resolving.
7
+ * The real driver is a thin adapter over that module's JSON-string API; the
8
+ * mock is a software implementation with test controls.
9
+ *
10
+ * Selection order: real native module > injected mock (DEV) > null. Null means
11
+ * "no YubiKey capability on this device", and every caller treats it as such —
12
+ * the vault UI hides, exactly like localpay's getLocalPayTransport() null path.
13
+ */
14
+ import { Platform } from 'react-native'
15
+ import { vaultErrorFromNative } from './types'
16
+
17
+ export interface KeyEvent {
18
+ type: 'attached' | 'detached' | 'session-failed'
19
+ serial?: string
20
+ transport: 'usb' | 'nfc' | 'mock'
21
+ /** session-failed only: why the session ended before any key connected.
22
+ * 'user-cancelled' = the user dismissed the system NFC sheet; 'no-key' =
23
+ * the session timed out or died without a key ever being presented. */
24
+ code?: 'user-cancelled' | 'no-key'
25
+ }
26
+
27
+ export interface VaultDriver {
28
+ isSupported(): boolean
29
+ /** True when the transport is a modal per-ceremony session (iOS NFC: start()
30
+ * shows the scan sheet, stop() dismisses it) rather than a persistent reader
31
+ * (Android USB, mock). Session-based drivers are started only when a ceremony
32
+ * begins — never at launch — and stopped when it arms or fails. */
33
+ sessionBased: boolean
34
+ start(): void
35
+ stop(): void
36
+ onKeyEvent(cb: (e: KeyEvent) => void): () => void
37
+ getKeyInfo(): Promise<{ serial: string; firmwareVersion: string; pinRetries: number }>
38
+ verifyPin(pin: string): Promise<{ ok: boolean; retriesLeft: number }>
39
+ changePin(oldPin: string, newPin: string): Promise<{ ok: boolean; retriesLeft: number }>
40
+ generateVaultKey(slot: number): Promise<{ publicKey: string }>
41
+ readVaultPublicKey(slot: number): Promise<{ publicKey: string } | null>
42
+ /** On-token ECDH (PIV KeyAgreement): derive the shared secret between the
43
+ * slot's P-256 key and a peer (ephemeral) public key. Returns the 32-byte
44
+ * x-coordinate as hex — the touch-gated step that unwraps a sealed vault
45
+ * key (see sealing.ts's seal/unseal pair). TOUCH-gated, PIN-gated. */
46
+ ecdh(slot: number, pin: string, peerPublicKey: string): Promise<{ secret: string }>
47
+ /** Sign a pre-computed 32-byte digest (64 hex chars) with the slot's P-256
48
+ * key. Returns a DER signature as hex. TOUCH-gated, PIN-gated. */
49
+ signEcdsa(slot: number, pin: string, digest: string): Promise<{ signature: string }>
50
+ }
51
+
52
+ /** Shape of the native Nitro module (JSON-string API). Kept local so a missing
53
+ * package never breaks the type-check. */
54
+ interface NativeYubiKeyPiv {
55
+ isSupported(): boolean
56
+ startDiscovery(): void
57
+ stopDiscovery(): void
58
+ setKeyListener(listener: (eventType: string, serial: string, transport: string) => void): void
59
+ clearKeyListener(): void
60
+ getKeyInfo(): Promise<string>
61
+ verifyPin(pin: string): Promise<string>
62
+ changePin(oldPin: string, newPin: string): Promise<string>
63
+ generateVaultKey(slot: number, touchPolicy: string, pinPolicy: string): Promise<string>
64
+ readVaultPublicKey(slot: number): Promise<string>
65
+ ecdh(slot: number, pin: string, peerPublicKey: string): Promise<string>
66
+ signEcdsa(slot: number, pin: string, digest: string): Promise<string>
67
+ }
68
+
69
+ let injectedMock: VaultDriver | null = null
70
+ let nativeCache: VaultDriver | null | undefined
71
+
72
+ /** DEV/test seam: force the mock (or clear it). */
73
+ export function setMockDriver(driver: VaultDriver | null): void {
74
+ injectedMock = driver
75
+ }
76
+
77
+ /** Normalize a native key event into the driver's vocabulary.
78
+ *
79
+ * The native modules emit `connected` / `removed` (iOS YubiKit + Android
80
+ * yubikit-android naming); the driver — and the mock, ceremony, and tests —
81
+ * speak `attached` / `detached`. Only an explicit connect is an attach; an
82
+ * explicit disconnect is a detach; anything unrecognized is treated as a
83
+ * detach (fail-safe: a stray event relocks rather than silently keeping the
84
+ * PKM armed). Getting this wrong makes insert read as detach and aborts the
85
+ * in-flight ceremony as `key-removed-mid-op`.
86
+ *
87
+ * `failed:<code>` is the native didFailConnectingNFC path — the session died
88
+ * BEFORE any key connected, so neither attach nor detach fits (a detach would
89
+ * misreport it as key-removed-mid-op). `<code>` is the CoreNFC invalidation
90
+ * code: 200 = the user pressed cancel on the system sheet, anything else
91
+ * (201 timeout, 202/203 system faults) = no key ever presented. */
92
+ export function mapNativeKeyEvent(eventType: string, serial: string, transport: string): KeyEvent {
93
+ const t = (transport as KeyEvent['transport']) || 'usb'
94
+ if (eventType === 'failed' || eventType.startsWith('failed:')) {
95
+ return {
96
+ type: 'session-failed',
97
+ code: eventType === 'failed:200' ? 'user-cancelled' : 'no-key',
98
+ serial: undefined,
99
+ transport: t
100
+ }
101
+ }
102
+ const attached = eventType === 'attached' || eventType === 'connected'
103
+ return {
104
+ type: attached ? 'attached' : 'detached',
105
+ serial: serial || undefined,
106
+ transport: t
107
+ }
108
+ }
109
+
110
+ /** Wrap the native module's JSON-string surface as a VaultDriver. */
111
+ function adaptNative(native: NativeYubiKeyPiv): VaultDriver {
112
+ const parse = async <T>(p: Promise<string>): Promise<T> => {
113
+ try {
114
+ return JSON.parse(await p) as T
115
+ } catch (e) {
116
+ throw vaultErrorFromNative(e)
117
+ }
118
+ }
119
+ const listeners = new Set<(e: KeyEvent) => void>()
120
+ return {
121
+ isSupported: () => native.isSupported(),
122
+ // iOS = NFC (a modal per-tap session); Android = persistent USB reader.
123
+ sessionBased: Platform.OS === 'ios',
124
+ start: () => {
125
+ // (Re)install the native listener each start; it forwards into the
126
+ // persistent JS `listeners` set so app subscribers survive stop/start
127
+ // cycles (a session-based transport starts and stops per ceremony).
128
+ native.setKeyListener((eventType, serial, transport) => {
129
+ const e = mapNativeKeyEvent(eventType, serial, transport)
130
+ listeners.forEach(cb => cb(e))
131
+ })
132
+ try {
133
+ native.startDiscovery()
134
+ } catch (e) {
135
+ // iOS throws VAULT_ERR:driver-unavailable when NFC reading is
136
+ // unavailable (NFC off, or a wedged nfcd needing a device restart)
137
+ // rather than silently not presenting the scan sheet.
138
+ throw vaultErrorFromNative(e)
139
+ }
140
+ },
141
+ stop: () => {
142
+ native.stopDiscovery()
143
+ native.clearKeyListener()
144
+ // NOTE: do NOT clear `listeners` — app subscribers (WalletContext) stay
145
+ // subscribed across ceremony sessions.
146
+ },
147
+ onKeyEvent: cb => {
148
+ listeners.add(cb)
149
+ return () => listeners.delete(cb)
150
+ },
151
+ getKeyInfo: () => parse(native.getKeyInfo()),
152
+ verifyPin: pin => parse(native.verifyPin(pin)),
153
+ changePin: (o, n) => parse(native.changePin(o, n)),
154
+ // 'always' (not 'cached'): the YubiKey is now an ECDH unwrap oracle — one
155
+ // on-token ECDH per ceremony recovers the vault key, then every vault
156
+ // input signs in software from that recovered key, so there's no longer
157
+ // a per-input touch to spare. A single per-op touch is affordable and is
158
+ // the stronger policy (no cached-touch window an attacker with a stolen,
159
+ // still-inserted key could ride). Existing enrolled keys keep whatever
160
+ // policy they were generated under — this only affects new enrollments.
161
+ generateVaultKey: slot => parse(native.generateVaultKey(slot, 'always', 'once')),
162
+ readVaultPublicKey: async slot => {
163
+ const r = await parse<{ publicKey: string | null }>(native.readVaultPublicKey(slot))
164
+ return r.publicKey ? { publicKey: r.publicKey } : null
165
+ },
166
+ ecdh: (slot, pin, peer) => parse(native.ecdh(slot, pin, peer)),
167
+ signEcdsa: (slot, pin, digest) => parse(native.signEcdsa(slot, pin, digest))
168
+ }
169
+ }
170
+
171
+ function loadNative(): VaultDriver | null {
172
+ if (nativeCache !== undefined) return nativeCache
173
+ try {
174
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
175
+ const mod = require('react-native-yubikey') as { getYubiKeyPiv?: () => NativeYubiKeyPiv | null }
176
+ const native = mod.getYubiKeyPiv?.() ?? null
177
+ nativeCache = native ? adaptNative(native) : null
178
+ } catch {
179
+ nativeCache = null
180
+ }
181
+ return nativeCache
182
+ }
183
+
184
+ /**
185
+ * The active driver: an injected mock if one is installed, else native, else
186
+ * null.
187
+ *
188
+ * The mock wins deliberately. It is only ever installed by the DEV-gated
189
+ * "Use mock YubiKey" toggle, and on a simulator the native module DOES
190
+ * resolve — it simply reports isSupported() === false. Native-first therefore
191
+ * made that toggle a no-op on exactly the device it exists for: the vault
192
+ * screen kept saying "needs a YubiKey" with the mock switched on.
193
+ */
194
+ export function getVaultDriver(): VaultDriver | null {
195
+ if (injectedMock) return injectedMock
196
+ return loadNative()
197
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Vault access guard (fixes the privilege-escalation review finding).
3
+ *
4
+ * PrivilegedKeyManager's key universe is the wallet's master HD root key — a
5
+ * strictly more sensitive key than the per-app `primaryKey` (m/0'/0') that
6
+ * every ordinary, non-privileged operation signs with. That is true whether
7
+ * or not a vault is enrolled: the vault does not route through this manager
8
+ * at all (vault inputs are signed from the vault's own HD node — the
9
+ * YubiKey-unwrapped seed, equivalently derived from the main mnemonic plus a
10
+ * vault passphrase that the root key cannot reach, since BIP39's `toSeed` is
11
+ * one-way and passphrase-dependent). The toolbox routes every
12
+ * BRC-100 `privileged: true` op through PrivilegedKeyManager regardless, and
13
+ * this app runs with `seekProtocolPermissionsForSigning` / public-key-
14
+ * revelation permissions OFF, so nothing else gates them. That let any web
15
+ * origin, via the CWI bridge, use `getPublicKey({ privileged: true, ... })`,
16
+ * `createSignature`, `encrypt`/`decrypt`, or HMAC ops to reveal or sign with
17
+ * the root key — none of which are spend actions, so none of them ever trip
18
+ * the spending-authorization sheet.
19
+ *
20
+ * Blocking privileged ops for external originators is what closes that
21
+ * exposure: it is the only thing standing between a web page and the root
22
+ * key, now that the keyGetter itself no longer discriminates by enrollment
23
+ * or caller. (It is not what keeps the YubiKey ceremony admin-only — that
24
+ * follows separately, because nothing outside `services/vault` ever calls
25
+ * `requestVaultKey`/`ceremony.requestKey` in the first place; a page
26
+ * cannot reach the ceremony through this guarded surface even in principle,
27
+ * privileged or not.)
28
+ *
29
+ * Privileged operations have never been used by external origins in this app
30
+ * (the keyGetter has only ever returned the root key with no ceremony and no
31
+ * web caller — first because there was no vault, now because the vault no
32
+ * longer routes through it either), so denying them breaks nothing real.
33
+ */
34
+ import type { WalletInterface } from '@bsv/sdk'
35
+
36
+ /** BRC-100 methods that accept `privileged: true` and would return / use
37
+ * privileged (root) key material. */
38
+ const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
39
+ 'getPublicKey',
40
+ 'revealCounterpartyKeyLinkage',
41
+ 'revealSpecificKeyLinkage',
42
+ 'encrypt',
43
+ 'decrypt',
44
+ 'createHmac',
45
+ 'verifyHmac',
46
+ 'createSignature',
47
+ 'verifySignature',
48
+ // Certificate ops thread `privileged` straight into the underlying wallet
49
+ // too: acquireCertificate's 'direct' branch calls getPublicKey({
50
+ // identityKey: true, privileged, privilegedReason }) on the unwrapped
51
+ // wallet, and proveCertificate threads privileged into
52
+ // MasterCertificate.createKeyringForVerifier. Omitting these left a hole
53
+ // to the same root key the other entries above are here to block.
54
+ 'acquireCertificate',
55
+ 'proveCertificate',
56
+ 'listCertificates'
57
+ ])
58
+
59
+ export class VaultAccessDenied extends Error {
60
+ constructor(method: string, originator: string) {
61
+ super(`Privileged operation "${method}" is not permitted for origin "${originator || 'unknown'}"`)
62
+ this.name = 'VaultAccessDenied'
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Wrap a wallet so that `privileged: true` operations from any originator other
68
+ * than `adminOriginator` are rejected. All other calls pass straight through.
69
+ * Apply this to the wallet handed to EXTERNAL callers (the in-tab CWI bridge and
70
+ * the desktop-pairing WalletClient); the vault's own UI keeps calling the
71
+ * unwrapped permissions manager with the admin originator.
72
+ */
73
+ export function guardVaultAccess<T extends WalletInterface>(wallet: T, adminOriginator: string): T {
74
+ return new Proxy(wallet, {
75
+ get(target, prop, receiver) {
76
+ const value = Reflect.get(target, prop, receiver)
77
+ if (typeof value !== 'function' || !PRIVILEGED_CAPABLE.has(prop as keyof WalletInterface)) {
78
+ return typeof value === 'function' ? value.bind(target) : value
79
+ }
80
+ const bound = (value as (a: unknown, o?: string) => unknown).bind(target)
81
+ return (args: unknown, originator?: string) => {
82
+ const privileged = !!(args && typeof args === 'object' && (args as { privileged?: boolean }).privileged)
83
+ if (privileged && originator !== adminOriginator) {
84
+ return Promise.reject(new VaultAccessDenied(String(prop), originator ?? ''))
85
+ }
86
+ return bound(args, originator)
87
+ }
88
+ }
89
+ })
90
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The K1 vault script: byte-length constants, the customInstructions codec,
3
+ * and locking-script construction.
4
+ *
5
+ * Every K1 detail lives here so no other module needs to know the template's
6
+ * shape. A K1 vault output is a plain P2PKH output — no R1/YubiKey leg, no
7
+ * template contract — locked to a BIP32 child key derived per
8
+ * services/vault/vaultDerivation.ts.
9
+ *
10
+ * SECURITY: nothing secret passes through this module — only public keys,
11
+ * hashes, and script bytes.
12
+ */
13
+ import { LockingScript, P2PKH } from '@bsv/sdk'
14
+
15
+ /** Exact: a P2PKH locking script is always
16
+ * OP_DUP OP_HASH160 push(20) OP_EQUALVERIFY OP_CHECKSIG = 1+1+1+20+1+1 = 25 bytes. */
17
+ export const K1_LOCK_LEN = 25
18
+
19
+ /** Conservative estimate, not exact: a real P2PKH unlock measures ~107 bytes
20
+ * (push(≤72-byte DER sig) + push(33-byte compressed pubkey)), matching the
21
+ * staging-unlock shape the legacy reclaim still builds (see transfers.ts's
22
+ * reclaimStagingOutputs). DER signatures
23
+ * vary between 70 and 72 bytes, so this pins the ceiling rather than the
24
+ * exact length. */
25
+ export const K1_UNLOCK_LEN = 108
26
+
27
+ /**
28
+ * What a K1 vault output records about itself.
29
+ *
30
+ * `v` is the customInstructions format version and is a hard fork from the
31
+ * old template-based line: v2 records carry a different type discriminator
32
+ * entirely and must never decode as v3 — see decodeVaultInstructions.
33
+ */
34
+ export interface VaultInstructions {
35
+ v: 3
36
+ type: 'K1'
37
+ /** BIP32 child key ID, e.g. 'bip32/7'. See vaultDerivation.ts's
38
+ * BIP32_KEYID_PREFIX / bip32KeyID. */
39
+ keyID: string
40
+ }
41
+
42
+ export function encodeVaultInstructions(i: VaultInstructions): string {
43
+ return JSON.stringify(i)
44
+ }
45
+
46
+ /**
47
+ * Parse an output's customInstructions, or null if it is not a well-formed
48
+ * K1 v3 record.
49
+ *
50
+ * Fails closed on anything unrecognised — including old v2 R1-K1 records —
51
+ * because a malformed record means an output we cannot construct a valid
52
+ * spend for, and silently dropping it from the spendable set beats building
53
+ * a transaction that cannot be signed.
54
+ */
55
+ export function decodeVaultInstructions(ci?: string): VaultInstructions | null {
56
+ if (!ci) return null
57
+ let parsed: unknown
58
+ try {
59
+ parsed = JSON.parse(ci)
60
+ } catch {
61
+ return null
62
+ }
63
+ if (!parsed || typeof parsed !== 'object') return null
64
+ const p = parsed as Partial<VaultInstructions>
65
+ if (p.v !== 3 || p.type !== 'K1') return null
66
+ if (typeof p.keyID !== 'string' || !p.keyID.startsWith('bip32/')) return null
67
+ return { v: 3, type: 'K1', keyID: p.keyID }
68
+ }
69
+
70
+ /** Build a K1 vault locking script: a plain P2PKH lock to the given public
71
+ * key hash. Synchronous — there is no template to await; callers may still
72
+ * `await` this without effect. */
73
+ export function buildVaultLockingScript(a: { k1PublicKeyHash: number[] }): LockingScript {
74
+ return new P2PKH().lock(a.k1PublicKeyHash)
75
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Software YubiKey for development and tests.
3
+ *
4
+ * Implements VaultDriver against an in-memory P-256 keypair, emulating the
5
+ * behaviours the real ceremony must survive: PIN retries and lockout, touch
6
+ * timeouts, and key removal mid-operation. ecdh mirrors the token's PIV
7
+ * KeyAgreement (32-byte x-coordinate) so a seal produced against the mock's
8
+ * public key unseals through the mock; signEcdsa emits DER exactly like both
9
+ * real platforms. Together they let the whole vault stack run end-to-end
10
+ * without hardware.
11
+ *
12
+ * DEV/test only. Never bundled into a path a production user reaches.
13
+ */
14
+ import { p256 } from '@noble/curves/nist.js'
15
+ import { Utils } from '@bsv/sdk'
16
+ import { VaultDriver, KeyEvent } from './driver'
17
+ import { softwareEcdh } from './sealing'
18
+ import { VaultError } from './types'
19
+
20
+ type TouchBehavior = 'instant' | 'timeout'
21
+
22
+ const DEFAULT_PIN = '123456'
23
+
24
+ export class MockYubiKey implements VaultDriver {
25
+ private listeners = new Set<(e: KeyEvent) => void>()
26
+ private present = false
27
+ private serial = 'MOCK-1'
28
+ private pin = DEFAULT_PIN
29
+ private pinRetries = 3
30
+ private pinVerified = false
31
+ private touch: TouchBehavior = 'instant'
32
+ private slotPriv: Uint8Array | null = null
33
+ private slotPub: string | null = null
34
+
35
+ // ---- test controls ---------------------------------------------------
36
+ insertKey(serial = 'MOCK-1'): void {
37
+ this.serial = serial
38
+ this.present = true
39
+ this.pinRetries = 3
40
+ this.pinVerified = false
41
+ this.emit({ type: 'attached', serial, transport: 'mock' })
42
+ }
43
+
44
+ removeKey(): void {
45
+ if (!this.present) return
46
+ const serial = this.serial
47
+ this.present = false
48
+ this.pinVerified = false
49
+ this.emit({ type: 'detached', serial, transport: 'mock' })
50
+ }
51
+
52
+ setTouchBehavior(b: TouchBehavior): void {
53
+ this.touch = b
54
+ }
55
+
56
+ setPin(pin: string): void {
57
+ this.pin = pin
58
+ }
59
+
60
+ /** Simulate the NFC session dying before any key connected — the system
61
+ * scan sheet being cancelled (user-cancelled) or timing out / failing to
62
+ * present (no-key). Mirrors the real adapter's `failed:<code>` events from
63
+ * the native didFailConnectingNFC handler. */
64
+ failSession(code: 'user-cancelled' | 'no-key'): void {
65
+ this.emit({ type: 'session-failed', code, transport: 'mock' })
66
+ }
67
+
68
+ /** Simulate a slot that already holds a key (e.g. an age-plugin-yubikey
69
+ * identity in retired slot 82), so readVaultPublicKey reports it occupied
70
+ * before any generate. */
71
+ occupySlot(): void {
72
+ this.slotPriv = p256.utils.randomSecretKey()
73
+ this.slotPub = Utils.toHex(Array.from(p256.getPublicKey(this.slotPriv, false)))
74
+ }
75
+
76
+ // ---- VaultDriver -----------------------------------------------------
77
+ isSupported(): boolean {
78
+ return true
79
+ }
80
+
81
+ /** The mock behaves like a persistent reader (insert/remove under test). */
82
+ sessionBased = false
83
+
84
+ start(): void {
85
+ // Session-based flows (NFC) call start() to open a scan session and wait
86
+ // for the tap to connect. Simulate that: if a key is "held", emit attached
87
+ // now. Persistent flows never rely on this (they see the key via getKeyInfo).
88
+ if (this.sessionBased && this.present) {
89
+ this.emit({ type: 'attached', serial: this.serial, transport: 'mock' })
90
+ }
91
+ }
92
+
93
+ stop(): void {
94
+ // Matches the real adapter's contract (driver.ts adaptNative.stop): do NOT
95
+ // clear listeners. App subscribers (WalletContext, and now the ceremony's
96
+ // own mid-flight NFC retry loop) stay subscribed across a session-based
97
+ // transport's stop/start cycles. Clearing here would silently break any
98
+ // ceremony that calls stop() and then start() again on the SAME run (e.g.
99
+ // reopening a fresh NFC session after a dropped tap) — its own attach
100
+ // listener, registered once at the top of that run, would be gone.
101
+ }
102
+
103
+ onKeyEvent(cb: (e: KeyEvent) => void): () => void {
104
+ this.listeners.add(cb)
105
+ return () => this.listeners.delete(cb)
106
+ }
107
+
108
+ async getKeyInfo(): Promise<{ serial: string; firmwareVersion: string; pinRetries: number }> {
109
+ this.requirePresent()
110
+ return { serial: this.serial, firmwareVersion: '5.7.1', pinRetries: this.pinRetries }
111
+ }
112
+
113
+ async verifyPin(pin: string): Promise<{ ok: boolean; retriesLeft: number }> {
114
+ this.requirePresent()
115
+ if (this.pinRetries <= 0) throw new VaultError('pin-locked', 'PIN is blocked')
116
+ if (pin === this.pin) {
117
+ this.pinRetries = 3
118
+ this.pinVerified = true
119
+ return { ok: true, retriesLeft: 3 }
120
+ }
121
+ this.pinRetries -= 1
122
+ this.pinVerified = false
123
+ return { ok: false, retriesLeft: this.pinRetries }
124
+ }
125
+
126
+ async changePin(oldPin: string, newPin: string): Promise<{ ok: boolean; retriesLeft: number }> {
127
+ this.requirePresent()
128
+ if (this.pinRetries <= 0) throw new VaultError('pin-locked', 'PIN is blocked')
129
+ if (oldPin !== this.pin) {
130
+ this.pinRetries -= 1
131
+ throw new VaultError('pin-invalid', 'Wrong PIN', this.pinRetries)
132
+ }
133
+ this.pin = newPin
134
+ this.pinRetries = 3
135
+ return { ok: true, retriesLeft: 3 }
136
+ }
137
+
138
+ async generateVaultKey(_slot: number): Promise<{ publicKey: string }> {
139
+ this.requirePresent()
140
+ this.slotPriv = p256.utils.randomSecretKey()
141
+ this.slotPub = Utils.toHex(Array.from(p256.getPublicKey(this.slotPriv, false)))
142
+ return { publicKey: this.slotPub }
143
+ }
144
+
145
+ async readVaultPublicKey(_slot: number): Promise<{ publicKey: string } | null> {
146
+ this.requirePresent()
147
+ return this.slotPub ? { publicKey: this.slotPub } : null
148
+ }
149
+
150
+ /** Software stand-in for the card's PIV KeyAgreement (on-token ECDH) — the
151
+ * touch-gated step that unwraps a sealed vault key (sealing.ts).
152
+ *
153
+ * pinPolicy=once: a prior verifyPin in this "session" satisfies it; if a
154
+ * PIN is supplied here and not yet verified, verify it inline — and check
155
+ * the result. A verifyPin call can fail (wrong PIN) without throwing; only
156
+ * a locked PIN throws. Discarding that `{ ok: false }` and proceeding
157
+ * anyway would make a wrong PIN indistinguishable from a correct one —
158
+ * the same trap signEcdsa's inline verify once fell into.
159
+ */
160
+ async ecdh(_slot: number, pin: string, peerPublicKey: string): Promise<{ secret: string }> {
161
+ this.requirePresent()
162
+ if (!this.pinVerified) {
163
+ if (!pin) throw new VaultError('pin-required', 'PIN required before ECDH')
164
+ const res = await this.verifyPin(pin)
165
+ if (!res.ok) throw new VaultError('pin-invalid', 'Wrong PIN', res.retriesLeft)
166
+ }
167
+ if (!this.slotPriv) throw new VaultError('no-key', 'No key in slot')
168
+ if (this.touch === 'timeout') throw new VaultError('touch-timeout', 'Touch not detected')
169
+
170
+ const secret = softwareEcdh(Utils.toHex(Array.from(this.slotPriv)), peerPublicKey)
171
+ return { secret }
172
+ }
173
+
174
+ /** Software stand-in for the card's GENERAL AUTHENTICATE.
175
+ *
176
+ * Emits DER, exactly like both real platforms, so a DER-parsing bug cannot
177
+ * hide behind the mock. Enforces the same 32-byte digest rule the native
178
+ * modules do — on iOS an unrecognised algorithm constant silently signs 32
179
+ * ZERO bytes, and on Android an over-long payload is silently truncated, so
180
+ * this check is load-bearing, not decorative.
181
+ *
182
+ * `lowS: false` is passed explicitly: @noble/curves defaults P-256 signing
183
+ * to low-S normalisation, but real YubiKey PIV hardware does not normalise
184
+ * — roughly half of real signatures are high-S. A mock that only ever
185
+ * emitted low-S signatures could not catch downstream code that mishandles
186
+ * a non-canonical signature; that failure would first appear against real
187
+ * hardware, exactly the scenario this mock exists to prevent.
188
+ */
189
+ async signEcdsa(_slot: number, pin: string, digest: string): Promise<{ signature: string }> {
190
+ this.requirePresent()
191
+ if (!this.pinVerified) {
192
+ if (!pin) throw new VaultError('pin-required', 'PIN required before signing')
193
+ const res = await this.verifyPin(pin)
194
+ if (!res.ok) throw new VaultError('pin-invalid', 'Wrong PIN', res.retriesLeft)
195
+ }
196
+ if (!this.slotPriv) throw new VaultError('no-key', 'No key in slot')
197
+
198
+ const bytes = Utils.toArray(digest, 'hex')
199
+ if (bytes.length !== 32) {
200
+ throw new VaultError('template-invalid', `Digest must be 32 bytes, got ${bytes.length}`)
201
+ }
202
+ if (this.touch === 'timeout') throw new VaultError('touch-timeout', 'Touch not detected')
203
+
204
+ const raw = p256.sign(Uint8Array.from(bytes), this.slotPriv, { prehash: false, lowS: false })
205
+ const der = p256.Signature.fromBytes(raw).toBytes('der')
206
+ return { signature: Utils.toHex(Array.from(der)) }
207
+ }
208
+
209
+ // ---- internals -------------------------------------------------------
210
+ private requirePresent(): void {
211
+ if (!this.present) throw new VaultError('no-key', 'No YubiKey present')
212
+ }
213
+
214
+ private emit(e: KeyEvent): void {
215
+ this.listeners.forEach(cb => cb(e))
216
+ }
217
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Entropy for vault crypto. Prefers expo-crypto's native RNG; falls back to
3
+ * the WebCrypto global (present under Jest/Node) so pure-TS tests run without
4
+ * native modules. Throws rather than degrade to weak randomness.
5
+ */
6
+ export function randomBytes(length: number): number[] {
7
+ try {
8
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
9
+ const { getRandomBytes } = require('expo-crypto') as { getRandomBytes: (n: number) => Uint8Array }
10
+ return Array.from(getRandomBytes(length))
11
+ } catch {
12
+ const g = globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }
13
+ if (g.crypto?.getRandomValues) {
14
+ const out = new Uint8Array(length)
15
+ g.crypto.getRandomValues(out)
16
+ return Array.from(out)
17
+ }
18
+ throw new Error('No secure random source available')
19
+ }
20
+ }