@bsv/expo-wallet-toolbox 0.3.1 → 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 (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -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/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -5,6 +5,24 @@ import { WalletClient, PrivateKey, ProtoWallet, Utils } from '@bsv/sdk'
5
5
  import type { WalletProtocol } from '@bsv/sdk'
6
6
  import connectionStore from '../stores/ConnectionStore'
7
7
  import type { Connection } from '../stores/ConnectionStore'
8
+ import {
9
+ buildPairingSignatureMessage,
10
+ buildRelayWebSocketUrl,
11
+ MAX_IN_FLIGHT_RPC,
12
+ MAX_RELAY_RESPONSE_BYTES,
13
+ parseBoundedWireEnvelope,
14
+ parseRelayResponse,
15
+ requireBoundedPlaintext,
16
+ validateCanonicalExternalOrigin,
17
+ validateConnectParams,
18
+ validateBackendIdentityKey,
19
+ validatePairingTopic,
20
+ validateStoredConnectionSequence,
21
+ validateStoredConnectionFields,
22
+ type ConnectParams
23
+ } from '../services/walletConnectionValidation'
24
+
25
+ export type { ConnectParams } from '../services/walletConnectionValidation'
8
26
 
9
27
  // ── Constants ─────────────────────────────────────────────────────────────────
10
28
 
@@ -37,15 +55,6 @@ export interface SessionMeta {
37
55
  protocolID: WalletProtocol
38
56
  }
39
57
 
40
- export interface ConnectParams {
41
- topic: string
42
- backendIdentityKey: string
43
- protocolID: string // JSON-encoded WalletProtocol
44
- origin: string
45
- expiry?: string // Unix seconds — required for signature verification
46
- sig?: string // base64url DER ECDSA signature
47
- }
48
-
49
58
  interface WalletConnectionContextValue {
50
59
  status: ConnectionStatus
51
60
  sessionMeta: SessionMeta | null
@@ -80,15 +89,13 @@ async function decryptPayload(
80
89
  ): Promise<string> {
81
90
  const ciphertext = Array.from(Buffer.from(ciphertextB64, 'base64url'))
82
91
  const { plaintext } = await wallet.decrypt({ protocolID, keyID, counterparty, ciphertext })
83
- return new TextDecoder().decode(new Uint8Array(plaintext))
92
+ return new TextDecoder().decode(new Uint8Array(requireBoundedPlaintext(plaintext)))
84
93
  }
85
94
 
86
- async function verifyQrSignature(params: ConnectParams): Promise<void> {
95
+ async function verifyQrSignature(params: Required<ConnectParams>): Promise<void> {
87
96
  if (!params.sig) throw new Error('QR code is not signed — do not connect')
88
97
  const anyoneWallet = new ProtoWallet(new PrivateKey(1))
89
- const payload = Array.from(new TextEncoder().encode(
90
- `${params.topic}|${params.backendIdentityKey}|${params.origin}|${params.expiry}`
91
- ))
98
+ const payload = Array.from(new TextEncoder().encode(buildPairingSignatureMessage(params)))
92
99
  const signature = Utils.toArray(params.sig.replace(/-/g, '+').replace(/_/g, '/'), 'base64') as number[]
93
100
  const { valid } = await anyoneWallet.verifySignature({
94
101
  data: payload,
@@ -100,12 +107,63 @@ async function verifyQrSignature(params: ConnectParams): Promise<void> {
100
107
  if (!valid) throw new Error('QR code signature is invalid — do not connect')
101
108
  }
102
109
 
103
- async function fetchRelay(origin: string, topic: string): Promise<string> {
104
- const res = await fetch(`${origin}/api/session/${topic}`)
105
- if (!res.ok) throw new Error(`Could not fetch session from origin: HTTP ${res.status}`)
106
- const data = await res.json() as { relay?: string }
107
- if (!data.relay) throw new Error('Origin server did not return a relay URL')
108
- return data.relay
110
+ async function readBoundedRelayResponse(res: Response): Promise<string> {
111
+ const declared = res.headers.get('content-length')
112
+ if (declared !== null) {
113
+ if (!/^[0-9]+$/.test(declared) || Number(declared) > MAX_RELAY_RESPONSE_BYTES) {
114
+ throw new Error('Origin server relay response is too large')
115
+ }
116
+ }
117
+
118
+ // Modern React Native exposes a WHATWG response stream. Bound it while it is
119
+ // consumed; the fallback still validates before JSON.parse on runtimes whose
120
+ // fetch implementation exposes only text().
121
+ const reader = res.body?.getReader?.()
122
+ if (reader) {
123
+ const chunks: Uint8Array[] = []
124
+ let total = 0
125
+ for (;;) {
126
+ const { done, value } = await reader.read()
127
+ if (done) break
128
+ total += value.byteLength
129
+ if (total > MAX_RELAY_RESPONSE_BYTES) {
130
+ await reader.cancel().catch(() => {})
131
+ throw new Error('Origin server relay response is too large')
132
+ }
133
+ chunks.push(value)
134
+ }
135
+ const joined = new Uint8Array(total)
136
+ let offset = 0
137
+ for (const chunk of chunks) {
138
+ joined.set(chunk, offset)
139
+ offset += chunk.byteLength
140
+ }
141
+ return new TextDecoder().decode(joined)
142
+ }
143
+
144
+ const text = await res.text()
145
+ if (text.length > MAX_RELAY_RESPONSE_BYTES || new TextEncoder().encode(text).length > MAX_RELAY_RESPONSE_BYTES) {
146
+ throw new Error('Origin server relay response is too large')
147
+ }
148
+ return text
149
+ }
150
+
151
+ export async function fetchRelay(origin: string, topic: string): Promise<string> {
152
+ const validatedTopic = validatePairingTopic(topic)
153
+ const external = validateCanonicalExternalOrigin(origin)
154
+ const controller = new AbortController()
155
+ const timer = setTimeout(() => controller.abort(), 10_000)
156
+ try {
157
+ const res = await fetch(`${external.origin}/api/session/${encodeURIComponent(validatedTopic)}`, {
158
+ signal: controller.signal,
159
+ redirect: 'error'
160
+ })
161
+ if (!res.ok) throw new Error(`Could not fetch session from origin: HTTP ${res.status}`)
162
+ const raw = await readBoundedRelayResponse(res)
163
+ return parseRelayResponse(raw)
164
+ } finally {
165
+ clearTimeout(timer)
166
+ }
109
167
  }
110
168
 
111
169
  // ── Context ───────────────────────────────────────────────────────────────────
@@ -249,11 +307,16 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
249
307
  wsRef.current = ws
250
308
  lastSeqRef.current = initialSeq
251
309
  let firstMessageFired = false
310
+ let inFlightRpc = 0
252
311
 
253
312
  ws.onmessage = async event => {
313
+ if (inFlightRpc >= MAX_IN_FLIGHT_RPC) {
314
+ console.warn('[WalletConnection] dropping message: too many requests in flight')
315
+ return
316
+ }
317
+ inFlightRpc++
254
318
  try {
255
- const envelope = JSON.parse(event.data as string) as WireEnvelope
256
- if (!envelope.ciphertext) return
319
+ const envelope = parseBoundedWireEnvelope(event.data, meta.topic)
257
320
 
258
321
  let plaintext: string
259
322
  try {
@@ -266,11 +329,14 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
266
329
  }
267
330
 
268
331
  const msg = JSON.parse(plaintext) as RpcRequest | RpcResponse
269
- if (typeof msg.seq !== 'number' || msg.seq <= lastSeqRef.current) {
270
- console.warn('[WalletConnection] dropping message: seq', msg.seq, '<= lastSeq', lastSeqRef.current)
332
+ const sequence = msg !== null && typeof msg === 'object' && !Array.isArray(msg)
333
+ ? (msg as { seq?: unknown }).seq
334
+ : undefined
335
+ if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence <= lastSeqRef.current) {
336
+ console.warn('[WalletConnection] dropping message: seq', sequence, '<= lastSeq', lastSeqRef.current)
271
337
  return
272
338
  }
273
- lastSeqRef.current = msg.seq
339
+ lastSeqRef.current = sequence
274
340
 
275
341
  if (!firstMessageFired) {
276
342
  firstMessageFired = true
@@ -278,11 +344,14 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
278
344
  }
279
345
 
280
346
  if ('method' in msg && msg.method === 'pairing_ack') return
281
- if ('method' in msg && msg.id) {
282
- void handleRpc(msg as RpcRequest, meta, ws, wallet)
347
+ if ('method' in msg && typeof msg.method === 'string' &&
348
+ typeof msg.id === 'string' && msg.id.length > 0 && msg.id.length <= 128) {
349
+ await handleRpc(msg as RpcRequest, meta, ws, wallet)
283
350
  }
284
351
  } catch {
285
352
  // malformed outer envelope — drop silently
353
+ } finally {
354
+ inFlightRpc--
286
355
  }
287
356
  }
288
357
 
@@ -332,29 +401,34 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
332
401
  setErrorMsg(null)
333
402
 
334
403
  let relay: string
404
+ let validated: ReturnType<typeof validateConnectParams>
335
405
  try {
406
+ // This provider is a public embedding boundary. Validate every field here
407
+ // even when a host screen already parsed the QR.
408
+ validated = validateConnectParams(params)
336
409
  // Verify QR signature before trusting the origin or opening any connection
337
- await verifyQrSignature(params)
410
+ await verifyQrSignature(validated.params)
338
411
 
339
412
  // Fetch relay URL from origin over HTTPS — TLS cert is the trust anchor
340
- relay = await fetchRelay(params.origin, params.topic)
413
+ relay = await fetchRelay(validated.external.origin, validated.params.topic)
341
414
  } catch (err) {
342
415
  setErrorMsg(err instanceof Error ? err.message : 'Connection failed')
343
416
  setStatus('error')
344
417
  throw err
345
418
  }
346
419
 
347
- const protocolID = JSON.parse(params.protocolID) as WalletProtocol
348
- const { publicKey: mobileIdentityKey } = await wallet.getPublicKey({ identityKey: true })
420
+ const protocolID = validated.protocolID
421
+ const identityResult = await wallet.getPublicKey({ identityKey: true })
422
+ const mobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
349
423
 
350
424
  const meta: SessionMeta = {
351
- topic: params.topic, origin: params.origin, relay,
352
- backendIdentityKey: params.backendIdentityKey, mobileIdentityKey,
425
+ topic: validated.params.topic, origin: validated.external.origin, relay,
426
+ backendIdentityKey: validated.params.backendIdentityKey, mobileIdentityKey,
353
427
  protocolID,
354
428
  }
355
429
  setSessionMeta(meta)
356
430
 
357
- const ws = new WebSocket(`${relay}/ws?topic=${params.topic}&role=mobile`)
431
+ const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.params.topic))
358
432
 
359
433
  ws.onopen = async () => {
360
434
  try {
@@ -362,12 +436,15 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
362
436
  id: crypto.randomUUID(), seq: 1, method: 'pairing_approved',
363
437
  params: {
364
438
  mobileIdentityKey,
439
+ protocolID: validated.params.protocolID,
365
440
  walletMeta: { name: walletName, platform: 'mobile' },
366
441
  permissions: Array.from(IMPLEMENTED_METHODS),
367
442
  },
368
443
  })
369
- const ciphertext = await encryptPayload(wallet, protocolID, params.topic, params.backendIdentityKey, payload)
370
- ws.send(JSON.stringify({ topic: params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope))
444
+ const ciphertext = await encryptPayload(
445
+ wallet, protocolID, validated.params.topic, validated.params.backendIdentityKey, payload
446
+ )
447
+ ws.send(JSON.stringify({ topic: validated.params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope))
371
448
  } catch {
372
449
  setErrorMsg('Failed to send pairing message')
373
450
  setStatus('error')
@@ -376,9 +453,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
376
453
 
377
454
  wireSocket(ws, wallet, meta, 0, () => {
378
455
  connectionStore.add({
379
- sessionId: params.topic, origin: params.origin, relay,
380
- backendIdentityKey: params.backendIdentityKey, mobileIdentityKey,
381
- protocolID: params.protocolID,
456
+ sessionId: validated.params.topic, origin: validated.external.origin, relay,
457
+ backendIdentityKey: validated.params.backendIdentityKey, mobileIdentityKey,
458
+ protocolID: validated.params.protocolID,
382
459
  connectedAt: Date.now(), status: 'active',
383
460
  })
384
461
  setStatus('connected')
@@ -391,39 +468,47 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
391
468
  setStatus('connecting')
392
469
  setErrorMsg(null)
393
470
 
471
+ // Stored connection data is untrusted after import or database tampering.
472
+ const validated = validateStoredConnectionFields(connection)
473
+ const identityResult = await wallet.getPublicKey({ identityKey: true })
474
+ const currentMobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
475
+ if (currentMobileIdentityKey !== validated.mobileIdentityKey) {
476
+ throw new Error('Stored connection belongs to a different wallet identity')
477
+ }
394
478
  // Fetch relay URL from origin over HTTPS — relay may have moved since last connection
395
- const relay = await fetchRelay(connection.origin, connection.sessionId)
479
+ const relay = await fetchRelay(validated.external.origin, validated.topic)
396
480
 
397
- const protocolID = JSON.parse(connection.protocolID) as WalletProtocol
398
- const storedSeq = await SecureStore.getItemAsync(lastSeqKey(connection.sessionId))
399
- const initialSeq = storedSeq ? Number(storedSeq) : 0
481
+ const protocolID = validated.protocolID
482
+ const storedSeq = await SecureStore.getItemAsync(lastSeqKey(validated.topic))
483
+ const initialSeq = validateStoredConnectionSequence(storedSeq)
400
484
 
401
485
  const meta: SessionMeta = {
402
- topic: connection.sessionId, origin: connection.origin, relay,
403
- backendIdentityKey: connection.backendIdentityKey,
404
- mobileIdentityKey: connection.mobileIdentityKey,
486
+ topic: validated.topic, origin: validated.external.origin, relay,
487
+ backendIdentityKey: validated.backendIdentityKey,
488
+ mobileIdentityKey: validated.mobileIdentityKey,
405
489
  protocolID,
406
490
  }
407
491
  setSessionMeta(meta)
408
492
 
409
- const ws = new WebSocket(`${relay}/ws?topic=${connection.sessionId}&role=mobile`)
493
+ const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.topic))
410
494
 
411
495
  ws.onopen = async () => {
412
496
  try {
413
497
  const payload = JSON.stringify({
414
498
  id: crypto.randomUUID(), seq: initialSeq + 1, method: 'pairing_approved',
415
499
  params: {
416
- mobileIdentityKey: connection.mobileIdentityKey,
500
+ mobileIdentityKey: validated.mobileIdentityKey,
501
+ protocolID: validated.protocolIDRaw,
417
502
  walletMeta: { name: walletName, platform: 'mobile' },
418
503
  permissions: Array.from(IMPLEMENTED_METHODS),
419
504
  },
420
505
  })
421
506
  const ciphertext = await encryptPayload(
422
- wallet, protocolID, connection.sessionId, connection.backendIdentityKey, payload,
507
+ wallet, protocolID, validated.topic, validated.backendIdentityKey, payload,
423
508
  )
424
509
  ws.send(JSON.stringify({
425
- topic: connection.sessionId,
426
- mobileIdentityKey: connection.mobileIdentityKey,
510
+ topic: validated.topic,
511
+ mobileIdentityKey: validated.mobileIdentityKey,
427
512
  ciphertext,
428
513
  } satisfies WireEnvelope))
429
514
  } catch {
@@ -433,7 +518,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
433
518
  }
434
519
 
435
520
  wireSocket(ws, wallet, meta, initialSeq, () => {
436
- connectionStore.setStatus(connection.sessionId, 'active')
521
+ connectionStore.setStatus(validated.topic, 'active')
437
522
  setStatus('connected')
438
523
  })
439
524
  }, [walletName]) // eslint-disable-line react-hooks/exhaustive-deps