@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -23,7 +23,7 @@
23
23
  * and `makeBeefRepair` declines rather than burning an attempt on it.
24
24
  */
25
25
  import { Beef, Utils } from '@bsv/sdk'
26
- import type { WocConfig } from './rails/address'
26
+ import { MAX_HEX_RESPONSE_CHARS, type WocConfig } from './rails/address'
27
27
 
28
28
  /** Injectable for tests; production uses global fetch. */
29
29
  export type FetchLike = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>
@@ -53,7 +53,11 @@ export async function refetchAtomicBeef(args: {
53
53
  // a code path the user never asked for.
54
54
  if (!resp.ok) return undefined
55
55
  const hex = (await resp.text()).trim()
56
- if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return undefined
56
+ // XR-059: reject an oversized body before it is ever hex-decoded or
57
+ // merged into a Beef — a compromised/misbehaving indexer must not be able
58
+ // to force that work with an arbitrarily large response.
59
+ if (hex.length === 0 || hex.length > MAX_HEX_RESPONSE_CHARS || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex))
60
+ return undefined
57
61
  bytes = Utils.toArray(hex, 'hex')
58
62
  } catch {
59
63
  return undefined
@@ -1,3 +1,5 @@
1
+ import { limitsForTier } from '../services/walletArgLimits'
2
+
1
3
  export type DamagedInboxReason = 'unparseable' | 'bad_shape'
2
4
 
3
5
  export interface DamagedInboxMessage {
@@ -6,6 +8,22 @@ export interface DamagedInboxMessage {
6
8
  reason: DamagedInboxReason
7
9
  }
8
10
 
11
+ /**
12
+ * XR-047: a poisoned inbox message stays in the box indefinitely — nothing
13
+ * here acknowledges or removes it — and is re-fetched and re-shape-checked on
14
+ * every 5s `HandleReceive` poll and every background `TaskCreditInbox` pass.
15
+ * With no ceiling, a `transaction` array (or a derivation string) sized to the
16
+ * message-box client's own much larger limit could make every one of those
17
+ * passes do an expensive `.every()` scan, indefinitely, and could reach
18
+ * `wallet.internalizeAction` were it ever credited.
19
+ *
20
+ * `internalizeTx`/`customInstructions` (walletArgLimits.ts) do not vary by
21
+ * device tier — only `aggregate` does — so `'mid'` here is just a stable way
22
+ * to read those shared constants, not a device probe; this module stays pure
23
+ * and needs no device-tier context.
24
+ */
25
+ const LIMITS = limitsForTier('mid')
26
+
9
27
  /** True when body looks like a PeerPay payment token. */
10
28
  export function isPaymentTokenShape(body: unknown): boolean {
11
29
  if (body === null || typeof body !== 'object') return false
@@ -16,8 +34,14 @@ export function isPaymentTokenShape(body: unknown): boolean {
16
34
  derivationSuffix?: unknown
17
35
  }
18
36
  if (typeof derivationPrefix !== 'string' || typeof derivationSuffix !== 'string') return false
37
+ if (derivationPrefix.length > LIMITS.customInstructions || derivationSuffix.length > LIMITS.customInstructions) {
38
+ return false
39
+ }
19
40
  const transaction = (body as { transaction?: unknown }).transaction
20
41
  if (!Array.isArray(transaction)) return false
42
+ // Length check BEFORE the O(n) scan below: an oversized array must never
43
+ // pay for its own rejection on every poll.
44
+ if (transaction.length > LIMITS.internalizeTx) return false
21
45
  return transaction.every(n => typeof n === 'number')
22
46
  }
23
47
 
@@ -23,7 +23,7 @@ import {
23
23
  } from '@bsv/sdk'
24
24
  import type { AppChain } from '../../config'
25
25
  import { abbreviateKey, addressLabel, FROM_ADDRESS_LABEL_PREFIX, TO_ADDRESS_LABEL_PREFIX } from '../counterparty'
26
- import { isValidBsvAddress } from './index'
26
+ import { addressNetwork, isValidBsvAddress } from './index'
27
27
 
28
28
  export const BRC29_PROTOCOL_ID: WalletProtocol = [2, '3241645161d8']
29
29
 
@@ -56,7 +56,9 @@ export function addressRailAvailability(args: {
56
56
  recipientRefusal?: (recipient: string) => string | null
57
57
  }): AddressRailAvailability {
58
58
  if (args.assetId === undefined || args.assetId === '') {
59
- return isValidBsvAddress(args.address) ? { kind: 'available' } : { kind: 'unavailable', reason: 'Invalid BSV address' }
59
+ return isValidBsvAddress(args.address)
60
+ ? { kind: 'available' }
61
+ : { kind: 'unavailable', reason: 'Invalid BSV address' }
60
62
  }
61
63
  const reason = args.recipientRefusal?.(args.address)
62
64
  return {
@@ -92,6 +94,40 @@ export function derivationPrefixFor(date: string): string {
92
94
  return Utils.toBase64(Utils.toArray(date, 'utf8'))
93
95
  }
94
96
 
97
+ /**
98
+ * XR-055. Upper bound for the MANUAL recovery stepper only (AddressReceive.tsx) — distinct
99
+ * from MAX_RECOVERY_DAYS, which also bounds runWalletCheck's automatic bulk repair scan (see
100
+ * recoveryDatesToScan below) and stays small there because that scan makes one WhatsOnChain
101
+ * round trip per candidate day. Nothing in this codebase tracks a wallet-creation timestamp
102
+ * to bound the manual, one-address-at-a-time stepper by, so it uses a generous constant
103
+ * instead: comfortably longer than this project has existed, so a user with a genuinely old
104
+ * address is never blocked from reaching it by hand — the one recovery path that must keep
105
+ * working even on a device with no persisted issued-date history at all (a fresh import with
106
+ * no backup, so pay/receiveHistory.ts has nothing recorded).
107
+ */
108
+ export const MAX_MANUAL_RECOVERY_DAYS = 3650
109
+
110
+ /**
111
+ * Which calendar dates conventional-address recovery should try, given this device's durable
112
+ * issued-date history if it has one (pay/receiveHistory.ts, XR-055).
113
+ *
114
+ * The watchlist (pay/watchlist.ts) prunes by a 7-day calendar age no matter how recently it
115
+ * was swept, and the fixed MAX_RECOVERY_DAYS lookback below is itself only 30 days — so a
116
+ * payer who sat on a legitimately-displayed address for longer than either window had no
117
+ * shipped recovery path back to internalizeAction. Scanning every date this device has ever
118
+ * actually issued fixes that regardless of age, since sweepAddress is idempotent and cheap to
119
+ * retry for a date that turns out to hold nothing.
120
+ *
121
+ * Falls back to the previous fixed MAX_RECOVERY_DAYS lookback only when there is no history
122
+ * to consult at all — a device that predates this feature, or one restored with neither a
123
+ * backup nor any local history of its own — which is exactly today's unchanged behaviour for
124
+ * that case.
125
+ */
126
+ export function recoveryDatesToScan(recordedDates: readonly string[], now: Date = new Date()): string[] {
127
+ if (recordedDates.length > 0) return [...new Set(recordedDates)]
128
+ return Array.from({ length: MAX_RECOVERY_DAYS }, (_, day) => getCurrentDate(day, now))
129
+ }
130
+
95
131
  /** One ASCII space. The wallet derives a different key for any other separator. */
96
132
  export function legacyKeyId(derivationPrefix: string): string {
97
133
  return `${derivationPrefix} ${LEGACY_DERIVATION_SUFFIX}`
@@ -152,10 +188,26 @@ export interface AddressRailWallet extends AddressDerivingWallet {
152
188
  createAction(args: unknown, originator?: string): Promise<unknown>
153
189
  }
154
190
 
191
+ /**
192
+ * Resource bounds for chain-service responses (XR-059/XR-060). Every
193
+ * configured chain-service call this rail makes trusts the *content* of what
194
+ * comes back (verified downstream by the real transaction bytes, a merkle
195
+ * path, or the wallet's own ledger) but not its *size* — a compromised or
196
+ * merely misbehaving indexer must not be able to force unbounded allocation,
197
+ * hex-decode/BEEF-merge work, or per-row network fanout just by sending back
198
+ * more than any real address or transaction could ever legitimately produce.
199
+ */
200
+ export const MAX_UTXO_LISTING_ROWS = 2000
201
+ export const MAX_HEX_RESPONSE_CHARS = 8_000_000
202
+
155
203
  export async function getUtxosForAddress(woc: WocConfig, address: string): Promise<Utxo[]> {
156
204
  const response = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/address/${address}/unspent/all`)
157
205
  const rp = await response.json()
206
+ // A live receive address never legitimately carries anywhere near this many
207
+ // UTXOs; sweepAddress fetches one BEEF per distinct txid in the result, so
208
+ // an unbounded row count is also unbounded network fanout.
158
209
  return rp.result
210
+ .slice(0, MAX_UTXO_LISTING_ROWS)
159
211
  .filter((r: any) => r.isSpentInMempoolTx === false)
160
212
  .map((r: any) => ({ txid: r.tx_hash, vout: r.tx_pos, satoshis: r.value }))
161
213
  }
@@ -248,7 +300,8 @@ export async function getProcessedTransactions(
248
300
  export function parseWocBeefBody(resp: { ok: boolean; text: string }): number[] | undefined {
249
301
  if (!resp.ok) return undefined
250
302
  const hex = resp.text.trim()
251
- if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return undefined
303
+ if (hex.length === 0 || hex.length > MAX_HEX_RESPONSE_CHARS || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex))
304
+ return undefined
252
305
  try {
253
306
  return Utils.toArray(hex, 'hex')
254
307
  } catch {
@@ -295,6 +348,20 @@ export function payerAddressOf(tx: Transaction, network: 'mainnet' | 'testnet' =
295
348
  * Each UTXO is fetched and internalized in its own try/catch so one bad BEEF
296
349
  * cannot skip the rest of the address.
297
350
  */
351
+ /**
352
+ * XR-054: the number of distinct transactions sweepAddress will fetch+verify+
353
+ * internalize in a single call. getUtxosForAddress already caps the raw UTXO
354
+ * listing at MAX_UTXO_LISTING_ROWS (XR-059), but that still allows up to that
355
+ * many distinct txids, each costing one sequential network fetch — dusting a
356
+ * published receive address with many small, distinct-txid payments would
357
+ * otherwise make every 30-second sweeper.ts pass do that many fetches, over
358
+ * and over, forever. Capping here bounds the work any one pass can do; any
359
+ * txid left over this pass is simply still "available" (not yet
360
+ * internalized) and gets picked up by a later pass — nothing is lost or
361
+ * double-credited, since internalizeAction is idempotent per output.
362
+ */
363
+ export const MAX_SWEEP_TXIDS_PER_PASS = 200
364
+
298
365
  export async function sweepAddress(args: {
299
366
  wallet: AddressRailWallet
300
367
  adminOriginator: string
@@ -314,14 +381,22 @@ export async function sweepAddress(args: {
314
381
  const senderIdentityKey = new PrivateKey(1).toPublicKey().toString()
315
382
  let importedSatoshis = 0
316
383
  let failureCount = 0
317
- const seen = new Set<string>()
318
384
 
385
+ // XR-054: a single linear grouping pass (was: one `.filter()` over the
386
+ // whole `utxos` array per unique txid inside this same loop, i.e. O(n^2)
387
+ // for n outputs), plus the per-pass txid cap above.
388
+ const byTxid = new Map<string, Utxo[]>()
319
389
  for (const utxo of utxos) {
320
- if (seen.has(utxo.txid)) continue
321
- seen.add(utxo.txid)
322
- const relevant = utxos.filter(o => o.txid === utxo.txid)
390
+ const group = byTxid.get(utxo.txid)
391
+ if (group) group.push(utxo)
392
+ else byTxid.set(utxo.txid, [utxo])
393
+ }
394
+ const txids = Array.from(byTxid.keys()).slice(0, MAX_SWEEP_TXIDS_PER_PASS)
395
+
396
+ for (const txid of txids) {
397
+ const relevant = byTxid.get(txid) as Utxo[]
323
398
  try {
324
- const resp = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${utxo.txid}/beef`)
399
+ const resp = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`)
325
400
  const bytes = parseWocBeefBody({ ok: resp.ok, text: await resp.text() })
326
401
  if (!bytes) {
327
402
  failureCount++
@@ -329,12 +404,24 @@ export async function sweepAddress(args: {
329
404
  }
330
405
  const beef = new Beef()
331
406
  beef.mergeBeef(bytes)
332
- const tx = beef.findAtomicTransaction(utxo.txid)
407
+ const tx = beef.findAtomicTransaction(txid)
333
408
  if (!tx) {
334
409
  failureCount++
335
410
  continue
336
411
  }
337
- const outputs: InternalizeOutput[] = relevant.map(o => ({
412
+ // XR-056: `o.satoshis` here is the chain-indexer's own unauthenticated
413
+ // `value` field (see getUtxosForAddress) — a faulty or malicious
414
+ // indexer can report any figure it likes. `tx` is the cryptographically
415
+ // parsed, atomic-BEEF-verified transaction the wallet is about to
416
+ // internalize, so its own outputs are the only trustworthy amount.
417
+ // A listing row whose vout doesn't even exist on the real transaction
418
+ // is dropped rather than internalized.
419
+ const verified = relevant.filter(o => tx.outputs[o.vout] !== undefined)
420
+ if (verified.length === 0) {
421
+ failureCount++
422
+ continue
423
+ }
424
+ const outputs: InternalizeOutput[] = verified.map(o => ({
338
425
  outputIndex: o.vout,
339
426
  protocol: 'wallet payment' as const,
340
427
  paymentRemittance: {
@@ -360,8 +447,9 @@ export async function sweepAddress(args: {
360
447
  ]
361
448
  }
362
449
  const response = await wallet.internalizeAction(internalizeArgs, adminOriginator)
363
- if (response?.accepted) importedSatoshis += relevant.reduce((sum, o) => sum + o.satoshis, 0)
364
- else failureCount++
450
+ if (response?.accepted) {
451
+ importedSatoshis += verified.reduce((sum, o) => sum + (tx.outputs[o.vout]?.satoshis ?? 0), 0)
452
+ } else failureCount++
365
453
  } catch {
366
454
  failureCount++
367
455
  }
@@ -391,6 +479,13 @@ export async function sendToAddress(args: {
391
479
  const sats = Math.round(Number(satoshis))
392
480
  if (!Number.isFinite(sats) || sats <= 0) throw new Error('Invalid amount')
393
481
  if (!isValidBsvAddress(address)) throw new Error('Invalid BSV address')
482
+ // XR-057 (SEC2-065): this rail only ever builds a P2PKH lock (see the D4
483
+ // comment above — P2SH is deliberately unsupported), so a well-formed
484
+ // base58check address whose version byte names neither mainnet nor a test
485
+ // chain (e.g. a P2SH `3...` address) must be refused here, as a repo-owned
486
+ // guarantee, rather than relying on @bsv/sdk's P2PKH.lock() to keep
487
+ // throwing for a non-P2PKH version byte.
488
+ if (addressNetwork(address) === undefined) throw new Error('Unsupported address type')
394
489
  const lockingScript = new P2PKH().lock(address).toHex()
395
490
  // A send-max request carries maxPossibleSatoshis and the wallet rewrites the
396
491
  // output to whatever the inputs can fund, so the real figure only exists on
@@ -356,8 +356,18 @@ export interface HandleRailWallet {
356
356
  abortAction(args: unknown, originator?: string): Promise<unknown>
357
357
  }
358
358
 
359
- /** Broadcast a previously-minted noSend transaction. A createAction call whose
360
- * only job is `options.sendWith` — no new outputs are created. */
359
+ /**
360
+ * Broadcast a previously-minted noSend transaction. A createAction call whose
361
+ * only job is `options.sendWith` — no new outputs are created.
362
+ *
363
+ * Requires positive confirmation, the same fail-closed check the Vault path
364
+ * uses (`requireReleasedHeldTransaction`): exactly one result whose txid
365
+ * matches (case-insensitively) with status `sending` or `unproven`. Anything
366
+ * else — missing/empty results, an unrelated or duplicate txid, an unknown
367
+ * status — is treated as unconfirmed and throws, so the caller's existing
368
+ * failure path leaves the outbox entry unsent and retryable rather than
369
+ * marking a possibly-still-reserved transaction as sent.
370
+ */
361
371
  async function broadcastNoSend(
362
372
  wallet: Pick<HandleRailWallet, 'createAction'>,
363
373
  adminOriginator: string,
@@ -367,11 +377,29 @@ async function broadcastNoSend(
367
377
  { description: 'PeerPay payment broadcast', options: { sendWith: [txid] } },
368
378
  adminOriginator
369
379
  )) as { sendWithResults?: { txid?: string; status?: string }[] }
370
- const failed = result.sendWithResults?.find(o => o.txid === txid && o.status === 'failed')
371
- if (failed) throw new Error('broadcast_failed')
380
+ const results = result.sendWithResults
381
+ const released =
382
+ Array.isArray(results) &&
383
+ results.length === 1 &&
384
+ typeof results[0]?.txid === 'string' &&
385
+ results[0].txid.toLowerCase() === txid.toLowerCase() &&
386
+ (results[0].status === 'sending' || results[0].status === 'unproven')
387
+ if (!released) throw new Error('broadcast_not_confirmed')
372
388
  }
373
389
 
374
- /** Abort a PeerPay noSend by recovering its reference from listActions. */
390
+ /**
391
+ * Abort a PeerPay noSend by recovering its reference from listActions.
392
+ *
393
+ * XR-034: the wrapped `abortAction` this wallet publishes can refuse with
394
+ * `{ aborted: false }` rather than throw (the abort guard's whole contract —
395
+ * see `abortGuard.ts`). Returning `true` unconditionally, as this used to,
396
+ * told `cancelOutboxPayment` the reservation was released when it was not,
397
+ * which for an `abandon` call then removed the outbox row that is the only
398
+ * record of this payment's delivery state — the exact row `isAbortSafe` (this
399
+ * file) relies on existing to refuse a later, unsafe generic abort. Checking
400
+ * the result keeps that row (and the reservation) in place until an abort
401
+ * actually lands.
402
+ */
375
403
  async function abortPeerPayNosend(
376
404
  wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>,
377
405
  adminOriginator: string,
@@ -382,8 +410,10 @@ async function abortPeerPayNosend(
382
410
  const { actions } = await wallet.listActions({ labels: ['peerpay'], limit: 1000 }, adminOriginator)
383
411
  const match = actions.find(a => a.txid === txid)
384
412
  if (!match?.reference) return false
385
- await wallet.abortAction({ reference: match.reference }, adminOriginator)
386
- return true
413
+ const result = (await wallet.abortAction({ reference: match.reference }, adminOriginator)) as
414
+ | { aborted?: boolean }
415
+ | undefined
416
+ return result?.aborted !== false
387
417
  }
388
418
 
389
419
  /**
@@ -532,10 +562,23 @@ export async function sendViaHandle(args: {
532
562
  * refuses to abort and returns `needsAbandon`.
533
563
  *
534
564
  * `abandon` (delivered or delivering): tell the recipient via
535
- * `payment_cancelled`, then abort if the action is still nosend, then remove.
536
- * A failed control send leaves the row — the recipient would otherwise keep
537
- * waiting. Legacy entries (no txid) were broadcast at creation; there is
538
- * nothing to abort for them.
565
+ * `payment_cancelled`, then stop tracking the entry locally. A failed control
566
+ * send leaves the row — the recipient would otherwise keep waiting for a
567
+ * cancellation notice that never arrived.
568
+ *
569
+ * SEC2-031: `abandon` never calls `abortAction`, even when it would genuinely
570
+ * succeed. Once a token may be sitting in the recipient's box, releasing the
571
+ * sender's own inputs — while the recipient's signed copy is still fully
572
+ * spendable — is the exact conflicting-spend this rail must not create; a
573
+ * *confirmed* abort is no safer than an unconfirmed one; either way the other
574
+ * side can still redeem. So this mode leaves the wallet's noSend action, and
575
+ * the inputs it reserves, exactly as they are: only this device's local
576
+ * retry/tracking row is dropped. That is safe to do unconditionally, because
577
+ * `isAbortSafe` (below) already refuses the generic Activity abort for any
578
+ * `peerpay` action whose outbox row is missing, not only one still marked
579
+ * delivered/delivering — so dropping the row here cannot open a path to
580
+ * release the same inputs some other way. Legacy entries (no txid) were
581
+ * broadcast at creation; there is nothing to notify or abort for them.
539
582
  */
540
583
  export async function cancelOutboxPayment(args: {
541
584
  wallet: Pick<HandleRailWallet, 'listActions' | 'abortAction'>
@@ -546,18 +589,14 @@ export async function cancelOutboxPayment(args: {
546
589
  mode?: 'undelivered' | 'abandon'
547
590
  }): Promise<{ aborted: boolean; needsAbandon?: boolean }> {
548
591
  const { wallet, adminOriginator, storage, entry, client, mode = 'undelivered' } = args
549
- if (mode !== 'abandon') {
550
- const stored = (await getOutboxEntries(storage)).find(e => e.id === entry.id)
551
- if (!stored) return { aborted: false }
552
- if (stored.delivered === true || stored.delivering === true) {
553
- return { aborted: false, needsAbandon: true }
554
- }
555
- }
592
+
556
593
  if (mode === 'abandon') {
557
594
  if (!client) throw new Error('client required to abandon')
558
595
  if (entry.txid) {
559
596
  // Same box the token went to — an entry minted for a link-named host must
560
- // be cancelled there, or the payee never hears.
597
+ // be cancelled there, or the payee never hears. Throwing here (network
598
+ // down, box unreachable) skips the removal below, so the row survives
599
+ // for a retry rather than going silently missing.
561
600
  await sendControlMessage(
562
601
  client,
563
602
  {
@@ -567,21 +606,57 @@ export async function cancelOutboxPayment(args: {
567
606
  entry.recipientHost
568
607
  )
569
608
  }
609
+ // Never abortAction here — see the doc comment above (SEC2-031).
610
+ await removeOutboxEntry(storage, entry.id)
611
+ return { aborted: false }
570
612
  }
613
+
614
+ const stored = (await getOutboxEntries(storage)).find(e => e.id === entry.id)
615
+ if (!stored) return { aborted: false }
616
+ if (stored.delivered === true || stored.delivering === true) {
617
+ return { aborted: false, needsAbandon: true }
618
+ }
619
+
571
620
  let aborted = false
572
621
  if (entry.txid) {
573
622
  try {
574
623
  aborted = await abortPeerPayNosend(wallet, adminOriginator, entry.txid)
575
624
  } catch {
576
- // The entry is still removed: the nosend row remains visible in wallet
577
- // activity with its own abort control, so the money is never stranded
578
- // invisibly.
625
+ // Unreachable-token case: no one else holds this payment, so the
626
+ // nosend row stays visible in wallet activity with its own abort
627
+ // control either way — removing our own tracking row below is safe
628
+ // regardless of whether the abort itself confirmed.
579
629
  }
580
630
  }
581
631
  await removeOutboxEntry(storage, entry.id)
582
632
  return { aborted }
583
633
  }
584
634
 
635
+ /**
636
+ * Whether the generic Activity "Abort" action may call `abortAction` for this action as-is.
637
+ *
638
+ * A `peerpay` outbound payment's real delivery state lives only in its outbox row (see
639
+ * `OutboxEntry`) — `key_value_store`, where that row lives, is not currently part of the
640
+ * encrypted backup, so a wallet restored from backup has NO row at all for an outbox entry
641
+ * that may already have reached the recipient's MessageBox. Unlike `cancelOutboxPayment`'s
642
+ * own live-device guard, the generic Activity abort path has no concept of "peerpay" at
643
+ * all, so without this check it would release the payer's inputs for ANY
644
+ * nosend/unsigned/failed/nonfinal action regardless of label — including one whose
645
+ * recipient may already hold a signed, deliverable token. A missing row must be treated
646
+ * exactly like a row that IS delivered/delivering: refuse, rather than assume "never sent".
647
+ */
648
+ export function isAbortSafe (
649
+ action: { labels?: string[], txid?: string },
650
+ outboxEntries: Array<Pick<OutboxEntry, 'txid' | 'delivered' | 'delivering'>>
651
+ ): { aborted: boolean, needsAbandon?: boolean } {
652
+ if (!action.labels?.includes('peerpay')) return { aborted: true }
653
+ const stored = action.txid != null ? outboxEntries.find(e => e.txid === action.txid) : undefined
654
+ if (stored == null || stored.delivered === true || stored.delivering === true) {
655
+ return { aborted: false, needsAbandon: true }
656
+ }
657
+ return { aborted: true }
658
+ }
659
+
585
660
  // ── The token half of the handle rail (offline-settlement spec §4.5) ──
586
661
  //
587
662
  // Same rail, different pipeline. A satoshi payment is minted here and delivered
@@ -674,8 +749,17 @@ export async function retryDelivery(args: {
674
749
  }): Promise<void> {
675
750
  const { wallet, adminOriginator, client, storage, entry } = args
676
751
  await updateOutboxEntry(storage, entry.id, { lastAttemptAt: new Date().toISOString() })
752
+ // XR-052: a concurrent UI abandon (cancelOutboxPayment) can remove this same
753
+ // row between awaits — it shares no lock with the background drain beyond
754
+ // the per-storage-mutation lock in outbox.ts, which only serializes the
755
+ // write itself. Re-read by id immediately before each side-effecting step
756
+ // (mirrors cancelOutboxPayment's own re-read for its 'undelivered' mode) and
757
+ // stop cleanly if the row is gone, so an in-flight retry cannot still
758
+ // deliver or broadcast a payment the user just cancelled.
759
+ const stillPending = async (): Promise<boolean> => (await getOutboxEntries(storage)).some(e => e.id === entry.id)
677
760
  try {
678
761
  if (entry.delivered !== true) {
762
+ if (!(await stillPending())) return
679
763
  await updateOutboxEntry(storage, entry.id, { delivering: true })
680
764
  try {
681
765
  await client.sendMessage(
@@ -695,6 +779,17 @@ export async function retryDelivery(args: {
695
779
  await updateOutboxEntry(storage, entry.id, { delivered: true })
696
780
  }
697
781
  if (entry.txid) {
782
+ if (!(await stillPending())) return
783
+ // XR-048: the persisted `txid` is unauthenticated — a tampered/imported
784
+ // outbox row (local storage tamper, malicious backup restore) could
785
+ // point it at an unrelated, still-pending noSend action's txid while
786
+ // leaving `token.transaction` alone. Re-derive the txid this entry's own
787
+ // token actually names and refuse to broadcast on a mismatch, rather
788
+ // than handing an attacker-chosen txid straight to `sendWith`.
789
+ const ownTxid = safeAtomicTxid(entry.token.transaction)
790
+ if (!ownTxid || ownTxid.toLowerCase() !== entry.txid.toLowerCase()) {
791
+ throw new Error('outbox_txid_mismatch')
792
+ }
698
793
  await broadcastNoSend(wallet, adminOriginator, entry.txid)
699
794
  }
700
795
  await markOutboxSent(storage, entry.id)
@@ -31,7 +31,7 @@ export type RailId = 'nearby' | 'handle' | 'address'
31
31
  export type PayTarget =
32
32
  | { kind: 'nearby'; session: Session }
33
33
  | { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string }
34
- | { kind: 'address'; address: string; sats?: number }
34
+ | { kind: 'address'; address: string; sats?: number; network?: 'main' | 'test' }
35
35
 
36
36
  /** Six cell names. Since the universal input, `pay-*` are deep-link aliases that all open the send form; `get-*` open one receive method directly. */
37
37
  export type PayCell = 'pay-nearby' | 'pay-handle' | 'pay-address' | 'get-nearby' | 'get-handle' | 'get-address'
@@ -90,6 +90,33 @@ export function isValidBsvAddress(text: string): boolean {
90
90
  }
91
91
  }
92
92
 
93
+ /**
94
+ * The network a base58check address's version byte names — 0x00 for
95
+ * mainnet, 0x6f for every test chain (testnet and teratest share the byte;
96
+ * the app's own network selector is what tells them apart, the address
97
+ * format does not). Undefined for text that is not a valid base58check
98
+ * address, or whose version byte names neither.
99
+ *
100
+ * Pure, like everything else here: it re-decodes the address rather than
101
+ * threading a value through, so a caller can compare a recipient's network
102
+ * against whichever chain the wallet has selected without either side
103
+ * knowing about the other (misc-p2-03 — a pasted/scanned address is accepted
104
+ * regardless of its version byte, so a mainnet wallet could pay a
105
+ * testnet-shaped address with zero warning; same key either way, but no
106
+ * visibility for the sender).
107
+ */
108
+ export function addressNetwork(address: string): 'main' | 'test' | undefined {
109
+ try {
110
+ const { prefix } = Utils.fromBase58Check(address)
111
+ const byte = Array.isArray(prefix) ? prefix[0] : undefined
112
+ if (byte === 0x00) return 'main'
113
+ if (byte === 0x6f) return 'test'
114
+ return undefined
115
+ } catch {
116
+ return undefined
117
+ }
118
+ }
119
+
93
120
  /**
94
121
  * Base58 alphabet (no 0, O, I, l), 25–35 chars: the shape of a P2PKH address on
95
122
  * either network — mainnet `1`, testnet `m`/`n`. P2SH `3` is deliberately
@@ -102,12 +129,20 @@ const ADDRESS_CANDIDATE_REGEX = /^[1mn][1-9A-HJ-NP-Za-km-z]{24,34}$/
102
129
  /** What the recipient field has been given, as typed. */
103
130
  export type RecipientInput =
104
131
  | { kind: 'empty' }
105
- | { kind: 'address'; address: string }
132
+ | { kind: 'address'; address: string; network?: 'main' | 'test' }
106
133
  | { kind: 'invalid_address' }
107
134
  | { kind: 'handle'; identityKey: string; sats?: number; asset?: string; amount?: number; messageBoxUrl?: string }
108
135
  | { kind: 'invalid_link'; message: string }
109
136
  | { kind: 'search'; query: string }
110
137
 
138
+ /** `{ network }` when the address's version byte names one, `{}` otherwise —
139
+ * spread onto an address result so an unrecognised prefix omits the field
140
+ * rather than carrying it as `undefined`. */
141
+ function addressNetworkField(address: string): { network?: 'main' | 'test' } {
142
+ const network = addressNetwork(address)
143
+ return network ? { network } : {}
144
+ }
145
+
111
146
  function handleFromPeerPay(result: PeerPayValidationResult): RecipientInput {
112
147
  if (!result.identityKey || peerPayHasErrors(result)) {
113
148
  return { kind: 'invalid_link', message: peerPayValidationMessage(result) ?? 'Invalid peerpay link' }
@@ -136,7 +171,9 @@ export function classifyRecipientInput(raw: string): RecipientInput {
136
171
  const isBitcoinUri = /^bitcoin:/i.test(text)
137
172
  const candidate = isBitcoinUri ? normalizeAddressInput(text) : text
138
173
  if (isBitcoinUri || ADDRESS_CANDIDATE_REGEX.test(candidate)) {
139
- return isValidBsvAddress(candidate) ? { kind: 'address', address: candidate } : { kind: 'invalid_address' }
174
+ return isValidBsvAddress(candidate)
175
+ ? { kind: 'address', address: candidate, ...addressNetworkField(candidate) }
176
+ : { kind: 'invalid_address' }
140
177
  }
141
178
 
142
179
  if (isCompressedPublicKey(text)) return { kind: 'handle', identityKey: text.toLowerCase() }
@@ -172,7 +209,7 @@ export function classifyScan(raw: string): PayTarget | null {
172
209
 
173
210
  if (/^bitcoin:/i.test(text)) {
174
211
  const address = normalizeAddressInput(text)
175
- return isValidBsvAddress(address) ? { kind: 'address', address } : null
212
+ return isValidBsvAddress(address) ? { kind: 'address', address, ...addressNetworkField(address) } : null
176
213
  }
177
214
 
178
215
  try {
@@ -182,7 +219,7 @@ export function classifyScan(raw: string): PayTarget | null {
182
219
  }
183
220
 
184
221
  if (isCompressedPublicKey(text)) return { kind: 'handle', identityKey: text.toLowerCase() }
185
- if (isValidBsvAddress(text)) return { kind: 'address', address: text }
222
+ if (isValidBsvAddress(text)) return { kind: 'address', address: text, ...addressNetworkField(text) }
186
223
  return null
187
224
  }
188
225
 
@@ -195,12 +232,13 @@ export function classifyScan(raw: string): PayTarget | null {
195
232
  */
196
233
  export function legacyRedirectTarget(
197
234
  route: 'payments' | 'legacy-payments' | 'local-payments',
198
- params: Record<string, string | undefined>
235
+ params: Record<string, string | string[] | undefined>
199
236
  ): { pathname: '/pay'; params: Record<string, string> } {
200
237
  const cell: PayCell = route === 'payments' ? 'pay-handle' : route === 'legacy-payments' ? 'get-address' : 'get-nearby'
201
238
  const forwarded: Record<string, string> = { cell }
202
239
  for (const key of ['peerpay', 'identityKey', 'sats'] as const) {
203
- const value = params[key]
240
+ const raw = params[key]
241
+ const value = Array.isArray(raw) ? raw[0] : raw
204
242
  if (value !== undefined) forwarded[key] = value
205
243
  }
206
244
  return { pathname: '/pay', params: forwarded }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Where an externally-opened link (a system deep link, not an in-app
3
+ * navigation) sends the user.
4
+ *
5
+ * Two protocols are handled: `peerpay:` — the toolbox's own payment-request
6
+ * scheme, recognised regardless of which app owns it — and the host app's own
7
+ * custom URL schemes, supplied by the caller as `walletSchemes` so this stays
8
+ * usable by a second wallet app with different scheme names. Both app schemes
9
+ * use the host as the first route segment.
10
+ *
11
+ * `pair` is passed straight through to `/pair` (PairScreen), unchanged. It
12
+ * used to be rewritten to `connections`, on the theory that Connections
13
+ * already shows its own approval step for a scanned/pasted URI — but a deep
14
+ * link never went through that step: ConnectionsScreen's `deepLinkParams`
15
+ * effect called straight into `connect()` with no user gesture in between
16
+ * (see the MITM-P1-deeplink-autoconnect finding). `/pair` is the screen that
17
+ * actually renders origin + permissions + Approve/Reject, so an external
18
+ * pairing link now gets exactly the same consent step a scanned QR gets —
19
+ * never less.
20
+ *
21
+ * `auth/scan-shares` and `auth/mnemonic` with `flow=import` in its query are
22
+ * the two destructive entry points into the recovery module — a deep link
23
+ * landing on either one overwrites the device's only stored secret. They are
24
+ * redirected to `/` instead of passed through, regardless of what an
25
+ * attacker puts in the rest of the link. `auth/mnemonic?flow=backup` (and any
26
+ * other `flow`) is unaffected — it only reads/displays the existing secret,
27
+ * never overwrites it. This is layer 1 of two; layer 2 lives in
28
+ * `recoverWallet.ts`, which refuses to overwrite an existing identity from
29
+ * ANY entry point (in-app or not) unless the caller explicitly confirms.
30
+ */
31
+ const AUTH_SCAN_SHARES_ROUTE = /^auth\/scan-shares\/?(?=[?#]|$)/i
32
+ const AUTH_MNEMONIC_ROUTE = /^auth\/mnemonic\/?(?=[?#]|$)/i
33
+
34
+ function isDestructiveAuthRoute(route: string): boolean {
35
+ if (AUTH_SCAN_SHARES_ROUTE.test(route)) return true
36
+ const match = AUTH_MNEMONIC_ROUTE.exec(route)
37
+ if (!match) return false
38
+ const rest = route.slice(match[0].length)
39
+ if (!rest.startsWith('?')) return false
40
+ const query = rest.slice(1).split('#')[0]
41
+ return new URLSearchParams(query).get('flow')?.toLowerCase() === 'import'
42
+ }
43
+
44
+ export function resolveNativeIntent(path: string, opts: { walletSchemes: string[] }): string {
45
+ try {
46
+ if (path?.toLowerCase().startsWith('peerpay:')) {
47
+ return `/pay?cell=pay-handle&peerpay=${encodeURIComponent(path)}`
48
+ }
49
+ const escaped = opts.walletSchemes.map(scheme => scheme.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
50
+ const walletScheme = new RegExp(`^(?:${escaped.join('|')}):\\/\\/`, 'i')
51
+ if (escaped.length > 0 && walletScheme.test(path)) {
52
+ // Return a relative path so Expo Router preserves encoded pairing parameters.
53
+ const route = path.replace(walletScheme, '').replace(/^\/+/, '')
54
+ if (isDestructiveAuthRoute(route)) return '/'
55
+ return `/${route}`
56
+ }
57
+ return path || '/'
58
+ } catch {
59
+ return '/'
60
+ }
61
+ }
@@ -79,6 +79,7 @@ export {
79
79
  declineReasonFor,
80
80
  verifyFramePayment,
81
81
  type DerivingWallet,
82
+ type FrameVerifyDeps,
82
83
  type FrameVerifyKind,
83
84
  type VerifiedPayment
84
85
  } from '../../localpay/verify'