@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
@@ -9,6 +9,7 @@ import {
9
9
  buildPairingSignatureMessage,
10
10
  buildRelayWebSocketUrl,
11
11
  MAX_IN_FLIGHT_RPC,
12
+ MAX_IN_FLIGHT_RPC_BYTES,
12
13
  MAX_RELAY_RESPONSE_BYTES,
13
14
  parseBoundedWireEnvelope,
14
15
  parseRelayResponse,
@@ -141,6 +142,16 @@ async function readBoundedRelayResponse(res: Response): Promise<string> {
141
142
  return new TextDecoder().decode(joined)
142
143
  }
143
144
 
145
+ // XR-025 (SEC2-094): no declared Content-Length AND no streamable body
146
+ // means there is no way to observe bytes as they arrive — `res.text()`
147
+ // would fully buffer the response before any size check could run, on an
148
+ // attacker-controlled canonical origin drawn straight from signed
149
+ // pairing/QR data. Fail closed rather than allocate an unbounded body in
150
+ // that specific case; a DECLARED length was already checked above, so
151
+ // reading the body here is still bounded defense-in-depth, not the gap.
152
+ if (declared === null) {
153
+ throw new Error('Origin server relay response has no declared length and cannot be streamed')
154
+ }
144
155
  const text = await res.text()
145
156
  if (text.length > MAX_RELAY_RESPONSE_BYTES || new TextEncoder().encode(text).length > MAX_RELAY_RESPONSE_BYTES) {
146
157
  throw new Error('Origin server relay response is too large')
@@ -176,6 +187,26 @@ export function useWalletConnection() {
176
187
  return ctx
177
188
  }
178
189
 
190
+ /**
191
+ * XR-018: WalletContext.tsx's logout() is a REACT ANCESTOR of
192
+ * WalletConnectionProvider (app/_layout.tsx nests the connection provider
193
+ * INSIDE WalletContextProvider), so it cannot call useWalletConnection()
194
+ * itself — there is no ancestor WalletConnectionContext.Provider at that
195
+ * point in the tree. Exactly one WalletConnectionProvider is ever mounted
196
+ * (app/_layout.tsx), matching this package's other module-level
197
+ * single-wallet-session state (e.g. WalletContext.tsx's
198
+ * autoApproveThresholdSnapshot), so a plain module-level handle is enough to
199
+ * let logout revoke any live paired session without becoming a consumer of
200
+ * this context.
201
+ */
202
+ let activeDisconnect: (() => void) | null = null
203
+
204
+ /** Tear down any live paired RPC socket. No-op if no WalletConnectionProvider
205
+ * is mounted or no session is currently connected. */
206
+ export function disconnectActivePairedSession(): void {
207
+ activeDisconnect?.()
208
+ }
209
+
179
210
  interface WalletConnectionProviderProps {
180
211
  children: React.ReactNode
181
212
  /** Sent to the desktop session as `walletMeta.name` during pairing. Host
@@ -196,27 +227,72 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
196
227
  const navTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
197
228
  const appStateTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
198
229
  const intentionalCloseRef = useRef(false)
230
+ // XR-018: bumped every time an existing socket is torn down (disconnect(),
231
+ // or connect()/reconnect() superseding a prior live session). wireSocket
232
+ // captures the value at wiring time as "myGeneration" and every one of its
233
+ // callbacks re-checks it before doing anything — closing/detaching a
234
+ // socket's handlers cannot cancel an onmessage invocation that is already
235
+ // mid-flight (awaiting decrypt or the durable sequence write) when the
236
+ // teardown happens, so without this check that in-flight message could
237
+ // still reach handleRpc and dispatch privileged RPC after the app has
238
+ // already moved on to a different (or no) session.
239
+ const connectionGenerationRef = useRef(0)
199
240
  // Snapshot of sessionMeta for use inside async WS callbacks
200
241
  const sessionMetaRef = useRef<SessionMeta | null>(null)
201
242
  useEffect(() => { sessionMetaRef.current = sessionMeta }, [sessionMeta])
202
243
 
203
244
  // ── Disconnect ─────────────────────────────────────────────────────────────
204
245
 
205
- const disconnect = useCallback(() => {
246
+ /** Fully detach `ws`'s handlers and close it, so it can never fire
247
+ * onopen/onmessage/onerror/onclose for this provider again, and bump the
248
+ * connection generation so any invocation of those handlers already
249
+ * in-flight for it is dropped too (see connectionGenerationRef). No-op for
250
+ * a null socket. */
251
+ const closeAndDetachSocket = useCallback((ws: WebSocket | null) => {
252
+ connectionGenerationRef.current++
253
+ if (wsRef.current === ws) wsRef.current = null
254
+ if (!ws) return
255
+ ws.onopen = null
256
+ ws.onmessage = null
257
+ ws.onerror = null
258
+ ws.onclose = null
259
+ try { ws.close() } catch { /* already closing/closed */ }
260
+ }, [])
261
+
262
+ /** XR-018: this provider models exactly one live paired session at a time
263
+ * (a single wsRef/sessionMeta) — connect() and reconnect() call this
264
+ * BEFORE wiring a new socket so a previously-live socket for a DIFFERENT
265
+ * session is fully torn down first, instead of being silently orphaned
266
+ * with full RPC authority intact while wsRef moves on to the new one.
267
+ * Deliberately leaves status/sessionMeta React state alone: the caller
268
+ * sets its own right after via setSessionMeta(meta), and flipping to
269
+ * 'idle' here first would flash the UI back out of "connecting" for no
270
+ * reason. */
271
+ const supersedeExistingSocket = useCallback(() => {
206
272
  const topic = sessionMetaRef.current?.topic
207
273
  if (topic) {
208
274
  void SecureStore.setItemAsync(lastSeqKey(topic), String(lastSeqRef.current))
209
275
  connectionStore.setStatus(topic, 'disconnected')
210
276
  }
211
- intentionalCloseRef.current = true
212
- const ws = wsRef.current
213
- wsRef.current = null
214
- ws?.close()
277
+ closeAndDetachSocket(wsRef.current)
215
278
  if (navTimerRef.current) { clearTimeout(navTimerRef.current); navTimerRef.current = null }
216
279
  if (appStateTimerRef.current) { clearTimeout(appStateTimerRef.current); appStateTimerRef.current = null }
280
+ }, [closeAndDetachSocket])
281
+
282
+ const disconnect = useCallback(() => {
283
+ intentionalCloseRef.current = true
284
+ supersedeExistingSocket()
217
285
  setSessionMeta(null)
218
286
  setStatus('idle')
219
- }, [])
287
+ }, [supersedeExistingSocket])
288
+
289
+ // Keep the module-level handle current so logout (a react ancestor of this
290
+ // provider) can reach the LATEST disconnect closure. Clearing it on
291
+ // unmount stops a stale/unmounted provider's disconnect from being called.
292
+ useEffect(() => {
293
+ activeDisconnect = disconnect
294
+ return () => { if (activeDisconnect === disconnect) activeDisconnect = null }
295
+ }, [disconnect])
220
296
 
221
297
  // ── Nav timer (pair screen lifecycle) ─────────────────────────────────────
222
298
 
@@ -302,22 +378,64 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
302
378
  wallet: WalletClient,
303
379
  meta: SessionMeta,
304
380
  initialSeq: number,
381
+ // XR-018: this socket's own identity for the generation check below —
382
+ // the caller (connect()/reconnect()) allocates it right after
383
+ // supersedeExistingSocket() and before opening `ws`, and reuses the same
384
+ // value to guard its own onopen handler, so a stale in-flight onopen
385
+ // from a socket superseded in the meantime is guarded exactly like
386
+ // onmessage/onerror/onclose below.
387
+ myGeneration: number,
305
388
  onFirstMessage: () => void,
306
389
  ) {
307
390
  wsRef.current = ws
308
391
  lastSeqRef.current = initialSeq
309
392
  let firstMessageFired = false
310
393
  let inFlightRpc = 0
394
+ let inFlightBytes = 0
395
+ // XR-021 review follow-up: MAX_IN_FLIGHT_RPC lets several messages
396
+ // decrypt concurrently, so the sequence check-then-durable-write-then-
397
+ // advance below is chained through this promise — each message's commit
398
+ // only runs once the previous one has fully resolved (write landed, ref
399
+ // advanced), and re-checks the watermark at that point. Without this,
400
+ // two concurrent messages can both pass the check against the same stale
401
+ // watermark and have their durable writes resolve out of order,
402
+ // regressing the watermark and letting an already-executed higher-
403
+ // sequence ciphertext be replayed immediately (no crash needed).
404
+ let seqCommitChain: Promise<boolean> = Promise.resolve(true)
311
405
 
312
406
  ws.onmessage = async event => {
407
+ // XR-018: this socket may have already been superseded (a concurrent
408
+ // disconnect()/connect()/reconnect() closed and detached it) between
409
+ // the relay delivering this event and this handler running — closing
410
+ // a socket cannot cancel an event already queued for it. Drop it
411
+ // before touching any in-flight counters.
412
+ if (connectionGenerationRef.current !== myGeneration) return
313
413
  if (inFlightRpc >= MAX_IN_FLIGHT_RPC) {
314
414
  console.warn('[WalletConnection] dropping message: too many requests in flight')
315
415
  return
316
416
  }
317
417
  inFlightRpc++
418
+ let reservedBytes = 0
318
419
  try {
319
420
  const envelope = parseBoundedWireEnvelope(event.data, meta.topic)
320
421
 
422
+ // XR-026: gate on the AGGREGATE estimated plaintext size of every
423
+ // message currently decrypting/dispatching, not just the count.
424
+ // MAX_IN_FLIGHT_RPC alone lets up to 4 near-ceiling messages decrypt
425
+ // at once; base64-decoded length is a tight estimate of the eventual
426
+ // plaintext (authenticated encryption only adds a small fixed
427
+ // overhead), and this must be checked BEFORE decryptPayload is even
428
+ // attempted — decoding the ciphertext into a number[] alone already
429
+ // allocates memory proportional to its size, before the wallet can
430
+ // authenticate it.
431
+ const estimatedBytes = Math.floor(envelope.ciphertext.length * 3 / 4)
432
+ if (inFlightBytes + estimatedBytes > MAX_IN_FLIGHT_RPC_BYTES) {
433
+ console.warn('[WalletConnection] dropping message: too many in-flight bytes')
434
+ return
435
+ }
436
+ reservedBytes = estimatedBytes
437
+ inFlightBytes += reservedBytes
438
+
321
439
  let plaintext: string
322
440
  try {
323
441
  plaintext = await decryptPayload(
@@ -336,7 +454,47 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
336
454
  console.warn('[WalletConnection] dropping message: seq', sequence, '<= lastSeq', lastSeqRef.current)
337
455
  return
338
456
  }
339
- lastSeqRef.current = sequence
457
+ // XR-021: commit the accepted sequence durably BEFORE dispatching the
458
+ // wallet's side-effecting call below (createAction, signAction, ...),
459
+ // and before advancing the in-memory watermark. Previously the
460
+ // watermark only advanced in memory, and the only durable write was
461
+ // fire-and-forget in disconnect()/onclose — a crash/kill between the
462
+ // wallet call completing and that write landing left SecureStore
463
+ // behind what actually ran, so a captured ciphertext replayed after
464
+ // reconnect re-executed the identical mutating call. Fail closed: if
465
+ // the durable write itself fails, drop the message rather than
466
+ // dispatching with no durable record of having accepted it.
467
+ //
468
+ // Chained through seqCommitChain (review follow-up): re-checks the
469
+ // watermark once it's this message's turn, so a concurrent message
470
+ // that already committed a higher sequence in the meantime causes
471
+ // this one to be dropped instead of regressing the watermark.
472
+ const accepted = await (seqCommitChain = seqCommitChain.then(async () => {
473
+ if (sequence <= lastSeqRef.current) return false
474
+ try {
475
+ await SecureStore.setItemAsync(lastSeqKey(meta.topic), String(sequence))
476
+ } catch (err) {
477
+ console.warn('[WalletConnection] dropping message: failed to persist sequence', err)
478
+ return false
479
+ }
480
+ lastSeqRef.current = sequence
481
+ return true
482
+ }))
483
+ if (!accepted) {
484
+ console.warn('[WalletConnection] dropping message: seq', sequence, 'superseded before durable commit')
485
+ return
486
+ }
487
+
488
+ // XR-018: re-check immediately before any dispatch/side-effect runs.
489
+ // The decrypt + durable sequence commit above can take long enough
490
+ // that a concurrent disconnect()/connect()/reconnect() supersedes
491
+ // this socket while this invocation was still awaiting them —
492
+ // detaching handlers at that point cannot cancel this already-
493
+ // running invocation, so the dispatch itself must also check.
494
+ if (connectionGenerationRef.current !== myGeneration) {
495
+ console.warn('[WalletConnection] dropping message: connection superseded before dispatch')
496
+ return
497
+ }
340
498
 
341
499
  if (!firstMessageFired) {
342
500
  firstMessageFired = true
@@ -352,15 +510,24 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
352
510
  // malformed outer envelope — drop silently
353
511
  } finally {
354
512
  inFlightRpc--
513
+ inFlightBytes -= reservedBytes
355
514
  }
356
515
  }
357
516
 
358
517
  ws.onerror = () => {
518
+ if (connectionGenerationRef.current !== myGeneration) return
359
519
  setErrorMsg('WebSocket connection failed')
360
520
  setStatus('error')
361
521
  }
362
522
 
363
523
  ws.onclose = () => {
524
+ // XR-018: a superseded socket's close event must never touch state for
525
+ // whatever session/socket has replaced it (or the idle state left by
526
+ // disconnect()) — closeAndDetachSocket already nulls this handler
527
+ // before calling close() for every controlled teardown path, so this
528
+ // is defense in depth for anything that still holds a reference to
529
+ // this closure directly.
530
+ if (connectionGenerationRef.current !== myGeneration) return
364
531
  const wasIntentional = intentionalCloseRef.current
365
532
  intentionalCloseRef.current = false
366
533
 
@@ -421,6 +588,13 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
421
588
  const identityResult = await wallet.getPublicKey({ identityKey: true })
422
589
  const mobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
423
590
 
591
+ // XR-018: tear down any live socket for a DIFFERENT prior session before
592
+ // wiring this one — see supersedeExistingSocket for why. myGeneration is
593
+ // allocated right after, so this connection's onopen AND wireSocket's
594
+ // handlers all guard against the same supersede event.
595
+ supersedeExistingSocket()
596
+ const myGeneration = ++connectionGenerationRef.current
597
+
424
598
  const meta: SessionMeta = {
425
599
  topic: validated.params.topic, origin: validated.external.origin, relay,
426
600
  backendIdentityKey: validated.params.backendIdentityKey, mobileIdentityKey,
@@ -431,6 +605,11 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
431
605
  const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.params.topic))
432
606
 
433
607
  ws.onopen = async () => {
608
+ // XR-018: this connection attempt may already have been superseded by
609
+ // a later connect()/reconnect()/disconnect() while relay/verify above
610
+ // were in flight — a stale send here must not touch the new session's
611
+ // state, and must not fire on an already-detached socket.
612
+ if (connectionGenerationRef.current !== myGeneration) return
434
613
  try {
435
614
  const payload = JSON.stringify({
436
615
  id: crypto.randomUUID(), seq: 1, method: 'pairing_approved',
@@ -444,14 +623,16 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
444
623
  const ciphertext = await encryptPayload(
445
624
  wallet, protocolID, validated.params.topic, validated.params.backendIdentityKey, payload
446
625
  )
626
+ if (connectionGenerationRef.current !== myGeneration) return
447
627
  ws.send(JSON.stringify({ topic: validated.params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope))
448
628
  } catch {
629
+ if (connectionGenerationRef.current !== myGeneration) return
449
630
  setErrorMsg('Failed to send pairing message')
450
631
  setStatus('error')
451
632
  }
452
633
  }
453
634
 
454
- wireSocket(ws, wallet, meta, 0, () => {
635
+ wireSocket(ws, wallet, meta, 0, myGeneration, () => {
455
636
  connectionStore.add({
456
637
  sessionId: validated.params.topic, origin: validated.external.origin, relay,
457
638
  backendIdentityKey: validated.params.backendIdentityKey, mobileIdentityKey,
@@ -460,7 +641,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
460
641
  })
461
642
  setStatus('connected')
462
643
  })
463
- }, [walletName]) // eslint-disable-line react-hooks/exhaustive-deps
644
+ }, [walletName, supersedeExistingSocket]) // eslint-disable-line react-hooks/exhaustive-deps
464
645
 
465
646
  // ── reconnect (resume from stored session) ────────────────────────────────
466
647
 
@@ -482,6 +663,13 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
482
663
  const storedSeq = await SecureStore.getItemAsync(lastSeqKey(validated.topic))
483
664
  const initialSeq = validateStoredConnectionSequence(storedSeq)
484
665
 
666
+ // XR-018: tear down any live socket for a DIFFERENT prior session before
667
+ // wiring this one — see supersedeExistingSocket for why. myGeneration is
668
+ // allocated right after, so this connection's onopen AND wireSocket's
669
+ // handlers all guard against the same supersede event.
670
+ supersedeExistingSocket()
671
+ const myGeneration = ++connectionGenerationRef.current
672
+
485
673
  const meta: SessionMeta = {
486
674
  topic: validated.topic, origin: validated.external.origin, relay,
487
675
  backendIdentityKey: validated.backendIdentityKey,
@@ -493,6 +681,8 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
493
681
  const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.topic))
494
682
 
495
683
  ws.onopen = async () => {
684
+ // XR-018: see the identical guard in connect()'s onopen.
685
+ if (connectionGenerationRef.current !== myGeneration) return
496
686
  try {
497
687
  const payload = JSON.stringify({
498
688
  id: crypto.randomUUID(), seq: initialSeq + 1, method: 'pairing_approved',
@@ -506,22 +696,24 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
506
696
  const ciphertext = await encryptPayload(
507
697
  wallet, protocolID, validated.topic, validated.backendIdentityKey, payload,
508
698
  )
699
+ if (connectionGenerationRef.current !== myGeneration) return
509
700
  ws.send(JSON.stringify({
510
701
  topic: validated.topic,
511
702
  mobileIdentityKey: validated.mobileIdentityKey,
512
703
  ciphertext,
513
704
  } satisfies WireEnvelope))
514
705
  } catch {
706
+ if (connectionGenerationRef.current !== myGeneration) return
515
707
  setErrorMsg('Failed to send reconnect message')
516
708
  setStatus('error')
517
709
  }
518
710
  }
519
711
 
520
- wireSocket(ws, wallet, meta, initialSeq, () => {
712
+ wireSocket(ws, wallet, meta, initialSeq, myGeneration, () => {
521
713
  connectionStore.setStatus(validated.topic, 'active')
522
714
  setStatus('connected')
523
715
  })
524
- }, [walletName]) // eslint-disable-line react-hooks/exhaustive-deps
716
+ }, [walletName, supersedeExistingSocket]) // eslint-disable-line react-hooks/exhaustive-deps
525
717
 
526
718
  // ── Provider ──────────────────────────────────────────────────────────────
527
719