@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
@@ -1,6 +1,134 @@
1
1
  import { Beef, Transaction, Utils } from '@bsv/sdk'
2
2
  import type { PostBeefResult, PostTxResultForTxid } from '../toolboxTypes'
3
3
 
4
+ const BROADCAST_TIMEOUT_MS = 30_000
5
+
6
+ /**
7
+ * XR-060 remainder: XR-063's body deadline below bounds how long a stalled
8
+ * body can hang, but not how LARGE a body that does arrive can be — a
9
+ * compromised/misbehaving broadcast endpoint could still force an unbounded
10
+ * JSON parse or string allocation over a multi-megabyte response before
11
+ * classification (and the already-capped log line) ever run. Comfortably
12
+ * over anything a real ARC/WoC reply ever carries.
13
+ */
14
+ const MAX_BROADCAST_BODY_BYTES = 1_000_000
15
+
16
+ /**
17
+ * Reads a body no bigger than `maxBytes`. Mirrors
18
+ * core/identity/handleRegistry/resolver.ts's readBoundedJson (XR-077 /
19
+ * SEC2-027): a declared Content-Length over the cap is refused before
20
+ * anything is read; otherwise, when the runtime exposes the body as a
21
+ * stream, chunks are counted as they arrive and the read is aborted the
22
+ * instant the running total crosses the cap, so an untrusted endpoint cannot
23
+ * make this buffer more than the cap regardless of what it claims or how it
24
+ * paces the bytes. Returns undefined when neither check applies (no
25
+ * Content-Length header and no stream to count from), leaving the caller to
26
+ * fall back to the runtime's own read and check its decoded size instead —
27
+ * a floor, not a firewall, for a runtime (or test double) with no stream.
28
+ */
29
+ async function readBoundedBytes(res: Response, maxBytes: number): Promise<Uint8Array | undefined> {
30
+ const declared = res.headers?.get?.('content-length')
31
+ if (declared) {
32
+ const n = Number(declared)
33
+ if (Number.isFinite(n) && n > maxBytes) {
34
+ throw new Error(`broadcast response declared ${n} bytes, over the ${maxBytes} byte limit`)
35
+ }
36
+ }
37
+ const reader = (res as { body?: ReadableStream<Uint8Array> | null }).body?.getReader?.()
38
+ if (!reader) return undefined
39
+ const chunks: Uint8Array[] = []
40
+ let total = 0
41
+ for (;;) {
42
+ const { done, value } = await reader.read()
43
+ if (done) break
44
+ if (!value) continue
45
+ total += value.byteLength
46
+ if (total > maxBytes) {
47
+ await reader.cancel().catch(() => {})
48
+ throw new Error(`broadcast response exceeded the ${maxBytes} byte limit while streaming`)
49
+ }
50
+ chunks.push(value)
51
+ }
52
+ const merged = new Uint8Array(total)
53
+ let offset = 0
54
+ for (const chunk of chunks) {
55
+ merged.set(chunk, offset)
56
+ offset += chunk.byteLength
57
+ }
58
+ return merged
59
+ }
60
+
61
+ async function readBoundedText(res: Response, fallback: () => Promise<string>, maxBytes: number): Promise<string> {
62
+ const bytes = await readBoundedBytes(res, maxBytes)
63
+ if (bytes !== undefined) return new TextDecoder().decode(bytes)
64
+ const text = await fallback()
65
+ if (text.length > maxBytes) {
66
+ throw new Error(`broadcast response exceeded the ${maxBytes} byte limit`)
67
+ }
68
+ return text
69
+ }
70
+
71
+ async function readBoundedJson(res: Response, fallback: () => Promise<unknown>, maxBytes: number): Promise<unknown> {
72
+ const bytes = await readBoundedBytes(res, maxBytes)
73
+ if (bytes !== undefined) return JSON.parse(new TextDecoder().decode(bytes))
74
+ const data = await fallback()
75
+ if (JSON.stringify(data).length > maxBytes) {
76
+ throw new Error(`broadcast response exceeded the ${maxBytes} byte limit`)
77
+ }
78
+ return data
79
+ }
80
+
81
+ /**
82
+ * XR-063: a broadcast provider that delivers headers within the deadline and
83
+ * then stalls (or drips) its body used to hold this promise open forever —
84
+ * the AbortController's timer was cleared as soon as fetch() resolved,
85
+ * before response.json()/text() ever ran, and since this provider sits first
86
+ * in the UntilSuccess fallback chain, a stall here blocked every later
87
+ * fallback from ever being tried. Mirrors
88
+ * core/identity/handleRegistry/resolver.ts's fetchWithTimeout: the same
89
+ * overall deadline that bounds the connection also bounds the body read, by
90
+ * racing it against a timer that aborts the underlying request too. Combined
91
+ * with readBoundedJson/readBoundedText above, the body read is now bounded
92
+ * in both time (this deadline) and size (XR-060 remainder).
93
+ */
94
+ async function fetchWithBodyDeadline(url: string, init: RequestInit, timeoutMs: number): Promise<Response> {
95
+ const controller = new AbortController()
96
+ const startedAt = Date.now()
97
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
98
+ let response: Response
99
+ try {
100
+ response = await fetch(url, { ...init, signal: controller.signal })
101
+ } finally {
102
+ clearTimeout(timer)
103
+ }
104
+ const withBodyDeadline = <T>(read: () => Promise<T>) => {
105
+ return (): Promise<T> => {
106
+ let bodyTimer: ReturnType<typeof setTimeout> | undefined
107
+ return new Promise<T>((resolve, reject) => {
108
+ bodyTimer = setTimeout(
109
+ () => {
110
+ controller.abort()
111
+ reject(new Error(`body did not complete within ${timeoutMs}ms`))
112
+ },
113
+ Math.max(0, timeoutMs - (Date.now() - startedAt))
114
+ )
115
+ void read().then(resolve, reject)
116
+ }).finally(() => {
117
+ if (bodyTimer !== undefined) clearTimeout(bodyTimer)
118
+ })
119
+ }
120
+ }
121
+ if (typeof response.json === 'function') {
122
+ const originalJson = response.json.bind(response)
123
+ response.json = withBodyDeadline(() => readBoundedJson(response, originalJson, MAX_BROADCAST_BODY_BYTES))
124
+ }
125
+ if (typeof response.text === 'function') {
126
+ const originalText = response.text.bind(response)
127
+ response.text = withBodyDeadline(() => readBoundedText(response, originalText, MAX_BROADCAST_BODY_BYTES))
128
+ }
129
+ return response
130
+ }
131
+
4
132
  /**
5
133
  * ARC intermediate statuses that still mean "accepted for relay".
6
134
  * Arcade often replies immediately with RECEIVED (HTTP 202); SEEN_* / MINED
@@ -8,11 +136,53 @@ import type { PostBeefResult, PostTxResultForTxid } from '../toolboxTypes'
8
136
  * non-double-spend 2xx as success — match that so we do not fail over to WoC
9
137
  * after Arcade already accepted the tx.
10
138
  */
11
- const ARC_DOUBLE_SPEND_STATUSES = new Set([
12
- 'DOUBLE_SPEND_ATTEMPTED',
13
- 'SEEN_IN_ORPHAN_MEMPOOL'
139
+ const ARC_DOUBLE_SPEND_STATUSES = new Set(['DOUBLE_SPEND_ATTEMPTED'])
140
+
141
+ /**
142
+ * XR-062: SEEN_IN_ORPHAN_MEMPOOL means the parent hasn't propagated yet — a
143
+ * transport/timing condition, not a proven conflict. offline/plan.ts's
144
+ * applyOutcome routes any `doubleSpend` outcome into a terminal, irreversible
145
+ * rejection cascade (the tx and every descendant, with reservations
146
+ * released), so lumping this in with a real double spend permanently kills a
147
+ * valid chained/offline payment purely from ordinary propagation timing.
148
+ * Treat it as retryable instead, like any other service hiccup.
149
+ */
150
+ const ARC_RETRYABLE_STATUSES = new Set(['SEEN_IN_ORPHAN_MEMPOOL'])
151
+
152
+ /**
153
+ * XR-064: explicit ARC statuses that mean "accepted for relay". A custom
154
+ * (person-configured) ARC endpoint's success predicate used to be
155
+ * `response.ok && data.txStatus !== 'REJECTED'` — no txid match, no
156
+ * requirement that txStatus be one of these. An on-path attacker on a
157
+ * person-chosen plaintext endpoint (or a misbehaving deployment) could
158
+ * therefore return a bare `200 {}` and have it accepted as delivery,
159
+ * suppressing the real broadcast/fallback chain for that attempt.
160
+ */
161
+ const ARC_ACCEPTED_STATUSES = new Set([
162
+ 'RECEIVED',
163
+ 'STORED',
164
+ 'SENT_TO_NETWORK',
165
+ 'ACCEPTED_BY_NETWORK',
166
+ 'SEEN_ON_NETWORK',
167
+ 'SEEN_MULTIPLE_NODES',
168
+ 'MINED',
169
+ 'IMMUTABLE'
14
170
  ])
15
171
 
172
+ /**
173
+ * XR-060: a compromised/misbehaving broadcast endpoint can answer with a
174
+ * response body far larger than any real ARC/WoC reply. Classification below
175
+ * still runs over the full body — this only bounds what a diagnostic log line
176
+ * repeats into memory/log storage.
177
+ */
178
+ const MAX_LOGGED_BODY_CHARS = 2000
179
+
180
+ function loggableSnippet(text: string): string {
181
+ return text.length > MAX_LOGGED_BODY_CHARS
182
+ ? `${text.slice(0, MAX_LOGGED_BODY_CHARS)}… [${text.length} chars total]`
183
+ : text
184
+ }
185
+
16
186
  /**
17
187
  * Shared response handling for ARC-compatible services (Arcade, Taal, GorillaPool).
18
188
  * Maps txStatus to the correct PostTxResultForTxid fields.
@@ -28,21 +198,30 @@ export function handleArcResponse(
28
198
  const txResult: PostTxResultForTxid = {
29
199
  txid: data.txid || txids[0],
30
200
  status: 'error',
31
- notes: [{
32
- when: new Date().toISOString(),
33
- what: `${serviceName}PostEF`,
34
- txStatus: data.txStatus,
35
- httpStatus: response.status
36
- }]
201
+ notes: [
202
+ {
203
+ when: new Date().toISOString(),
204
+ what: `${serviceName}PostEF`,
205
+ txStatus: data.txStatus,
206
+ httpStatus: response.status
207
+ }
208
+ ]
37
209
  }
210
+ const hasAcceptedStatus = data.txStatus !== undefined && ARC_ACCEPTED_STATUSES.has(data.txStatus)
211
+ const hasMatchingTxid = data.txid !== undefined && data.txid === txids[0]
38
212
  if (data.txStatus && ARC_DOUBLE_SPEND_STATUSES.has(data.txStatus)) {
39
213
  txResult.doubleSpend = true
40
- } else if (response.ok && data.txStatus !== 'REJECTED') {
214
+ } else if (data.txStatus && ARC_RETRYABLE_STATUSES.has(data.txStatus)) {
215
+ txResult.serviceError = true
216
+ } else if (response.ok && data.txStatus !== 'REJECTED' && (hasAcceptedStatus || hasMatchingTxid)) {
41
217
  // RECEIVED / STORED / SENT_TO_NETWORK / ACCEPTED_BY_NETWORK / SEEN_* / MINED
42
218
  // all mean the broadcaster accepted the tx. Page-load 402 must not wait for
43
- // SSE SEEN_ON_NETWORK before treating the post as successful.
219
+ // SSE SEEN_ON_NETWORK before treating the post as successful. An
220
+ // unrecognized-but-matching-txid response is also accepted (forward
221
+ // compatibility with a status this list doesn't know yet) — but a bare
222
+ // or unrelated response is not (XR-064).
44
223
  txResult.status = 'success'
45
- } else if (data.txStatus === 'REJECTED' || !response.ok) {
224
+ } else {
46
225
  txResult.serviceError = true
47
226
  }
48
227
  return txResult
@@ -58,10 +237,15 @@ function beefToEF(beef: Beef): Uint8Array {
58
237
 
59
238
  /**
60
239
  * Create an ARC-compatible broadcast service that posts EF-format transactions.
240
+ *
241
+ * `txPath` is where the deployment serves its submit route. Arcade serves
242
+ * POST /tx at the root; standard ARC (TAAL, GorillaPool) serves POST /v1/tx and
243
+ * answers POST /tx with 404. Both take EF as application/octet-stream.
61
244
  */
62
245
  function createArcBroadcastService(
63
246
  name: string,
64
247
  arcUrl: string,
248
+ txPath: '/tx' | '/v1/tx',
65
249
  headers: Record<string, string>
66
250
  ) {
67
251
  return {
@@ -70,29 +254,25 @@ function createArcBroadcastService(
70
254
  const r: PostBeefResult = { name, status: 'success', txidResults: [] }
71
255
  try {
72
256
  const ef = beefToEF(beef)
73
- const controller = new AbortController()
74
- const timeout = setTimeout(() => controller.abort(), 30_000)
75
- let response: Response
76
- try {
77
- response = await fetch(`${arcUrl}/tx`, {
257
+ const response = await fetchWithBodyDeadline(
258
+ `${arcUrl}${txPath}`,
259
+ {
78
260
  method: 'POST',
79
261
  headers: {
80
262
  'Content-Type': 'application/octet-stream',
81
263
  ...headers
82
264
  },
83
- body: ef as unknown as BodyInit,
84
- signal: controller.signal
85
- })
86
- } finally {
87
- clearTimeout(timeout)
88
- }
265
+ body: ef as unknown as BodyInit
266
+ },
267
+ BROADCAST_TIMEOUT_MS
268
+ )
89
269
  const data = await response.json()
90
- console.log(`[${name}] POST /tx ${response.status}`, JSON.stringify(data))
270
+ console.log(`[${name}] POST ${txPath} ${response.status}`, loggableSnippet(JSON.stringify(data)))
91
271
  const txResult = handleArcResponse(name, response, data, txids)
92
272
  r.txidResults.push(txResult)
93
273
  r.status = txResult.status
94
274
  } catch (err: any) {
95
- console.log(`[${name}] POST /tx error: ${err.message}`)
275
+ console.log(`[${name}] POST ${txPath} error: ${err.message}`)
96
276
  r.status = 'error'
97
277
  r.txidResults.push({
98
278
  txid: txids[0],
@@ -110,7 +290,7 @@ function createArcBroadcastService(
110
290
  * Arcade broadcast service — EF format with callback token for SSE updates.
111
291
  */
112
292
  export function createArcadeBroadcastService(arcadeUrl: string, callbackToken: string) {
113
- return createArcBroadcastService('Arcade', arcadeUrl, {
293
+ return createArcBroadcastService('Arcade', arcadeUrl, '/tx', {
114
294
  'X-CallbackToken': callbackToken,
115
295
  'X-FullStatusUpdates': 'true'
116
296
  })
@@ -122,28 +302,36 @@ export function createArcadeBroadcastService(arcadeUrl: string, callbackToken: s
122
302
  export function createTaalBroadcastService(arcUrl: string, apiKey?: string) {
123
303
  const headers: Record<string, string> = {}
124
304
  if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`
125
- return createArcBroadcastService('TaalArc', arcUrl, headers)
305
+ return createArcBroadcastService('TaalArc', arcUrl, '/v1/tx', headers)
126
306
  }
127
307
 
128
308
  /**
129
309
  * GorillaPool ARC broadcast service — EF format.
130
310
  */
131
311
  export function createGorillaPoolBroadcastService(arcUrl: string) {
132
- return createArcBroadcastService('GorillaPoolArc', arcUrl, {})
312
+ return createArcBroadcastService('GorillaPoolArc', arcUrl, '/v1/tx', {})
133
313
  }
134
314
 
135
315
  /**
136
316
  * WhatsOnChain broadcast service — raw tx hex.
137
317
  */
138
318
  export function createWocBroadcastService(chain: string, apiKey?: string) {
319
+ // XQ-011: `chain` here is WalletContext.tsx's un-normalized `walletChain`,
320
+ // which a corrupted/garbage persisted finalConfig.network value passes
321
+ // through unchanged (toWalletChain only special-cases the literal
322
+ // 'teratest'). Every sibling consumer of that same raw value —
323
+ // chaintracksUrlFor, the backupChain ternary that actually buckets which
324
+ // local DB is opened, walletDbRegistry's registry key — fails safe by
325
+ // collapsing any unrecognized string to a teratest/testnet bucket. This
326
+ // switch used to do the opposite, defaulting an unrecognized value to the
327
+ // live mainnet broadcast endpoint: the most privileged branch, not the
328
+ // least. Fail safe the same direction as every other consumer instead.
139
329
  const baseUrl =
140
330
  chain === 'main'
141
331
  ? 'https://api.whatsonchain.com/v1/bsv/main'
142
332
  : chain === 'test'
143
333
  ? 'https://api.whatsonchain.com/v1/bsv/test'
144
- : chain === 'ttn'
145
- ? 'https://api.woc-ttn.bsvblockchain.tech/v1/bsv/test'
146
- : 'https://api.whatsonchain.com/v1/bsv/main'
334
+ : 'https://api.woc-ttn.bsvblockchain.tech/v1/bsv/test'
147
335
  const name = 'WhatsOnChain'
148
336
 
149
337
  return {
@@ -153,26 +341,22 @@ export function createWocBroadcastService(chain: string, apiKey?: string) {
153
341
  try {
154
342
  const tx = Transaction.fromBEEF(beef.toBinary())
155
343
  const rawHex = Utils.toHex(tx.toBinary())
156
- const controller = new AbortController()
157
- const timeout = setTimeout(() => controller.abort(), 30_000)
158
- let response: Response
159
- try {
160
- const headers: Record<string, string> = {
161
- 'Content-Type': 'application/json',
162
- 'Accept': 'text/plain'
163
- }
164
- if (apiKey) headers['woc-api-key'] = apiKey
165
- response = await fetch(`${baseUrl}/tx/raw`, {
344
+ const headers: Record<string, string> = {
345
+ 'Content-Type': 'application/json',
346
+ Accept: 'text/plain'
347
+ }
348
+ if (apiKey) headers['woc-api-key'] = apiKey
349
+ const response = await fetchWithBodyDeadline(
350
+ `${baseUrl}/tx/raw`,
351
+ {
166
352
  method: 'POST',
167
353
  headers,
168
- body: JSON.stringify({ txhex: rawHex }),
169
- signal: controller.signal
170
- })
171
- } finally {
172
- clearTimeout(timeout)
173
- }
354
+ body: JSON.stringify({ txhex: rawHex })
355
+ },
356
+ BROADCAST_TIMEOUT_MS
357
+ )
174
358
  const body = await response.text()
175
- console.log(`[${name}] POST /tx/raw ${response.status}`, body)
359
+ console.log(`[${name}] POST /tx/raw ${response.status}`, loggableSnippet(body))
176
360
  const txResult: PostTxResultForTxid = {
177
361
  txid: txids[0],
178
362
  status: 'error',
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Auto-approve accounting for spendingAuthorizationCallback (misc-p2-04,
3
+ * MITM-P1-hijacked-sessions-unprompted's spending-accounting half).
4
+ *
5
+ * Previously a single module-level `lastAutoApproveTime` gated EVERY
6
+ * originator with one global cooldown and no cumulative total — so multiple
7
+ * paired origins accidentally throttled each other, while a single origin
8
+ * alone could still auto-approve up to the per-request threshold every
9
+ * cooldown window forever (≈0.0864 BSV/day at the shipped defaults). This
10
+ * module replaces that with: a per-originator cooldown (so origins no
11
+ * longer throttle each other) PLUS a global rolling 24h cumulative cap
12
+ * across every originator (so no single origin, or combination of
13
+ * originators, can auto-approve an unbounded total). A ledger entry records
14
+ * every APPROVED auto-approval so the cap can be computed and pruned.
15
+ *
16
+ * Pure and dependency-injected (no AsyncStorage, no Date.now()) so it can be
17
+ * unit tested deterministically; the caller (WalletContext) owns wiring the
18
+ * ledger to persistent storage.
19
+ */
20
+
21
+ const DAY_MS = 24 * 60 * 60 * 1000
22
+
23
+ export type AutoApproveReason = 'over-threshold' | 'cooldown' | 'daily-cap' | null
24
+
25
+ export interface AutoApproveDecision {
26
+ approve: boolean
27
+ reason: AutoApproveReason
28
+ }
29
+
30
+ export interface AutoApproveLedgerEntry {
31
+ originator: string
32
+ satoshis: number
33
+ at: number
34
+ }
35
+
36
+ export interface AutoApprovePolicyDeps {
37
+ /** Current time, ms since epoch. Injected so tests can control the clock. */
38
+ now: () => number
39
+ /** Read fresh on every decision, matching the existing threshold-read-per-request behaviour. */
40
+ threshold: () => number
41
+ /** Minimum ms between two auto-approvals for the SAME originator. */
42
+ cooldownMs: number
43
+ /** Global rolling-24h cumulative cap on auto-approved satoshis, across every originator. */
44
+ dailyCapSats: number
45
+ }
46
+
47
+ export interface AutoApprovePolicy {
48
+ /** Decide whether to auto-approve, WITHOUT recording anything. */
49
+ shouldAutoApprove(args: { originator: string; satoshis: number }): AutoApproveDecision
50
+ /** Record an approval that was actually granted (call only when `shouldAutoApprove` said yes). */
51
+ record(args: { originator: string; satoshis: number; at: number }): void
52
+ /** Snapshot of the current (already-pruned as of last access) ledger, for persistence. */
53
+ getLedger(): AutoApproveLedgerEntry[]
54
+ /** Restore a ledger previously returned by `getLedger`, e.g. from AsyncStorage at startup. */
55
+ loadLedger(entries: AutoApproveLedgerEntry[]): void
56
+ }
57
+
58
+ export function createAutoApprovePolicy(deps: AutoApprovePolicyDeps): AutoApprovePolicy {
59
+ const lastApproveAtByOriginator = new Map<string, number>()
60
+ let ledger: AutoApproveLedgerEntry[] = []
61
+
62
+ function pruneLedger(now: number): void {
63
+ ledger = ledger.filter(entry => now - entry.at < DAY_MS)
64
+ }
65
+
66
+ function dailyTotal(now: number): number {
67
+ pruneLedger(now)
68
+ return ledger.reduce((sum, entry) => sum + entry.satoshis, 0)
69
+ }
70
+
71
+ return {
72
+ shouldAutoApprove({ originator, satoshis }) {
73
+ const threshold = deps.threshold()
74
+ if (!(threshold > 0) || satoshis > threshold) {
75
+ return { approve: false, reason: 'over-threshold' }
76
+ }
77
+
78
+ const now = deps.now()
79
+ const lastApproveAt = lastApproveAtByOriginator.get(originator) ?? 0
80
+ if (now - lastApproveAt < deps.cooldownMs) {
81
+ return { approve: false, reason: 'cooldown' }
82
+ }
83
+
84
+ if (dailyTotal(now) + satoshis > deps.dailyCapSats) {
85
+ return { approve: false, reason: 'daily-cap' }
86
+ }
87
+
88
+ return { approve: true, reason: null }
89
+ },
90
+
91
+ record({ originator, satoshis, at }) {
92
+ lastApproveAtByOriginator.set(originator, at)
93
+ ledger.push({ originator, satoshis, at })
94
+ pruneLedger(at)
95
+ },
96
+
97
+ getLedger() {
98
+ return ledger.slice()
99
+ },
100
+
101
+ loadLedger(entries) {
102
+ ledger = entries.slice()
103
+ }
104
+ }
105
+ }
@@ -0,0 +1,19 @@
1
+ import { Hash, Utils, type KeyDeriver } from '@bsv/sdk'
2
+
3
+ /**
4
+ * Derive the Arcade/broadcast X-CallbackToken from PRIVATE key material.
5
+ *
6
+ * Previously this was `keyDeriver.identityKey.substring(0, 32)` (misc-p2-06)
7
+ * — the first 32 hex chars of the wallet's own PUBLIC identity key, a value
8
+ * routinely disclosed to every counterparty and resolvable via the handle
9
+ * registry, so it gave the callback header no confidentiality at all.
10
+ *
11
+ * Instead derive a BRC-42 private key under a fixed protocol/keyID for
12
+ * counterparty 'self' and hash it. Deterministic per wallet build, but only
13
+ * this wallet's root key can compute it — unlike the public identity key.
14
+ */
15
+ export function deriveCallbackToken(keyDeriver: Pick<KeyDeriver, 'derivePrivateKey'>): string {
16
+ const priv = keyDeriver.derivePrivateKey([2, 'arcade callback token'], '1', 'self')
17
+ const digest = Hash.sha256(priv.toArray())
18
+ return Utils.toHex(digest).slice(0, 32)
19
+ }
@@ -60,8 +60,20 @@ function tierLimits(): WalletArgLimits {
60
60
  }
61
61
  }
62
62
 
63
- /** The calls that can carry transaction bytes. */
64
- const SIZED = new Set<keyof WalletInterface>(['createAction', 'signAction', 'internalizeAction'])
63
+ /** The calls that can carry transaction bytes, plus the byte-bearing crypto
64
+ * calls (XR-026) that previously had no per-call cap at all beyond the raw
65
+ * transport ceiling shared with every other paired-RPC method. */
66
+ const SIZED = new Set<keyof WalletInterface>([
67
+ 'createAction',
68
+ 'signAction',
69
+ 'internalizeAction',
70
+ 'encrypt',
71
+ 'decrypt',
72
+ 'createHmac',
73
+ 'verifyHmac',
74
+ 'createSignature',
75
+ 'verifySignature'
76
+ ])
65
77
 
66
78
  /**
67
79
  * Wrap `wallet` so oversize arguments are refused before it is called.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * XR-027: saved pairing authority.
3
+ *
4
+ * ConnectionStore persists an approved (origin, topic, protocolID,
5
+ * backendIdentityKey) tuple in plain AsyncStorage. Reconnect used to trust
6
+ * that tuple structurally -- any well-formed replacement (a different
7
+ * backend/origin, planted by anything that can write to AsyncStorage)
8
+ * authenticated exactly like the real one on the next Reconnect tap.
9
+ *
10
+ * The fix computes an HMAC over the tuple with the ADMIN-scoped wallet, under
11
+ * the `connection authority` namespace reserved in
12
+ * core/services/vault/guard.ts, and stores it alongside the record. Reconnect
13
+ * re-verifies it before ever trusting the tuple.
14
+ *
15
+ * WHY ADMIN-SCOPED, NOT THE WALLET ALREADY PASSED TO connect()/reconnect().
16
+ * That WalletClient is deliberately scoped to the PAIRED SITE'S OWN
17
+ * originator (PairScreen.tsx/ConnectionsScreen.tsx construct it with
18
+ * `external.originator`, never ADMIN_ORIGINATOR) and forwards
19
+ * createHmac/verifyHmac for any non-reserved protocol namespace straight to
20
+ * the underlying wallet (see IMPLEMENTED_METHODS in
21
+ * WalletConnectionContext.tsx). Computing this tag with that wallet -- under
22
+ * ANY namespace it could reach -- would let the paired peer itself mint or
23
+ * reproduce the exact same tag over that same already-allowlisted RPC method,
24
+ * which authenticates nothing. Deliberately independent of connect()/
25
+ * reconnect(): this module never touches either function or its signature --
26
+ * the two pairing/reconnect screens compute and verify the tag themselves,
27
+ * with their own admin-scoped wallet, entirely around those calls.
28
+ */
29
+ import type { WalletInterface } from '@bsv/sdk'
30
+ import {
31
+ CONNECTION_AUTHORITY_PROTOCOL_ID,
32
+ buildConnectionAuthorityMessage,
33
+ type ConnectionAuthorityTuple
34
+ } from './walletConnectionValidation'
35
+
36
+ type HmacCapableWallet = Pick<WalletInterface, 'createHmac' | 'verifyHmac'>
37
+
38
+ function authorityMessageBytes(tuple: ConnectionAuthorityTuple): number[] {
39
+ return Array.from(new TextEncoder().encode(buildConnectionAuthorityMessage(tuple)))
40
+ }
41
+
42
+ /** Called once, at approval time, by the screen that just showed the user
43
+ * this exact tuple (PairScreen's Approve, ConnectionsScreen's scan/paste) --
44
+ * BEFORE connect() is invoked, from data the screen already fully controls.
45
+ * `adminWallet` must be wrapped in guardVaultAccess(..., adminOriginator)
46
+ * (and typically capWalletArgs too) exactly like every other external-facing
47
+ * wallet in this package; passing `adminOriginator` as the call's originator
48
+ * is what lets guard.ts's reservation recognize this as trusted. */
49
+ export async function computeConnectionAuthorityTag(
50
+ adminWallet: HmacCapableWallet,
51
+ adminOriginator: string,
52
+ tuple: ConnectionAuthorityTuple
53
+ ): Promise<string> {
54
+ const { hmac } = await adminWallet.createHmac(
55
+ {
56
+ protocolID: CONNECTION_AUTHORITY_PROTOCOL_ID,
57
+ keyID: tuple.topic,
58
+ counterparty: 'self',
59
+ data: authorityMessageBytes(tuple)
60
+ },
61
+ adminOriginator
62
+ )
63
+ return Buffer.from(hmac).toString('base64url')
64
+ }
65
+
66
+ /**
67
+ * Re-derives the tag over the CURRENT (possibly tampered) tuple and compares
68
+ * it to the one on file. Never throws: a missing tag, a malformed tag, a
69
+ * mismatched tuple, or any wallet-side failure are all indistinguishable
70
+ * "not authentic" outcomes to the caller, which must treat every one of them
71
+ * as "needs re-approval" -- never silently reconnect. `@bsv/sdk`'s
72
+ * `verifyHmac` itself REJECTS (does not resolve false) on a mismatched HMAC,
73
+ * which the try/catch below turns into `false` like every other failure mode.
74
+ */
75
+ export async function verifyConnectionAuthorityTag(
76
+ adminWallet: HmacCapableWallet,
77
+ adminOriginator: string,
78
+ tuple: ConnectionAuthorityTuple,
79
+ tag: string | undefined
80
+ ): Promise<boolean> {
81
+ if (!tag) return false
82
+ try {
83
+ const hmac = Array.from(Buffer.from(tag, 'base64url'))
84
+ const { valid } = await adminWallet.verifyHmac(
85
+ {
86
+ protocolID: CONNECTION_AUTHORITY_PROTOCOL_ID,
87
+ keyID: tuple.topic,
88
+ counterparty: 'self',
89
+ data: authorityMessageBytes(tuple),
90
+ hmac
91
+ },
92
+ adminOriginator
93
+ )
94
+ return valid === true
95
+ } catch {
96
+ return false
97
+ }
98
+ }