@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
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Every calendar date this device has issued a conventional-receive address for.
3
+ *
4
+ * XR-055. `pay/watchlist.ts` prunes by a 7-day calendar age no matter how recently an
5
+ * address was swept — that bound exists to keep the BACKGROUND sweeper's polling cost
6
+ * bounded, and is deliberately left alone here (see watchlist.ts's own "spec open question
7
+ * 5" note and its pinned-bounds test). But it means the watchlist cannot answer "which
8
+ * dates has this wallet ever issued an address for", which is exactly what a payer-sat-on-
9
+ * it-for-a-month recovery scan needs: a payer who pays a legitimately-displayed address more
10
+ * than MAX_WATCH_DAYS/MAX_RECOVERY_DAYS after issue had no shipped path back to
11
+ * internalizeAction once the watchlist entry aged out.
12
+ *
13
+ * This store answers that question. It is capped by COUNT, not calendar age — an issued
14
+ * date is worth remembering indefinitely, since sweepAddress (core/pay/rails/address.ts) is
15
+ * idempotent and cheap to retry for a date that turns out to hold nothing — and it rides the
16
+ * encrypted backup envelope (core/backup/appData.ts) so a restored device CAN resume
17
+ * scanning every date this wallet has ever shown, not just the ones the restoring device
18
+ * itself issued — but only for a date recorded in a window where some OTHER entity change
19
+ * also happened to get pushed; see appData.ts's own "KNOWN, STILL-OPEN GAP" note for why a
20
+ * date issued with nothing else going on in the wallet at the time can still fail to reach
21
+ * the log at all.
22
+ */
23
+
24
+ export const RECEIVE_HISTORY_KEY = 'pay_receive_issued_dates'
25
+
26
+ /**
27
+ * Count cap, not calendar-age cap (see module docstring). One entry is a ~10-byte
28
+ * YYYY-MM-DD string, so even this many costs nothing to store or to carry in a backup
29
+ * envelope — it exists only so a pathological caller cannot grow this list forever, not
30
+ * because any realistic wallet would approach it.
31
+ */
32
+ export const MAX_RECEIVE_HISTORY = 3650
33
+
34
+ export interface KVStorage {
35
+ getKeyValue (k: string): Promise<string | undefined>
36
+ setKeyValue (k: string, v: string): Promise<void>
37
+ }
38
+
39
+ // Same discipline as localpay/pending.ts and pay/watchlist.ts: every read-modify-write on
40
+ // this single storage key runs through one chain, or a write built from a stale read
41
+ // silently drops an entry.
42
+ let queueLock: Promise<unknown> = Promise.resolve()
43
+
44
+ function withQueueLock<T> (fn: () => Promise<T>): Promise<T> {
45
+ const run = queueLock.then(fn, fn)
46
+ queueLock = run.catch(() => undefined)
47
+ return run
48
+ }
49
+
50
+ async function readAll (storage: KVStorage): Promise<string[]> {
51
+ const raw = await storage.getKeyValue(RECEIVE_HISTORY_KEY)
52
+ if (!raw) return []
53
+ try {
54
+ const parsed = JSON.parse(raw) as unknown
55
+ return Array.isArray(parsed) ? parsed.filter((d): d is string => typeof d === 'string') : []
56
+ } catch {
57
+ return []
58
+ }
59
+ }
60
+
61
+ function normalise (dates: Iterable<string>): string[] {
62
+ return [...new Set(dates)].sort().slice(-MAX_RECEIVE_HISTORY)
63
+ }
64
+
65
+ /**
66
+ * Record a newly issued date, deduplicated. Called from the same place AddressReceive.tsx
67
+ * already calls watchAddress — every address this app has shown the user gets its date
68
+ * remembered here too, independent of whether that address also survives the watchlist's
69
+ * own 7-day prune.
70
+ */
71
+ export async function recordIssuedDate (storage: KVStorage, date: string): Promise<void> {
72
+ return withQueueLock(async () => {
73
+ const all = await readAll(storage)
74
+ if (all.includes(date)) return
75
+ await storage.setKeyValue(RECEIVE_HISTORY_KEY, JSON.stringify(normalise([...all, date])))
76
+ })
77
+ }
78
+
79
+ /** Every recorded date, deduplicated and sorted ascending. */
80
+ export async function getIssuedDates (storage: KVStorage): Promise<string[]> {
81
+ return normalise(await readAll(storage))
82
+ }
83
+
84
+ /**
85
+ * Replace the whole list. Used only by backup restore (core/backup/appData.ts), which has
86
+ * already merged every device's own history into one deduplicated, capped list and wants a
87
+ * single write rather than N individual `recordIssuedDate` inserts.
88
+ */
89
+ export async function setIssuedDates (storage: KVStorage, dates: string[]): Promise<void> {
90
+ return withQueueLock(async () => {
91
+ await storage.setKeyValue(RECEIVE_HISTORY_KEY, JSON.stringify(normalise(dates)))
92
+ })
93
+ }
@@ -10,6 +10,7 @@
10
10
  * no req, the proof is written directly: a proven_tx row (the toolbox's own
11
11
  * `findOrInsertProvenTx` shape) and the transaction promoted to `completed`.
12
12
  */
13
+ import { Transaction } from '@bsv/sdk'
13
14
  import type { TableProvenTx, TableProvenTxReq, TableTransaction } from '@bsv/wallet-toolbox-mobile'
14
15
  import type { UpdateProvenTxReqWithNewProvenTxArgs } from '../toolboxTypes'
15
16
 
@@ -70,13 +71,30 @@ export async function recordProof(
70
71
 
71
72
  let provenTxId = (await storage.findProvenTxs({ partial: { txid } }))[0]?.provenTxId
72
73
  if (provenTxId === undefined) {
74
+ // XR-029: the direct path has no proven_tx_req to have already checked
75
+ // these bytes against anything — the BUMP/root check that authenticated
76
+ // `txid` never touches the separately-fetched rawTx. Require it to
77
+ // actually parse and hash to the txid we are recording a proof for
78
+ // before it is ever inserted or a transaction is promoted to completed;
79
+ // a mismatched or unparsable response from a compromised/faulty raw-tx
80
+ // endpoint must not corrupt local data.
81
+ const rawTx = await args.fetchRawTx()
82
+ let parsedTxid: string
83
+ try {
84
+ parsedTxid = Transaction.fromBinary(rawTx).id('hex')
85
+ } catch (e: any) {
86
+ throw new Error(`recordProof: fetched raw tx for ${txid} does not parse as a transaction: ${e.message}`)
87
+ }
88
+ if (parsedTxid !== txid) {
89
+ throw new Error(`recordProof: fetched raw tx hashes to ${parsedTxid}, expected ${txid}`)
90
+ }
73
91
  const now = new Date()
74
92
  provenTxId = await storage.insertProvenTx({
75
93
  created_at: now,
76
94
  updated_at: now,
77
95
  provenTxId: 0,
78
96
  txid,
79
- rawTx: await args.fetchRawTx(),
97
+ rawTx,
80
98
  ...proof
81
99
  })
82
100
  }
@@ -18,6 +18,22 @@ export type OfflineRefreshStatus =
18
18
  // Held back deliberately, never released for broadcast. Like queued and
19
19
  // posting, a Refresh must not decide such a transaction has failed.
20
20
  | 'parked'
21
+ // Written only by a raw database import (ui/importDatabases.ts) over a
22
+ // copied-in 'queued'/'posting' row (XR-085): still an unresolved, possibly
23
+ // already-handed-off spend awaiting the user's renewed review, so it must
24
+ // not be failed either — same reasoning as 'parked'.
25
+ | 'import_hold'
26
+
27
+ /**
28
+ * refreshProof's /tx/hash/{txid} probe is advisory, single-source. Only an
29
+ * authoritative 404 means the network doesn't have the tx; any other
30
+ * completed non-OK response (429 rate-limit, 5xx, 401/403 auth trouble, ...)
31
+ * is a service problem, not proof of absence, and must be treated as
32
+ * inconclusive — exactly like a thrown network error.
33
+ */
34
+ export function isChainAbsenceConfirmed(status: number): boolean {
35
+ return status === 404
36
+ }
21
37
 
22
38
  export function shouldFailUnprovenTx(args: {
23
39
  offlineStatus?: OfflineRefreshStatus
@@ -25,10 +41,35 @@ export function shouldFailUnprovenTx(args: {
25
41
  updatedAtMs: number
26
42
  nowMs: number
27
43
  }): 'pending' | 'failed' {
28
- if (args.offlineStatus === 'queued' || args.offlineStatus === 'posting' || args.offlineStatus === 'parked') {
44
+ if (
45
+ args.offlineStatus === 'queued' ||
46
+ args.offlineStatus === 'posting' ||
47
+ args.offlineStatus === 'parked' ||
48
+ args.offlineStatus === 'import_hold'
49
+ ) {
29
50
  return 'pending'
30
51
  }
31
52
  if (!IN_FLIGHT.has(args.txStatus)) return 'pending'
32
53
  if (args.updatedAtMs && args.nowMs - args.updatedAtMs < STUCK_AFTER_MS) return 'pending'
33
54
  return 'failed'
34
55
  }
56
+
57
+ /**
58
+ * XR-059 remainder: refreshProof's two chain-service reads — the merkle BUMP
59
+ * hex from WoC's /proof/bump, and the raw-tx hex fetched inside its
60
+ * fetchRawTx callback — were unbounded, exactly like the address-sweep/BEEF
61
+ * reads XR-059 already bounded in address.ts's parseWocBeefBody and
62
+ * beefRepair.ts's refetchAtomicBeef. Same guard, same shape: a
63
+ * compromised/misbehaving configured indexer must not be able to force an
64
+ * arbitrarily large hex-decode (MerklePath.fromHex / Utils.toArray) just by
65
+ * answering with more bytes than any real proof or raw tx ever carries.
66
+ * Returns undefined for anything empty, oversized, odd-length, or not hex —
67
+ * the caller fails closed exactly as it already does for an unparseable body.
68
+ */
69
+ export function boundedHexResponse(text: string, maxChars: number): string | undefined {
70
+ const hex = text.trim()
71
+ if (hex.length === 0 || hex.length > maxChars || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) {
72
+ return undefined
73
+ }
74
+ return hex
75
+ }
@@ -14,8 +14,11 @@
14
14
  * · never older than MAX_WATCH_DAYS by its issue date
15
15
  *
16
16
  * A dropped address is not lost money: the Get paid → conventional wallet view
17
- * re-registers today's address every time it is opened, and the earlier-day
18
- * recovery stepper can reach back MAX_RECOVERY_DAYS and sweep by hand.
17
+ * re-registers today's address every time it is opened, the durable issued-date
18
+ * history (pay/receiveHistory.ts, XR-055) lets the automatic repair scan reach
19
+ * ANY previously issued date regardless of age, and the earlier-day recovery
20
+ * stepper can reach back MAX_MANUAL_RECOVERY_DAYS (core/pay/rails/address.ts)
21
+ * and sweep by hand.
19
22
  */
20
23
 
21
24
  export const WATCHLIST_KEY = 'pay_address_watchlist'
@@ -15,12 +15,7 @@ export type PaymentControlMessage =
15
15
  | { type: 'resend_request'; txid: string; reason: ResendReason; messageId?: string }
16
16
  | { type: 'payment_cancelled'; txid: string }
17
17
 
18
- const RESEND_REASONS: ReadonlySet<string> = new Set([
19
- 'corrupt',
20
- 'uncreditible',
21
- 'double_spent',
22
- 'bounced_offline'
23
- ])
18
+ const RESEND_REASONS: ReadonlySet<string> = new Set(['corrupt', 'uncreditible', 'double_spent', 'bounced_offline'])
24
19
 
25
20
  function asObject(body: unknown): Record<string, unknown> | undefined {
26
21
  let value: unknown = body
@@ -76,15 +71,9 @@ export async function sendControlMessage(
76
71
  export type ControlBoxMessage = { messageId: string; sender: string; body: unknown }
77
72
 
78
73
  /** Raw `payment_control` messages. `acceptPayments: false` avoids fee auto-internalize. */
79
- export async function listControlMessages(
80
- client: {
81
- listMessages(args: {
82
- messageBox: string
83
- host?: string
84
- acceptPayments?: boolean
85
- }): Promise<ControlBoxMessage[]>
86
- }
87
- ): Promise<ControlBoxMessage[]> {
74
+ export async function listControlMessages(client: {
75
+ listMessages(args: { messageBox: string; host?: string; acceptPayments?: boolean }): Promise<ControlBoxMessage[]>
76
+ }): Promise<ControlBoxMessage[]> {
88
77
  const listed = await client.listMessages({
89
78
  messageBox: PAYMENT_CONTROL_BOX,
90
79
  acceptPayments: false
@@ -112,11 +101,21 @@ export async function ackControlMessages(
112
101
  * never succeed — and the alternative, perturbing the body so it earns a fresh
113
102
  * id, would plant a second copy of a payment the recipient already holds.
114
103
  *
115
- * Matched on the server's own words rather than the bare status, so a 400 for
116
- * any other reason still surfaces as the failure it is.
104
+ * XR-046: matched ONLY on `@bsv/message-box-client`'s own structured
105
+ * `ERR_DUPLICATE_MESSAGE` code (`Message Box send failed with HTTP 400
106
+ * (ERR_DUPLICATE_MESSAGE).`), never on free prose. The client builds that
107
+ * string itself from a server response field it validates against
108
+ * `/^ERR_[A-Z0-9_]{1,64}$/` before embedding it — everything else in a
109
+ * thrown Error's message is attacker/host-controlled text a malicious or
110
+ * compromised recipientHost can fabricate at will for a 400 the recipient
111
+ * never actually received, which would wrongly mark retryDelivery's caller
112
+ * `delivered` and broadcast. Narrowing this does not close the deeper gap —
113
+ * a bare, non-throwing `sendMessage` success is still accepted with no
114
+ * recipient-authenticated receipt — closing that needs a receipt protocol
115
+ * change out of scope for this fix.
117
116
  */
118
117
  export function isDuplicateMessageError(e: unknown): boolean {
119
118
  const text = e instanceof Error ? e.message : typeof e === 'string' ? e : ''
120
119
  if (!/\b400\b/.test(text)) return false
121
- return /duplicate|already[ _-]?(exists|sent|delivered|present|received)|ERR_DUPLICATE/i.test(text)
120
+ return /\bERR_DUPLICATE_MESSAGE\b/.test(text)
122
121
  }
@@ -271,6 +271,30 @@ export function makeListPeerPayAction(
271
271
  }
272
272
  }
273
273
 
274
+ /**
275
+ * The payment's recorded recipient for `txid`, or undefined when this device
276
+ * cannot resolve one (matches the recipient half of rebuildAndDeliver's own
277
+ * resolution exactly, but without building the full action or touching
278
+ * derivation data / the network — this is the cheap pre-check that has to run
279
+ * BEFORE any of that expensive work, not a replacement for it).
280
+ *
281
+ * XR-051: this is the authority a resend_request's sender is checked
282
+ * against. `entry.recipient` (an outbox row this device itself created) is
283
+ * always trusted over a listed action's labels, exactly like
284
+ * rebuildAndDeliver.
285
+ */
286
+ async function resolveResendRecipient(
287
+ storage: StorageLike,
288
+ txid: string,
289
+ listPeerPayAction?: (txid: string) => Promise<PeerPayActionLike | undefined>
290
+ ): Promise<string | undefined> {
291
+ const entries = await getOutboxEntries(storage)
292
+ const entry = entries.find(e => outboxTxid(e) === txid)
293
+ if (entry?.recipient) return entry.recipient
294
+ const listed = listPeerPayAction ? await listPeerPayAction(txid) : undefined
295
+ return recipientFromLabels(listed?.labels)
296
+ }
297
+
274
298
  export async function loadUnansweredResends(storage: StorageLike): Promise<PendingResend[]> {
275
299
  try {
276
300
  const raw = await storage.getKeyValue(UNANSWERED_RESENDS_KEY)
@@ -301,6 +325,12 @@ async function storeUnansweredResends(storage: StorageLike, pending: PendingRese
301
325
  export async function listPendingResendRequests(args: {
302
326
  client: ListAckClient
303
327
  storage: StorageLike
328
+ /** Optional for backward compatibility: omitting it preserves the exact
329
+ * pre-XR-051 behavior (every resend_request is surfaced as pending) since
330
+ * without a way to list this wallet's own actions there is no way to
331
+ * resolve a recipient to check the sender against. Every production caller
332
+ * should pass it. */
333
+ listPeerPayAction?: (txid: string) => Promise<PeerPayActionLike | undefined>
304
334
  }): Promise<{ pending: PendingResend[] }> {
305
335
  const messages = await listControlMessages(args.client)
306
336
  const pending: PendingResend[] = []
@@ -316,10 +346,22 @@ export async function listPendingResendRequests(args: {
316
346
  continue
317
347
  }
318
348
  if (!parsed || parsed.type !== 'resend_request') continue
319
- pending.push({
320
- txid: parsed.txid,
321
- sender: typeof msg.sender === 'string' ? msg.sender : ''
322
- })
349
+ const sender = typeof msg.sender === 'string' ? msg.sender : ''
350
+ try {
351
+ // XR-051: a resend_request whose sender is provably NOT the payment's
352
+ // recorded recipient must never be persisted (or it would keep showing
353
+ // up as an unanswered resend banner forever) -- ack it away instead.
354
+ const recipient = await resolveResendRecipient(args.storage, parsed.txid, args.listPeerPayAction)
355
+ if (recipient !== undefined && recipient !== sender) {
356
+ await ackControlMessages(args.client, [msg.messageId])
357
+ continue
358
+ }
359
+ } catch {
360
+ // Resolution failed transiently (e.g. a storage read error) -- fall
361
+ // through and surface it as pending like before this fix, rather than
362
+ // silently dropping a request that might be entirely legitimate.
363
+ }
364
+ pending.push({ txid: parsed.txid, sender })
323
365
  }
324
366
  await storeUnansweredResends(args.storage, pending)
325
367
  return { pending }
@@ -450,6 +492,18 @@ export async function handleResendRequests(args: {
450
492
  if (!parsed || parsed.type !== 'resend_request') continue
451
493
  const sender = typeof msg.sender === 'string' ? msg.sender : ''
452
494
  try {
495
+ // XR-051: authenticate the request BEFORE any of the decrypt/rebuild/
496
+ // refetch/send work below. A resend_request is legitimate only from
497
+ // the payment's own recorded recipient -- anyone else who can address
498
+ // this wallet's control box must never be able to trigger that work
499
+ // (or a persistent retry of it) just by naming a txid it knows or
500
+ // guesses. Ack-and-drop silently: the requester gets no signal either
501
+ // way, and the control message cannot be replayed to try again.
502
+ const recipient = await resolveResendRecipient(storage, parsed.txid, listPeerPayAction)
503
+ if (recipient !== undefined && recipient !== sender) {
504
+ await ackControlMessages(client, [msg.messageId])
505
+ continue
506
+ }
453
507
  const deliveredTo = await rebuildAndDeliver({
454
508
  client,
455
509
  storage,
@@ -80,7 +80,9 @@ interface StorageLike {
80
80
 
81
81
  // ── Constants ─────────────────────────────────────────────────────────────────
82
82
 
83
- const OUTBOX_KEY = 'peerpay_outbox'
83
+ /** Exported so backup/appData.ts (XR-011/XR-012) can snapshot/replay this row without
84
+ * duplicating the literal — this module stays the single source of truth for the key. */
85
+ export const OUTBOX_KEY = 'peerpay_outbox'
84
86
 
85
87
  /** How long sent entries are kept as a sender-side token copy before pruning. */
86
88
  export const SENT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000
@@ -0,0 +1,61 @@
1
+ /**
2
+ * readBackupMaterial — what the "view/export my recovery material" screen
3
+ * shows.
4
+ *
5
+ * A wallet has exactly one secret at a time (restoreWallet.ts's write order
6
+ * guarantees that), so this never needs to reconcile two. The mnemonic wins
7
+ * when present — it is the richer material (it also derives the vault key)
8
+ * — and only when there is none does this fall back to the raw WIF, whose
9
+ * hex form is what actually gets shown/exported as `text` (the WIF encoding
10
+ * itself is still returned separately, for callers that need it as-is).
11
+ *
12
+ * `getRecoveredKey` is not even called once a mnemonic is found: an extra
13
+ * secure-store read (and, on some platforms, a biometric prompt) for a value
14
+ * that will not be used is a cost with no benefit.
15
+ *
16
+ * Neither secret present is not a recoverable state for this screen — it
17
+ * throws rather than returning something the caller could render as if it
18
+ * were valid.
19
+ *
20
+ * Does NOT decide who is allowed to call this, does not touch UI, i18n, or
21
+ * navigation.
22
+ */
23
+ import { PrivateKey } from '@bsv/sdk'
24
+ import { recoverMnemonicWallet } from '../mnemonicWallet'
25
+
26
+ export interface BackupMaterial {
27
+ text: string
28
+ mnemonic: string | null
29
+ wif: string | null
30
+ identityKey: string
31
+ }
32
+
33
+ export interface ReadBackupMaterialDeps {
34
+ getMnemonic(): Promise<string | null>
35
+ getRecoveredKey(): Promise<string | null>
36
+ }
37
+
38
+ export async function readBackupMaterial(deps: ReadBackupMaterialDeps): Promise<BackupMaterial> {
39
+ const mnemonic = await deps.getMnemonic()
40
+ if (mnemonic != null) {
41
+ return {
42
+ text: mnemonic,
43
+ mnemonic,
44
+ wif: null,
45
+ identityKey: recoverMnemonicWallet(mnemonic).identityKey
46
+ }
47
+ }
48
+
49
+ const wif = await deps.getRecoveredKey()
50
+ if (wif != null) {
51
+ const key = PrivateKey.fromWif(wif)
52
+ return {
53
+ text: key.toHex(),
54
+ mnemonic: null,
55
+ wif,
56
+ identityKey: key.toPublicKey().toString()
57
+ }
58
+ }
59
+
60
+ throw new Error('Wallet keys unavailable')
61
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * createNewWallet — the "generate a brand new wallet" path
3
+ * (mnemonic.tsx's handleGenerateNew). SDK-free: the mnemonic generator
4
+ * itself is injected (`deps.generate`, normally `generateMnemonicWallet`),
5
+ * so this module never touches `@bsv/sdk`.
6
+ *
7
+ * Guards FIRST, before generating anything: an already-built wallet or an
8
+ * already-stored identity means this call landed on a device/session that
9
+ * does not need a new secret — generating one anyway and then discovering
10
+ * `createMnemonic` refuses to overwrite it would be a wasted generation (and
11
+ * a phrase shown to the user that was never actually stored). `exists` tells
12
+ * the caller to route to the backup flow for the wallet that is already
13
+ * there instead.
14
+ *
15
+ * `createMnemonic` can also refuse for the same reason (a race: something
16
+ * else created an identity between this function's guard check and the
17
+ * store call) — checked again after a refusal, so that race still resolves
18
+ * to `exists` rather than the more alarming `refused`.
19
+ *
20
+ * Write order on success: generate → createMnemonic (the actual store,
21
+ * which is where the real "does an identity already exist" check lives) →
22
+ * `onStored` (fires BEFORE markPending/build, so the caller can show the
23
+ * words to the user while the build runs in the background — mirrors
24
+ * today's screen's setMnemonic/setMode/setHasExistingWallet timing) →
25
+ * markPending (best-effort: throwing here must not undo a secret that is
26
+ * already safely stored, so it is caught and warned, never propagated) →
27
+ * buildWalletFromMnemonic, called with NO options — a freshly generated
28
+ * mnemonic has no backup history to replay, unlike the restore path.
29
+ *
30
+ * Does NOT touch UI, i18n, or navigation.
31
+ */
32
+ export interface CreateWalletDeps {
33
+ /** generateMnemonicWallet, injected so this module stays sdk-free. */
34
+ generate(): { mnemonic: string; identityKey: string }
35
+ hasStoredIdentity(): Promise<boolean>
36
+ createMnemonic(mnemonic: string): Promise<boolean>
37
+ /** backupAttestation.markPending; errors swallowed and warned. */
38
+ markPending(identityKey: string): Promise<void>
39
+ buildWalletFromMnemonic(mnemonic: string): Promise<void>
40
+ isWalletBuilt(): boolean
41
+ }
42
+
43
+ export type CreateOutcome =
44
+ | { kind: 'created'; mnemonic: string; identityKey: string }
45
+ | { kind: 'exists' } // a wallet is already built or an identity is already stored → caller goes to backup flow
46
+ | { kind: 'refused' } // createMnemonic returned false and still no identity stored
47
+ | { kind: 'cancelled' } // opts.cancelled() became true after the identity guard → nothing generated or stored
48
+ | { kind: 'failed'; error: string }
49
+
50
+ /**
51
+ * `onStored` fires right after `createMnemonic` succeeds (before
52
+ * markPending/build) so the screen can show the words while the build runs.
53
+ *
54
+ * `cancelled`, when given, is re-checked right after the `hasStoredIdentity`
55
+ * await and before anything is generated. The caller's own screen state can
56
+ * change while that await is in flight (e.g. its route flips to the backup
57
+ * flow); if `cancelled()` now says yes, this returns `{ kind: 'cancelled' }`
58
+ * without generating or storing anything, rather than racing ahead on state
59
+ * that is already stale.
60
+ */
61
+ export async function createNewWallet(
62
+ deps: CreateWalletDeps,
63
+ opts?: { onStored?: (w: { mnemonic: string; identityKey: string }) => void; cancelled?: () => boolean }
64
+ ): Promise<CreateOutcome> {
65
+ try {
66
+ if (deps.isWalletBuilt() || (await deps.hasStoredIdentity())) {
67
+ return { kind: 'exists' }
68
+ }
69
+
70
+ if (opts?.cancelled?.()) {
71
+ return { kind: 'cancelled' }
72
+ }
73
+
74
+ const generated = deps.generate()
75
+
76
+ const stored = await deps.createMnemonic(generated.mnemonic)
77
+ if (!stored) {
78
+ return (await deps.hasStoredIdentity()) ? { kind: 'exists' } : { kind: 'refused' }
79
+ }
80
+
81
+ opts?.onStored?.(generated)
82
+
83
+ try {
84
+ await deps.markPending(generated.identityKey)
85
+ } catch (err) {
86
+ console.warn('[recovery] markPending failed (mnemonic is already stored):', err)
87
+ }
88
+
89
+ await deps.buildWalletFromMnemonic(generated.mnemonic)
90
+
91
+ return { kind: 'created', mnemonic: generated.mnemonic, identityKey: generated.identityKey }
92
+ } catch (err) {
93
+ return { kind: 'failed', error: err instanceof Error ? err.message : String(err) }
94
+ }
95
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * recoverWallet — the single retry policy for a recovery attempt (audit §3:
3
+ * on any failure, go back to the input the user already gave, never loop
4
+ * silently on a server error). Wraps `restoreWallet` (called as a value —
5
+ * this module owns no restore logic of its own, only the policy for when to
6
+ * call it again) with the two prompts a screen needs to show:
7
+ *
8
+ * - `biometric-refused`: the user declined to authenticate the store write.
9
+ * `retry` tries the exact same secret again (the common case: they meant
10
+ * to approve and fumbled the prompt); `cancel` gives up after exactly one
11
+ * store attempt — restoreWallet's own write-order guarantee means a
12
+ * single refused attempt never partially wrote anything, so there is
13
+ * nothing to unwind.
14
+ * - `confirmReplace`: asked ONCE, before the first `restoreWallet` attempt
15
+ * of a call, whenever `deps.hasStoredIdentity()` says a secret is already
16
+ * on this device (P1-7: a deep link or any other entry point must never
17
+ * silently overwrite a wallet whose phrase may be unsaved). `keep` (or a
18
+ * dismissal — see `ui/recoveryPrompts.ts`) returns `cancelled` before
19
+ * touching `restoreWallet` at all. `replace` proceeds into the ordinary
20
+ * loop below, which never re-checks `hasStoredIdentity` or re-prompts —
21
+ * a biometric retry on the SAME call must not ask the user to confirm the
22
+ * replace a second time. This also means the onboarding "replace an
23
+ * auto-created wallet" path sees this same confirm, deliberately: any
24
+ * caller of `recoverWallet` that reaches this point already has a stored
25
+ * identity to protect, in-app or not.
26
+ * - `restore-failed`: the secret was stored but the wallet was NOT built —
27
+ * the encrypted backup log failed to replay, so `WalletContext` destroys
28
+ * its never-published storage and the build never completes. `retry`
29
+ * returns control to the caller's input
30
+ * state (`retry-later`) rather than looping here — a server-side failure
31
+ * does not get better by hammering it in a tight loop, and the user may
32
+ * want to check connectivity first. `skip` re-attempts with
33
+ * `restore: false`: the secret is stored again (a no-op re-write, since
34
+ * the KEK is already held this session — see restoreWallet's docs) and
35
+ * the wallet is (re)built without asking for history replay, which is
36
+ * the only way this policy can turn a stuck restore into a usable wallet.
37
+ *
38
+ * SDK-FREE BY DESIGN, same as restoreWallet.ts: only `import type` reaches
39
+ * into `./secret`. `restoreWallet` itself is imported as a VALUE (it is
40
+ * called, not just typed), which is exactly why restoreWallet.ts must stay
41
+ * SDK-free too — a value import transitively pulls in whatever that module
42
+ * imports at runtime.
43
+ *
44
+ * The loop is bounded by construction: every branch either returns
45
+ * immediately or falls through to exactly one more `restoreWallet` call
46
+ * before the next prompt decides the branch again. No branch re-enters the
47
+ * loop without first awaiting a human's choice, so it cannot spin without a
48
+ * prompt resolving — and it does not use recursion, so there is no risk of
49
+ * unbounded stack growth either.
50
+ *
51
+ * Does NOT render prompts itself (that's `ui/recoveryPrompts.ts`'s
52
+ * `restorePrompts(t)`, injected here as `opts.prompts`), and does not touch
53
+ * i18n or navigation.
54
+ */
55
+ import { restoreWallet } from './restoreWallet'
56
+ import type { RestoreWalletDeps, RestoreHistory } from './restoreWallet'
57
+ import type { WalletSecret } from './secret'
58
+ import type { BackupMedium } from '../services/vault/backupAttestation'
59
+
60
+ export interface RestorePrompts {
61
+ biometricRefused(): Promise<'retry' | 'cancel'>
62
+ restoreFailed(error?: string): Promise<'retry' | 'skip'>
63
+ confirmReplace(): Promise<'replace' | 'keep'>
64
+ }
65
+
66
+ export type RecoveryOutcome =
67
+ | {
68
+ kind: 'ok'
69
+ identityKey: string
70
+ secret: WalletSecret
71
+ history: RestoreHistory
72
+ attested: boolean
73
+ /** See restoreWallet.ts's RestoreOutcome — forwarded verbatim. */
74
+ verified: boolean
75
+ }
76
+ | { kind: 'cancelled' } // user declined biometrics
77
+ | { kind: 'retry-later' } // restore failed and the user chose retry → caller returns to its input state
78
+ | { kind: 'failed'; error: string }
79
+
80
+ export async function recoverWallet(
81
+ deps: RestoreWalletDeps,
82
+ secret: WalletSecret,
83
+ opts: { medium: BackupMedium; prompts: RestorePrompts }
84
+ ): Promise<RecoveryOutcome> {
85
+ if (await deps.hasStoredIdentity()) {
86
+ if ((await opts.prompts.confirmReplace()) !== 'replace') return { kind: 'cancelled' }
87
+ }
88
+
89
+ let restore = true
90
+
91
+ for (;;) {
92
+ const r = await restoreWallet(deps, secret, { restore, medium: opts.medium })
93
+
94
+ if (r.kind === 'ok') {
95
+ return {
96
+ kind: 'ok',
97
+ identityKey: r.identityKey,
98
+ secret: r.secret,
99
+ history: r.history,
100
+ attested: r.attested,
101
+ verified: r.verified
102
+ }
103
+ }
104
+
105
+ if (r.kind === 'failed') {
106
+ return { kind: 'failed', error: r.error }
107
+ }
108
+
109
+ if (r.kind === 'biometric-refused') {
110
+ const choice = await opts.prompts.biometricRefused()
111
+ if (choice === 'cancel') return { kind: 'cancelled' }
112
+ continue // retry: same secret, same restore flag
113
+ }
114
+
115
+ // r.kind === 'restore-failed'
116
+ const choice = await opts.prompts.restoreFailed(r.error)
117
+ if (choice === 'retry') return { kind: 'retry-later' }
118
+ restore = false // skip: re-attempt without asking for history replay
119
+ }
120
+ }