@bsv/expo-wallet-toolbox 0.22.0 → 0.24.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.
- package/CHANGELOG.md +241 -0
- package/README.md +10 -9
- package/android/build.gradle +15 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
- package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
- package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
- package/core/backup/RemoteSyncReader.ts +71 -46
- package/core/backup/client.ts +6 -15
- package/core/backup/codec.ts +78 -13
- package/core/backup/constants.ts +3 -9
- package/core/backup/cursor.ts +8 -0
- package/core/backup/push.ts +26 -16
- package/core/backup/restore.ts +6 -5
- package/core/bridge/BrowserBridgeProvider.tsx +273 -0
- package/core/bridge/bindings.ts +459 -0
- package/core/bridge/conformance.ts +222 -0
- package/core/bridge/consent.ts +494 -0
- package/core/bridge/consentSheetSource.ts +98 -0
- package/core/bridge/dispatcher.ts +621 -0
- package/core/bridge/inbox.ts +569 -0
- package/core/bridge/index.ts +48 -0
- package/core/bridge/loopback/cors.ts +57 -0
- package/core/bridge/loopback/endpoints.ts +11 -0
- package/core/bridge/loopback/hostCheck.ts +25 -0
- package/core/bridge/loopback/index.ts +7 -0
- package/core/bridge/loopback/launchProof.ts +166 -0
- package/core/bridge/loopback/router.ts +770 -0
- package/core/bridge/loopback/routerTypes.ts +115 -0
- package/core/bridge/loopback/status.ts +52 -0
- package/core/bridge/memoryInboxStore.ts +231 -0
- package/core/bridge/permissionPolicy.ts +247 -0
- package/core/bridge/policy.ts +72 -0
- package/core/bridge/protocol/base64url.ts +64 -0
- package/core/bridge/protocol/connectionError.ts +79 -0
- package/core/bridge/protocol/constants.ts +21 -0
- package/core/bridge/protocol/continuity.ts +21 -0
- package/core/bridge/protocol/descriptor.ts +395 -0
- package/core/bridge/protocol/envelopes.ts +188 -0
- package/core/bridge/protocol/errorCodec.ts +164 -0
- package/core/bridge/protocol/json.ts +237 -0
- package/core/bridge/protocol/limits.ts +43 -0
- package/core/bridge/protocol/methods.ts +55 -0
- package/core/bridge/protocol/origin.ts +130 -0
- package/core/bridge/runtime.ts +642 -0
- package/core/bridge/runtimeFlags.ts +34 -0
- package/core/bridge/testing/conformanceCases.ts +149 -0
- package/core/bridge/testing/pageClient.ts +44 -0
- package/core/bridge/unverifiedManager.ts +97 -0
- package/core/bridge/unverifiedOriginator.ts +79 -0
- package/core/config.tsx +1 -16
- package/core/constants.ts +7 -11
- package/core/context/WalletConnectionContext.tsx +92 -49
- package/core/context/WalletContext.tsx +288 -165
- package/core/context/sessionTeardown.ts +46 -0
- package/core/context/usePairingAttempt.ts +31 -0
- package/core/e2e/broadcaster.ts +25 -0
- package/core/e2e/consentFixture.ts +46 -0
- package/core/e2e/mode.ts +42 -0
- package/core/headers/OfflineFirstChaintracks.ts +57 -107
- package/core/headers/headerConsensus.ts +230 -0
- package/core/headers/headerStore.ts +344 -122
- package/core/headers/prewarm.ts +4 -7
- package/core/headers/syncHeaders.ts +82 -12
- package/core/hooks/usePermissionQueue.ts +89 -34
- package/core/i18n/translations.tsx +958 -24
- package/core/identity/handleRegistry/client.ts +4 -2
- package/core/identity/handleRegistry/resolver.ts +7 -11
- package/core/index.ts +17 -0
- package/core/localpay/pending.ts +39 -4
- package/core/network/boundedFetch.ts +101 -0
- package/core/networks.ts +11 -13
- package/core/pay/rails/address.ts +5 -4
- package/core/pay/rails/handle.ts +3 -1
- package/core/pay/rails/sweep.ts +791 -0
- package/core/peerpay/brc29.ts +4 -0
- package/core/peerpay/handleResendRequests.ts +15 -2
- package/core/peerpay/outbox.ts +115 -2
- package/core/profiles/assertProfileEmpty.ts +2 -2
- package/core/profiles/profileStore.ts +3 -2
- package/core/services/arcadeBroadcastProvider.ts +260 -114
- package/core/services/autoApprovePolicy.ts +7 -1
- package/core/services/capWalletArgs.ts +2 -1
- package/core/services/permissionPrompts.ts +132 -0
- package/core/services/secrets/kek.ts +5 -0
- package/core/services/secrets/migration.ts +27 -2
- package/core/services/secrets/policy.ts +6 -0
- package/core/services/signingPermissionPolicy.ts +230 -2
- package/core/services/vault/VaultKeyService.ts +5 -2
- package/core/services/vault/ceremony.ts +2 -2
- package/core/services/vault/ceremonyHost.ts +1 -1
- package/core/services/vault/guard.ts +20 -0
- package/core/services/vault/outputAuthority.ts +76 -0
- package/core/services/vault/transfers.ts +52 -28
- package/core/services/vault/vaultStore.ts +60 -14
- package/core/services/walletArgLimits.ts +17 -2
- package/core/services/walletConnectionValidation.ts +13 -1
- package/core/services/walletServiceConfig.ts +8 -7
- package/core/storage/encryptedDbImage.ts +325 -0
- package/core/stores/ConnectionStore.ts +17 -0
- package/core/toolboxConfig.ts +78 -2
- package/expo-module.config.json +5 -0
- package/ios/BoundedBody.swift +15 -0
- package/ios/BsvBoundedFetch.podspec +17 -0
- package/ios/BsvBoundedFetchModule.swift +121 -0
- package/package.json +12 -8
- package/ui/bridgeSheet/ContextRelay.tsx +86 -0
- package/ui/bridgeSheet/relayedContexts.ts +21 -0
- package/ui/components/pay/AddressReceive.tsx +6 -2
- package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
- package/ui/components/pay/PayCellRow.tsx +3 -1
- package/ui/components/pay/PayForm.tsx +12 -2
- package/ui/components/pay/RecipientField.tsx +1 -0
- package/ui/components/pay/RequestHub.tsx +1 -0
- package/ui/components/pay/UniversalSend.tsx +110 -42
- package/ui/components/ui/ListRow.tsx +10 -2
- package/ui/components/ui/PermissionSheet.tsx +534 -158
- package/ui/components/ui/Sheet.tsx +59 -7
- package/ui/components/ui/sheetResumeSignal.ts +19 -0
- package/ui/components/vault/KeyChooser.tsx +1 -1
- package/ui/components/wallet/AmountInput.tsx +4 -1
- package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
- package/ui/components/wallet/ProfileButton.tsx +1 -0
- package/ui/exportDatabases.ts +94 -5
- package/ui/hooks/useExportWalletData.ts +37 -24
- package/ui/importDatabases.ts +154 -34
- package/ui/index.ts +4 -0
- package/ui/screens/ConnectionsScreen.tsx +12 -3
- package/ui/screens/PairScreen.tsx +10 -3
- package/ui/screens/PayScreen.tsx +1 -0
- package/ui/screens/TrustScreen.tsx +6 -3
- package/ui/screens/VaultScreen.tsx +13 -3
- package/ui/screens/VaultTransferScreen.tsx +6 -3
- package/ui/screens/WalletConfigScreen.tsx +30 -3
- package/ui/screens/WalletHomeScreen.tsx +7 -1
|
@@ -4,6 +4,7 @@ import * as SecureStore from 'expo-secure-store'
|
|
|
4
4
|
import { WalletClient, PrivateKey, ProtoWallet, Utils } from '@bsv/sdk'
|
|
5
5
|
import type { WalletProtocol } from '@bsv/sdk'
|
|
6
6
|
import connectionStore from '../stores/ConnectionStore'
|
|
7
|
+
import { registerSessionTeardown } from './sessionTeardown'
|
|
7
8
|
import type { Connection } from '../stores/ConnectionStore'
|
|
8
9
|
import {
|
|
9
10
|
buildPairingSignatureMessage,
|
|
@@ -20,7 +21,8 @@ import {
|
|
|
20
21
|
validatePairingTopic,
|
|
21
22
|
validateStoredConnectionSequence,
|
|
22
23
|
validateStoredConnectionFields,
|
|
23
|
-
type ConnectParams
|
|
24
|
+
type ConnectParams,
|
|
25
|
+
type OriginSessionTuple
|
|
24
26
|
} from '../services/walletConnectionValidation'
|
|
25
27
|
|
|
26
28
|
export type { ConnectParams } from '../services/walletConnectionValidation'
|
|
@@ -171,19 +173,26 @@ async function readBoundedRelayResponse(res: Response): Promise<string> {
|
|
|
171
173
|
return text
|
|
172
174
|
}
|
|
173
175
|
|
|
174
|
-
export async function fetchRelay(origin: string, topic: string): Promise<string> {
|
|
176
|
+
export async function fetchRelay(origin: string, topic: string, expected?: OriginSessionTuple): Promise<string> {
|
|
175
177
|
const validatedTopic = validatePairingTopic(topic)
|
|
176
178
|
const external = validateCanonicalExternalOrigin(origin)
|
|
179
|
+
const sessionUrl = `${external.origin}/api/session/${encodeURIComponent(validatedTopic)}`
|
|
177
180
|
const controller = new AbortController()
|
|
178
181
|
const timer = setTimeout(() => controller.abort(), 10_000)
|
|
179
182
|
try {
|
|
180
|
-
const res = await fetch(
|
|
183
|
+
const res = await fetch(sessionUrl, {
|
|
181
184
|
signal: controller.signal,
|
|
182
185
|
redirect: 'error'
|
|
183
186
|
})
|
|
184
187
|
if (!res.ok) throw new Error(`Could not fetch session from origin: HTTP ${res.status}`)
|
|
188
|
+
// React Native's XHR fetch polyfill can ignore redirect: 'error'. Only
|
|
189
|
+
// the exact requested HTTPS endpoint may supply this authority proof;
|
|
190
|
+
// missing final-URL metadata must fail closed too.
|
|
191
|
+
if (res.url !== sessionUrl || res.redirected === true) {
|
|
192
|
+
throw new Error('Origin session response URL does not match the requested endpoint')
|
|
193
|
+
}
|
|
185
194
|
const raw = await readBoundedRelayResponse(res)
|
|
186
|
-
return parseRelayResponse(raw)
|
|
195
|
+
return parseRelayResponse(raw, expected)
|
|
187
196
|
} finally {
|
|
188
197
|
clearTimeout(timer)
|
|
189
198
|
}
|
|
@@ -214,7 +223,9 @@ export function useWalletConnection() {
|
|
|
214
223
|
let activeDisconnect: (() => void) | null = null
|
|
215
224
|
|
|
216
225
|
/** Tear down any live paired RPC socket. No-op if no WalletConnectionProvider
|
|
217
|
-
* is mounted or no session is currently connected.
|
|
226
|
+
* is mounted or no session is currently connected. Shim kept for existing
|
|
227
|
+
* callers and tests; WalletContext now goes through runSessionTeardown, where
|
|
228
|
+
* the provider registers this same disconnect for logout and profile. */
|
|
218
229
|
export function disconnectActivePairedSession(): void {
|
|
219
230
|
activeDisconnect?.()
|
|
220
231
|
}
|
|
@@ -249,6 +260,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
249
260
|
// still reach handleRpc and dispatch privileged RPC after the app has
|
|
250
261
|
// already moved on to a different (or no) session.
|
|
251
262
|
const connectionGenerationRef = useRef(0)
|
|
263
|
+
// Keep sequence commits serialized across replacement sockets as well as
|
|
264
|
+
// concurrent messages. A closing session can still have a native write pending.
|
|
265
|
+
const sequenceCommitRef = useRef<Promise<boolean>>(Promise.resolve(true))
|
|
252
266
|
// Snapshot of sessionMeta for use inside async WS callbacks
|
|
253
267
|
const sessionMetaRef = useRef<SessionMeta | null>(null)
|
|
254
268
|
useEffect(() => {
|
|
@@ -289,7 +303,6 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
289
303
|
const supersedeExistingSocket = useCallback(() => {
|
|
290
304
|
const topic = sessionMetaRef.current?.topic
|
|
291
305
|
if (topic) {
|
|
292
|
-
void SecureStore.setItemAsync(lastSeqKey(topic), String(lastSeqRef.current))
|
|
293
306
|
connectionStore.setStatus(topic, 'disconnected')
|
|
294
307
|
}
|
|
295
308
|
closeAndDetachSocket(wsRef.current)
|
|
@@ -315,10 +328,14 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
315
328
|
// unmount stops a stale/unmounted provider's disconnect from being called.
|
|
316
329
|
useEffect(() => {
|
|
317
330
|
activeDisconnect = disconnect
|
|
331
|
+
// A network switch keeps the identity, so pairings survive it.
|
|
332
|
+
const unregister = registerSessionTeardown(['logout', 'profile'], () => disconnect())
|
|
318
333
|
return () => {
|
|
334
|
+
unregister()
|
|
319
335
|
if (activeDisconnect === disconnect) activeDisconnect = null
|
|
336
|
+
closeAndDetachSocket(wsRef.current)
|
|
320
337
|
}
|
|
321
|
-
}, [disconnect])
|
|
338
|
+
}, [disconnect, closeAndDetachSocket])
|
|
322
339
|
|
|
323
340
|
// ── Nav timer (pair screen lifecycle) ─────────────────────────────────────
|
|
324
341
|
|
|
@@ -411,13 +428,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
411
428
|
wallet: WalletClient,
|
|
412
429
|
meta: SessionMeta,
|
|
413
430
|
initialSeq: number,
|
|
414
|
-
//
|
|
415
|
-
// the
|
|
416
|
-
|
|
417
|
-
// value to guard its own onopen handler, so a stale in-flight onopen
|
|
418
|
-
// from a socket superseded in the meantime is guarded exactly like
|
|
419
|
-
// onmessage/onerror/onclose below.
|
|
420
|
-
myGeneration: number,
|
|
431
|
+
// Captured at attempt start, before any asynchronous work. Includes both
|
|
432
|
+
// the provider generation and this topic's explicit revocation version.
|
|
433
|
+
isCurrent: () => boolean,
|
|
421
434
|
onFirstMessage: () => void
|
|
422
435
|
) {
|
|
423
436
|
wsRef.current = ws
|
|
@@ -427,14 +440,13 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
427
440
|
let inFlightBytes = 0
|
|
428
441
|
// XR-021 review follow-up: MAX_IN_FLIGHT_RPC lets several messages
|
|
429
442
|
// decrypt concurrently, so the sequence check-then-durable-write-then-
|
|
430
|
-
// advance below is chained through
|
|
443
|
+
// advance below is chained through the provider-wide promise — each message's commit
|
|
431
444
|
// only runs once the previous one has fully resolved (write landed, ref
|
|
432
445
|
// advanced), and re-checks the watermark at that point. Without this,
|
|
433
446
|
// two concurrent messages can both pass the check against the same stale
|
|
434
447
|
// watermark and have their durable writes resolve out of order,
|
|
435
448
|
// regressing the watermark and letting an already-executed higher-
|
|
436
449
|
// sequence ciphertext be replayed immediately (no crash needed).
|
|
437
|
-
let seqCommitChain: Promise<boolean> = Promise.resolve(true)
|
|
438
450
|
|
|
439
451
|
ws.onmessage = async event => {
|
|
440
452
|
// XR-018: this socket may have already been superseded (a concurrent
|
|
@@ -442,7 +454,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
442
454
|
// the relay delivering this event and this handler running — closing
|
|
443
455
|
// a socket cannot cancel an event already queued for it. Drop it
|
|
444
456
|
// before touching any in-flight counters.
|
|
445
|
-
if (
|
|
457
|
+
if (!isCurrent()) return
|
|
446
458
|
if (inFlightRpc >= MAX_IN_FLIGHT_RPC) {
|
|
447
459
|
console.warn('[WalletConnection] dropping message: too many requests in flight')
|
|
448
460
|
return
|
|
@@ -501,18 +513,23 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
501
513
|
// the durable write itself fails, drop the message rather than
|
|
502
514
|
// dispatching with no durable record of having accepted it.
|
|
503
515
|
//
|
|
504
|
-
// Chained through
|
|
516
|
+
// Chained through sequenceCommitRef (review follow-up): re-checks the
|
|
505
517
|
// watermark once it's this message's turn, so a concurrent message
|
|
506
518
|
// that already committed a higher sequence in the meantime causes
|
|
507
519
|
// this one to be dropped instead of regressing the watermark.
|
|
508
|
-
const accepted = await (
|
|
509
|
-
if (
|
|
520
|
+
const accepted = await (sequenceCommitRef.current = sequenceCommitRef.current.then(async () => {
|
|
521
|
+
if (!isCurrent()) return false
|
|
510
522
|
try {
|
|
523
|
+
const stored = validateStoredConnectionSequence(await SecureStore.getItemAsync(lastSeqKey(meta.topic)))
|
|
524
|
+
if (!isCurrent() || sequence <= Math.max(lastSeqRef.current, stored)) {
|
|
525
|
+
return false
|
|
526
|
+
}
|
|
511
527
|
await SecureStore.setItemAsync(lastSeqKey(meta.topic), String(sequence))
|
|
512
528
|
} catch (err) {
|
|
513
529
|
console.warn('[WalletConnection] dropping message: failed to persist sequence', err)
|
|
514
530
|
return false
|
|
515
531
|
}
|
|
532
|
+
if (!isCurrent()) return false
|
|
516
533
|
lastSeqRef.current = sequence
|
|
517
534
|
return true
|
|
518
535
|
}))
|
|
@@ -527,7 +544,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
527
544
|
// this socket while this invocation was still awaiting them —
|
|
528
545
|
// detaching handlers at that point cannot cancel this already-
|
|
529
546
|
// running invocation, so the dispatch itself must also check.
|
|
530
|
-
if (
|
|
547
|
+
if (!isCurrent()) {
|
|
531
548
|
console.warn('[WalletConnection] dropping message: connection superseded before dispatch')
|
|
532
549
|
return
|
|
533
550
|
}
|
|
@@ -556,7 +573,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
556
573
|
}
|
|
557
574
|
|
|
558
575
|
ws.onerror = () => {
|
|
559
|
-
if (
|
|
576
|
+
if (!isCurrent()) return
|
|
560
577
|
setErrorMsg('WebSocket connection failed')
|
|
561
578
|
setStatus('error')
|
|
562
579
|
}
|
|
@@ -568,7 +585,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
568
585
|
// before calling close() for every controlled teardown path, so this
|
|
569
586
|
// is defense in depth for anything that still holds a reference to
|
|
570
587
|
// this closure directly.
|
|
571
|
-
if (
|
|
588
|
+
if (!isCurrent()) return
|
|
572
589
|
const wasIntentional = intentionalCloseRef.current
|
|
573
590
|
intentionalCloseRef.current = false
|
|
574
591
|
|
|
@@ -580,11 +597,12 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
580
597
|
if (!wasIntentional) {
|
|
581
598
|
const topic = sessionMetaRef.current?.topic
|
|
582
599
|
if (topic) {
|
|
583
|
-
void SecureStore.setItemAsync(lastSeqKey(topic), String(lastSeqRef.current))
|
|
584
600
|
connectionStore.setStatus(topic, 'disconnected')
|
|
585
601
|
}
|
|
586
602
|
}
|
|
587
|
-
|
|
603
|
+
// Remote close revokes handlers already awaiting decrypt or persistence,
|
|
604
|
+
// just as an explicit disconnect does.
|
|
605
|
+
closeAndDetachSocket(ws)
|
|
588
606
|
lastSeqRef.current = 0
|
|
589
607
|
if (navTimerRef.current) {
|
|
590
608
|
clearTimeout(navTimerRef.current)
|
|
@@ -612,10 +630,18 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
612
630
|
|
|
613
631
|
const connect = useCallback(
|
|
614
632
|
async (params: ConnectParams, wallet: WalletClient) => {
|
|
633
|
+
// Allocate authority before waits so teardown can revoke this attempt.
|
|
634
|
+
supersedeExistingSocket()
|
|
635
|
+
const myGeneration = ++connectionGenerationRef.current
|
|
636
|
+
const revocation = connectionStore.revocationVersion(params.topic)
|
|
637
|
+
const isCurrent = () =>
|
|
638
|
+
connectionGenerationRef.current === myGeneration &&
|
|
639
|
+
connectionStore.revocationVersion(params.topic) === revocation
|
|
615
640
|
setStatus('connecting')
|
|
616
641
|
setErrorMsg(null)
|
|
617
642
|
|
|
618
643
|
let relay: string
|
|
644
|
+
let initialSeq: number
|
|
619
645
|
let validated: ReturnType<typeof validateConnectParams>
|
|
620
646
|
try {
|
|
621
647
|
// This provider is a public embedding boundary. Validate every field here
|
|
@@ -623,10 +649,19 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
623
649
|
validated = validateConnectParams(params)
|
|
624
650
|
// Verify QR signature before trusting the origin or opening any connection
|
|
625
651
|
await verifyQrSignature(validated.params)
|
|
652
|
+
if (!isCurrent()) return
|
|
626
653
|
|
|
627
654
|
// Fetch relay URL from origin over HTTPS — TLS cert is the trust anchor
|
|
628
|
-
relay = await fetchRelay(validated.external.origin, validated.params.topic)
|
|
655
|
+
relay = await fetchRelay(validated.external.origin, validated.params.topic, validated.params)
|
|
656
|
+
if (!isCurrent()) return
|
|
657
|
+
// Re-approval does not rotate the topic's encryption key. Previously
|
|
658
|
+
// accepted ciphertexts must remain consumed when this QR is scanned again.
|
|
659
|
+
initialSeq = validateStoredConnectionSequence(
|
|
660
|
+
await SecureStore.getItemAsync(lastSeqKey(validated.params.topic))
|
|
661
|
+
)
|
|
662
|
+
if (!isCurrent()) return
|
|
629
663
|
} catch (err) {
|
|
664
|
+
if (!isCurrent()) return
|
|
630
665
|
setErrorMsg(err instanceof Error ? err.message : 'Connection failed')
|
|
631
666
|
setStatus('error')
|
|
632
667
|
throw err
|
|
@@ -634,14 +669,15 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
634
669
|
|
|
635
670
|
const protocolID = validated.protocolID
|
|
636
671
|
const identityResult = await wallet.getPublicKey({ identityKey: true })
|
|
672
|
+
if (!isCurrent()) return
|
|
637
673
|
const mobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
|
|
638
674
|
|
|
639
|
-
//
|
|
640
|
-
//
|
|
641
|
-
//
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
675
|
+
// The current socket can accept requests while the stored floor and
|
|
676
|
+
// identity are being read. Preserve its newer floor when re-pairing the
|
|
677
|
+
// same topic, with no await between this snapshot and replacing it.
|
|
678
|
+
if (sessionMetaRef.current?.topic === validated.params.topic) {
|
|
679
|
+
initialSeq = Math.max(initialSeq, lastSeqRef.current)
|
|
680
|
+
}
|
|
645
681
|
|
|
646
682
|
const meta: SessionMeta = {
|
|
647
683
|
topic: validated.params.topic,
|
|
@@ -660,11 +696,11 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
660
696
|
// a later connect()/reconnect()/disconnect() while relay/verify above
|
|
661
697
|
// were in flight — a stale send here must not touch the new session's
|
|
662
698
|
// state, and must not fire on an already-detached socket.
|
|
663
|
-
if (
|
|
699
|
+
if (!isCurrent()) return
|
|
664
700
|
try {
|
|
665
701
|
const payload = JSON.stringify({
|
|
666
702
|
id: crypto.randomUUID(),
|
|
667
|
-
seq: 1,
|
|
703
|
+
seq: initialSeq + 1,
|
|
668
704
|
method: 'pairing_approved',
|
|
669
705
|
params: {
|
|
670
706
|
mobileIdentityKey,
|
|
@@ -680,18 +716,18 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
680
716
|
validated.params.backendIdentityKey,
|
|
681
717
|
payload
|
|
682
718
|
)
|
|
683
|
-
if (
|
|
719
|
+
if (!isCurrent()) return
|
|
684
720
|
ws.send(
|
|
685
721
|
JSON.stringify({ topic: validated.params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope)
|
|
686
722
|
)
|
|
687
723
|
} catch {
|
|
688
|
-
if (
|
|
724
|
+
if (!isCurrent()) return
|
|
689
725
|
setErrorMsg('Failed to send pairing message')
|
|
690
726
|
setStatus('error')
|
|
691
727
|
}
|
|
692
728
|
}
|
|
693
729
|
|
|
694
|
-
wireSocket(ws, wallet, meta,
|
|
730
|
+
wireSocket(ws, wallet, meta, initialSeq, isCurrent, () => {
|
|
695
731
|
connectionStore.add({
|
|
696
732
|
sessionId: validated.params.topic,
|
|
697
733
|
origin: validated.external.origin,
|
|
@@ -712,30 +748,37 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
712
748
|
|
|
713
749
|
const reconnect = useCallback(
|
|
714
750
|
async (connection: Connection, wallet: WalletClient) => {
|
|
751
|
+
// Allocate authority before waits so teardown can revoke this attempt.
|
|
752
|
+
supersedeExistingSocket()
|
|
753
|
+
const myGeneration = ++connectionGenerationRef.current
|
|
754
|
+
const revocation = connectionStore.revocationVersion(connection.sessionId)
|
|
755
|
+
const isCurrent = () =>
|
|
756
|
+
connectionGenerationRef.current === myGeneration &&
|
|
757
|
+
connectionStore.revocationVersion(connection.sessionId) === revocation
|
|
715
758
|
setStatus('connecting')
|
|
716
759
|
setErrorMsg(null)
|
|
717
760
|
|
|
718
761
|
// Stored connection data is untrusted after import or database tampering.
|
|
719
762
|
const validated = validateStoredConnectionFields(connection)
|
|
720
763
|
const identityResult = await wallet.getPublicKey({ identityKey: true })
|
|
764
|
+
if (!isCurrent()) return
|
|
721
765
|
const currentMobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
|
|
722
766
|
if (currentMobileIdentityKey !== validated.mobileIdentityKey) {
|
|
723
767
|
throw new Error('Stored connection belongs to a different wallet identity')
|
|
724
768
|
}
|
|
725
769
|
// Fetch relay URL from origin over HTTPS — relay may have moved since last connection
|
|
726
|
-
const relay = await fetchRelay(validated.external.origin, validated.topic
|
|
770
|
+
const relay = await fetchRelay(validated.external.origin, validated.topic, {
|
|
771
|
+
topic: validated.topic,
|
|
772
|
+
backendIdentityKey: validated.backendIdentityKey,
|
|
773
|
+
protocolID: validated.protocolIDRaw
|
|
774
|
+
})
|
|
775
|
+
if (!isCurrent()) return
|
|
727
776
|
|
|
728
777
|
const protocolID = validated.protocolID
|
|
729
778
|
const storedSeq = await SecureStore.getItemAsync(lastSeqKey(validated.topic))
|
|
779
|
+
if (!isCurrent()) return
|
|
730
780
|
const initialSeq = validateStoredConnectionSequence(storedSeq)
|
|
731
781
|
|
|
732
|
-
// XR-018: tear down any live socket for a DIFFERENT prior session before
|
|
733
|
-
// wiring this one — see supersedeExistingSocket for why. myGeneration is
|
|
734
|
-
// allocated right after, so this connection's onopen AND wireSocket's
|
|
735
|
-
// handlers all guard against the same supersede event.
|
|
736
|
-
supersedeExistingSocket()
|
|
737
|
-
const myGeneration = ++connectionGenerationRef.current
|
|
738
|
-
|
|
739
782
|
const meta: SessionMeta = {
|
|
740
783
|
topic: validated.topic,
|
|
741
784
|
origin: validated.external.origin,
|
|
@@ -750,7 +793,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
750
793
|
|
|
751
794
|
ws.onopen = async () => {
|
|
752
795
|
// XR-018: see the identical guard in connect()'s onopen.
|
|
753
|
-
if (
|
|
796
|
+
if (!isCurrent()) return
|
|
754
797
|
try {
|
|
755
798
|
const payload = JSON.stringify({
|
|
756
799
|
id: crypto.randomUUID(),
|
|
@@ -770,7 +813,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
770
813
|
validated.backendIdentityKey,
|
|
771
814
|
payload
|
|
772
815
|
)
|
|
773
|
-
if (
|
|
816
|
+
if (!isCurrent()) return
|
|
774
817
|
ws.send(
|
|
775
818
|
JSON.stringify({
|
|
776
819
|
topic: validated.topic,
|
|
@@ -779,13 +822,13 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
779
822
|
} satisfies WireEnvelope)
|
|
780
823
|
)
|
|
781
824
|
} catch {
|
|
782
|
-
if (
|
|
825
|
+
if (!isCurrent()) return
|
|
783
826
|
setErrorMsg('Failed to send reconnect message')
|
|
784
827
|
setStatus('error')
|
|
785
828
|
}
|
|
786
829
|
}
|
|
787
830
|
|
|
788
|
-
wireSocket(ws, wallet, meta, initialSeq,
|
|
831
|
+
wireSocket(ws, wallet, meta, initialSeq, isCurrent, () => {
|
|
789
832
|
connectionStore.setStatus(validated.topic, 'active')
|
|
790
833
|
setStatus('connected')
|
|
791
834
|
})
|