@bsv/expo-wallet-toolbox 0.19.0 → 0.21.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 +154 -30
- package/README.md +79 -79
- package/core/backup/RemoteSyncReader.ts +26 -24
- package/core/backup/appData.ts +9 -8
- package/core/backup/codec.ts +21 -18
- package/core/backup/constants.ts +5 -5
- package/core/backup/contactsBackup.ts +8 -8
- package/core/backup/cursor.ts +12 -7
- package/core/backup/derive.ts +3 -3
- package/core/backup/deviceId.ts +2 -2
- package/core/backup/erase.ts +2 -2
- package/core/backup/preference.ts +2 -2
- package/core/backup/push.ts +10 -12
- package/core/backup/restore.ts +22 -14
- package/core/backup/restoreOnImport.ts +3 -2
- package/core/config.tsx +17 -13
- package/core/constants.ts +34 -11
- package/core/contacts/contactsStore.ts +4 -3
- package/core/context/WalletConnectionContext.tsx +294 -212
- package/core/context/WalletContext.tsx +132 -97
- package/core/context/defaultWalletSettings.ts +4 -2
- package/core/demo/demoLedger.ts +1 -5
- package/core/directpay/DirectPayManager.ts +148 -29
- package/core/directpay/DirectPayProvider.tsx +26 -26
- package/core/directpay/payFlow.ts +10 -1
- package/core/directpay/receive.ts +2 -1
- package/core/directpay/settings.ts +56 -9
- package/core/directpay/types.ts +11 -2
- package/core/directpay/webrtpay.ts +4 -0
- package/core/headers/checkpoints.ts +10 -1
- package/core/headers/headerStore.ts +13 -2
- package/core/hooks/useConfirmationSound.ts +3 -3
- package/core/hooks/useHaptics.ts +23 -6
- package/core/i18n/translations.tsx +382 -209
- package/core/index.ts +2 -0
- package/core/localpay/codec.ts +12 -6
- package/core/localpay/deviceCaps.ts +4 -14
- package/core/localpay/pending.ts +2 -1
- package/core/localpay/qr.ts +1 -1
- package/core/localpay/settlementAck.ts +1 -4
- package/core/localpay/transport/ble.ts +2 -2
- package/core/localpay/transport/socket.ts +1 -1
- package/core/mandala/abortGuard.ts +1 -1
- package/core/mandala/drain.ts +3 -0
- package/core/mandala/permissionModule.ts +3 -2
- package/core/mandala/resendTransfer.ts +4 -1
- package/core/mandala/runtime.ts +4 -4
- package/core/monitor/TaskBackupPush.ts +10 -13
- package/core/net/chainMatch.ts +8 -5
- package/core/networks.ts +145 -0
- package/core/parsePeerPayURI.ts +4 -1
- package/core/pay/beefRepair.ts +6 -3
- package/core/pay/creditErrors.ts +37 -1
- package/core/pay/rails/address.ts +10 -6
- package/core/pay/rails/direct.ts +6 -2
- package/core/pay/rails/handle.ts +84 -11
- package/core/pay/rails/index.ts +18 -2
- package/core/pay/receiveHistory.ts +8 -8
- package/core/peerpay/handleResendRequests.ts +11 -18
- package/core/peerpay/inboxAttempts.ts +1 -4
- package/core/peerpay/rebuildToken.ts +12 -9
- package/core/profiles/profileStore.ts +2 -1
- package/core/profiles/removalProblems.ts +3 -1
- package/core/services/arcTokenStorage.ts +2 -1
- package/core/services/arcadeBroadcastProvider.ts +7 -17
- package/core/services/secrets/envelope.ts +1 -6
- package/core/services/secrets/hkdf.ts +1 -6
- package/core/services/secrets/index.ts +3 -22
- package/core/services/usdFxRates.ts +1 -4
- package/core/services/vault/VaultKeyService.ts +2 -1
- package/core/services/vault/chainRecovery.ts +48 -21
- package/core/services/vault/metaAuthority.ts +4 -1
- package/core/services/vault/r1comb.ts +113 -51
- package/core/services/vault/session.ts +5 -1
- package/core/services/vault/transfers.ts +699 -576
- package/core/services/vault/vaultStore.ts +12 -10
- package/core/services/walletArgLimits.ts +1 -2
- package/core/services/walletConnectionValidation.ts +44 -28
- package/core/services/walletServiceConfig.ts +9 -40
- package/core/storage/StorageExpoSQLite.ts +7 -21
- package/core/storage/methods/listActionsSql.ts +81 -67
- package/core/storage/methods/listOutputsSql.ts +21 -16
- package/core/storage/methods/reviewStatusSql.ts +1 -4
- package/core/stores/ConnectionStore.ts +1 -1
- package/core/theme/ThemeContext.tsx +12 -16
- package/core/theme/motion.ts +3 -3
- package/core/theme/tokens.ts +6 -6
- package/core/toolboxConfig.ts +23 -0
- package/core/walletDbRegistry.ts +7 -5
- package/core/walletRepair/runWalletCheck.ts +1 -4
- package/package.json +2 -2
- package/ui/components/pay/AddressReceive.tsx +3 -3
- package/ui/components/pay/HandleReceive.tsx +21 -15
- package/ui/components/pay/MessageBoxConfig.tsx +46 -20
- package/ui/components/pay/NearbyFlow.tsx +575 -507
- package/ui/components/pay/OfflineNotice.tsx +1 -3
- package/ui/components/pay/PayCellRow.tsx +1 -4
- package/ui/components/pay/PayForm.tsx +1 -3
- package/ui/components/pay/RequestHub.tsx +14 -6
- package/ui/components/pay/UniversalSend.tsx +79 -27
- package/ui/components/pay/tokenSendCopy.ts +1 -2
- package/ui/components/pay/useRecipientInput.ts +2 -2
- package/ui/components/security/WalletLockNotice.tsx +1 -3
- package/ui/components/ui/AlertCard.tsx +44 -45
- package/ui/components/ui/BlurChrome.tsx +4 -15
- package/ui/components/ui/Celebration.tsx +3 -3
- package/ui/components/ui/ChoiceSheet.ts +1 -3
- package/ui/components/ui/ErrorBoundary.tsx +2 -6
- package/ui/components/ui/GroupedList.tsx +13 -31
- package/ui/components/ui/IconButton.tsx +6 -9
- package/ui/components/ui/ListRow.tsx +19 -25
- package/ui/components/ui/PresenceRow.tsx +4 -4
- package/ui/components/ui/PressableScale.tsx +24 -20
- package/ui/components/ui/Toast.tsx +23 -16
- package/ui/components/vault/KeyChooser.tsx +9 -6
- package/ui/components/vault/VaultBackdrop.tsx +1 -8
- package/ui/components/vault/VaultCeremonySheet.tsx +5 -5
- package/ui/components/wallet/ActivityRow.tsx +3 -2
- package/ui/components/wallet/BackupReminderSheet.tsx +1 -5
- package/ui/components/wallet/Balance.tsx +4 -1
- package/ui/components/wallet/ContactActivityList.tsx +7 -7
- package/ui/components/wallet/IconPickerSheet.tsx +1 -5
- package/ui/components/wallet/ProfileSwitcherPopover.tsx +6 -1
- package/ui/components/wallet/tokenEviction.ts +4 -1
- package/ui/hooks/useMandala.ts +1 -7
- package/ui/hooks/useOfflineNoticeActions.ts +21 -27
- package/ui/hooks/useSpendableBalance.ts +2 -2
- package/ui/hooks/useVaultCoverage.ts +7 -1
- package/ui/index.ts +9 -1
- package/ui/resolveIdentity.ts +20 -8
- package/ui/screens/ConnectionsScreen.tsx +44 -18
- package/ui/screens/LogsScreen.tsx +24 -22
- package/ui/screens/PairScreen.tsx +85 -54
- package/ui/screens/PayScreen.tsx +5 -1
- package/ui/screens/ProfileScreen.tsx +0 -3
- package/ui/screens/TrustScreen.tsx +125 -80
- package/ui/screens/VaultScreen.tsx +19 -7
- package/ui/screens/VaultTransferScreen.tsx +5 -1
- package/ui/screens/WalletCheckScreen.tsx +14 -17
- package/ui/screens/WalletConfigScreen.tsx +414 -376
- package/ui/screens/WalletHomeScreen.tsx +47 -42
|
@@ -28,14 +28,26 @@ export type { ConnectParams } from '../services/walletConnectionValidation'
|
|
|
28
28
|
// ── Constants ─────────────────────────────────────────────────────────────────
|
|
29
29
|
|
|
30
30
|
export const IMPLEMENTED_METHODS = new Set([
|
|
31
|
-
'getPublicKey',
|
|
32
|
-
'
|
|
33
|
-
'
|
|
34
|
-
'
|
|
31
|
+
'getPublicKey',
|
|
32
|
+
'listOutputs',
|
|
33
|
+
'listCertificates',
|
|
34
|
+
'createAction',
|
|
35
|
+
'signAction',
|
|
36
|
+
'listActions',
|
|
37
|
+
'internalizeAction',
|
|
38
|
+
'acquireCertificate',
|
|
39
|
+
'relinquishCertificate',
|
|
40
|
+
'revealCounterpartyKeyLinkage',
|
|
41
|
+
'createHmac',
|
|
42
|
+
'verifyHmac',
|
|
43
|
+
'encrypt',
|
|
44
|
+
'decrypt',
|
|
45
|
+
'createSignature',
|
|
46
|
+
'verifySignature'
|
|
35
47
|
])
|
|
36
48
|
|
|
37
|
-
const NAV_TIMEOUT_MS
|
|
38
|
-
const APP_STATE_TIMEOUT_MS = 12 * 60 * 1000
|
|
49
|
+
const NAV_TIMEOUT_MS = 5 * 60 * 1000 // 5 min — navigated away from pair screen
|
|
50
|
+
const APP_STATE_TIMEOUT_MS = 12 * 60 * 1000 // 12 min — app backgrounded
|
|
39
51
|
|
|
40
52
|
export const lastSeqKey = (topic: string) => `wallet_pairing_lastseq_${topic}`
|
|
41
53
|
|
|
@@ -43,28 +55,28 @@ export const lastSeqKey = (topic: string) => `wallet_pairing_lastseq_${topic}`
|
|
|
43
55
|
|
|
44
56
|
export type ConnectionStatus = 'idle' | 'connecting' | 'connected' | 'disconnected' | 'error'
|
|
45
57
|
|
|
46
|
-
type RpcRequest
|
|
58
|
+
type RpcRequest = { id: string; seq: number; method: string; params: unknown }
|
|
47
59
|
type RpcResponse = { id: string; seq: number; result?: unknown; error?: { code: number; message: string } }
|
|
48
60
|
type WireEnvelope = { topic: string; ciphertext: string; mobileIdentityKey?: string }
|
|
49
61
|
|
|
50
62
|
export interface SessionMeta {
|
|
51
|
-
topic:
|
|
52
|
-
origin:
|
|
53
|
-
relay:
|
|
63
|
+
topic: string
|
|
64
|
+
origin: string
|
|
65
|
+
relay: string
|
|
54
66
|
backendIdentityKey: string
|
|
55
|
-
mobileIdentityKey:
|
|
56
|
-
protocolID:
|
|
67
|
+
mobileIdentityKey: string
|
|
68
|
+
protocolID: WalletProtocol
|
|
57
69
|
}
|
|
58
70
|
|
|
59
71
|
interface WalletConnectionContextValue {
|
|
60
|
-
status:
|
|
61
|
-
sessionMeta:
|
|
62
|
-
errorMsg:
|
|
63
|
-
connect:
|
|
64
|
-
reconnect:
|
|
65
|
-
disconnect:
|
|
66
|
-
startNavTimer:
|
|
67
|
-
cancelNavTimer:
|
|
72
|
+
status: ConnectionStatus
|
|
73
|
+
sessionMeta: SessionMeta | null
|
|
74
|
+
errorMsg: string | null
|
|
75
|
+
connect: (params: ConnectParams, wallet: WalletClient) => Promise<void>
|
|
76
|
+
reconnect: (connection: Connection, wallet: WalletClient) => Promise<void>
|
|
77
|
+
disconnect: () => void
|
|
78
|
+
startNavTimer: () => void
|
|
79
|
+
cancelNavTimer: () => void
|
|
68
80
|
}
|
|
69
81
|
|
|
70
82
|
// ── Helpers ───────────────────────────────────────────────────────────────────
|
|
@@ -74,7 +86,7 @@ async function encryptPayload(
|
|
|
74
86
|
protocolID: WalletProtocol,
|
|
75
87
|
keyID: string,
|
|
76
88
|
counterparty: string,
|
|
77
|
-
payload: string
|
|
89
|
+
payload: string
|
|
78
90
|
): Promise<string> {
|
|
79
91
|
const plaintext = Array.from(new TextEncoder().encode(payload))
|
|
80
92
|
const { ciphertext } = await wallet.encrypt({ protocolID, keyID, counterparty, plaintext })
|
|
@@ -86,7 +98,7 @@ async function decryptPayload(
|
|
|
86
98
|
protocolID: WalletProtocol,
|
|
87
99
|
keyID: string,
|
|
88
100
|
counterparty: string,
|
|
89
|
-
ciphertextB64: string
|
|
101
|
+
ciphertextB64: string
|
|
90
102
|
): Promise<string> {
|
|
91
103
|
const ciphertext = Array.from(Buffer.from(ciphertextB64, 'base64url'))
|
|
92
104
|
const { plaintext } = await wallet.decrypt({ protocolID, keyID, counterparty, ciphertext })
|
|
@@ -99,11 +111,11 @@ async function verifyQrSignature(params: Required<ConnectParams>): Promise<void>
|
|
|
99
111
|
const payload = Array.from(new TextEncoder().encode(buildPairingSignatureMessage(params)))
|
|
100
112
|
const signature = Utils.toArray(params.sig.replace(/-/g, '+').replace(/_/g, '/'), 'base64') as number[]
|
|
101
113
|
const { valid } = await anyoneWallet.verifySignature({
|
|
102
|
-
data:
|
|
114
|
+
data: payload,
|
|
103
115
|
signature,
|
|
104
|
-
protocolID:
|
|
105
|
-
keyID:
|
|
106
|
-
counterparty: params.backendIdentityKey
|
|
116
|
+
protocolID: [0, 'qr pairing'],
|
|
117
|
+
keyID: params.topic,
|
|
118
|
+
counterparty: params.backendIdentityKey
|
|
107
119
|
})
|
|
108
120
|
if (!valid) throw new Error('QR code signature is invalid — do not connect')
|
|
109
121
|
}
|
|
@@ -217,15 +229,15 @@ interface WalletConnectionProviderProps {
|
|
|
217
229
|
}
|
|
218
230
|
|
|
219
231
|
export function WalletConnectionProvider({ children, walletName = 'App' }: WalletConnectionProviderProps) {
|
|
220
|
-
const [status,
|
|
221
|
-
const [sessionMeta,
|
|
222
|
-
const [errorMsg,
|
|
232
|
+
const [status, setStatus] = useState<ConnectionStatus>('idle')
|
|
233
|
+
const [sessionMeta, setSessionMeta] = useState<SessionMeta | null>(null)
|
|
234
|
+
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
|
223
235
|
|
|
224
236
|
// Internal refs — changes here don't trigger re-renders
|
|
225
|
-
const wsRef
|
|
226
|
-
const lastSeqRef
|
|
227
|
-
const navTimerRef
|
|
228
|
-
const appStateTimerRef
|
|
237
|
+
const wsRef = useRef<WebSocket | null>(null)
|
|
238
|
+
const lastSeqRef = useRef(0)
|
|
239
|
+
const navTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
240
|
+
const appStateTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
229
241
|
const intentionalCloseRef = useRef(false)
|
|
230
242
|
// XR-018: bumped every time an existing socket is torn down (disconnect(),
|
|
231
243
|
// or connect()/reconnect() superseding a prior live session). wireSocket
|
|
@@ -238,8 +250,10 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
238
250
|
// already moved on to a different (or no) session.
|
|
239
251
|
const connectionGenerationRef = useRef(0)
|
|
240
252
|
// Snapshot of sessionMeta for use inside async WS callbacks
|
|
241
|
-
const sessionMetaRef
|
|
242
|
-
useEffect(() => {
|
|
253
|
+
const sessionMetaRef = useRef<SessionMeta | null>(null)
|
|
254
|
+
useEffect(() => {
|
|
255
|
+
sessionMetaRef.current = sessionMeta
|
|
256
|
+
}, [sessionMeta])
|
|
243
257
|
|
|
244
258
|
// ── Disconnect ─────────────────────────────────────────────────────────────
|
|
245
259
|
|
|
@@ -252,11 +266,15 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
252
266
|
connectionGenerationRef.current++
|
|
253
267
|
if (wsRef.current === ws) wsRef.current = null
|
|
254
268
|
if (!ws) return
|
|
255
|
-
ws.onopen
|
|
269
|
+
ws.onopen = null
|
|
256
270
|
ws.onmessage = null
|
|
257
|
-
ws.onerror
|
|
258
|
-
ws.onclose
|
|
259
|
-
try {
|
|
271
|
+
ws.onerror = null
|
|
272
|
+
ws.onclose = null
|
|
273
|
+
try {
|
|
274
|
+
ws.close()
|
|
275
|
+
} catch {
|
|
276
|
+
/* already closing/closed */
|
|
277
|
+
}
|
|
260
278
|
}, [])
|
|
261
279
|
|
|
262
280
|
/** XR-018: this provider models exactly one live paired session at a time
|
|
@@ -275,8 +293,14 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
275
293
|
connectionStore.setStatus(topic, 'disconnected')
|
|
276
294
|
}
|
|
277
295
|
closeAndDetachSocket(wsRef.current)
|
|
278
|
-
if (navTimerRef.current)
|
|
279
|
-
|
|
296
|
+
if (navTimerRef.current) {
|
|
297
|
+
clearTimeout(navTimerRef.current)
|
|
298
|
+
navTimerRef.current = null
|
|
299
|
+
}
|
|
300
|
+
if (appStateTimerRef.current) {
|
|
301
|
+
clearTimeout(appStateTimerRef.current)
|
|
302
|
+
appStateTimerRef.current = null
|
|
303
|
+
}
|
|
280
304
|
}, [closeAndDetachSocket])
|
|
281
305
|
|
|
282
306
|
const disconnect = useCallback(() => {
|
|
@@ -291,7 +315,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
291
315
|
// unmount stops a stale/unmounted provider's disconnect from being called.
|
|
292
316
|
useEffect(() => {
|
|
293
317
|
activeDisconnect = disconnect
|
|
294
|
-
return () => {
|
|
318
|
+
return () => {
|
|
319
|
+
if (activeDisconnect === disconnect) activeDisconnect = null
|
|
320
|
+
}
|
|
295
321
|
}, [disconnect])
|
|
296
322
|
|
|
297
323
|
// ── Nav timer (pair screen lifecycle) ─────────────────────────────────────
|
|
@@ -305,7 +331,10 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
305
331
|
}, [disconnect])
|
|
306
332
|
|
|
307
333
|
const cancelNavTimer = useCallback(() => {
|
|
308
|
-
if (navTimerRef.current) {
|
|
334
|
+
if (navTimerRef.current) {
|
|
335
|
+
clearTimeout(navTimerRef.current)
|
|
336
|
+
navTimerRef.current = null
|
|
337
|
+
}
|
|
309
338
|
}, [])
|
|
310
339
|
|
|
311
340
|
// ── AppState timer (app backgrounded) ────────────────────────────────────
|
|
@@ -319,7 +348,10 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
319
348
|
if (wsRef.current) disconnect()
|
|
320
349
|
}, APP_STATE_TIMEOUT_MS)
|
|
321
350
|
} else if (nextState === 'active') {
|
|
322
|
-
if (appStateTimerRef.current) {
|
|
351
|
+
if (appStateTimerRef.current) {
|
|
352
|
+
clearTimeout(appStateTimerRef.current)
|
|
353
|
+
appStateTimerRef.current = null
|
|
354
|
+
}
|
|
323
355
|
}
|
|
324
356
|
})
|
|
325
357
|
return () => sub.remove()
|
|
@@ -327,16 +359,15 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
327
359
|
|
|
328
360
|
// ── RPC dispatch ──────────────────────────────────────────────────────────
|
|
329
361
|
|
|
330
|
-
async function handleRpc(
|
|
331
|
-
request: RpcRequest,
|
|
332
|
-
meta: SessionMeta,
|
|
333
|
-
ws: WebSocket,
|
|
334
|
-
wallet: WalletClient,
|
|
335
|
-
): Promise<void> {
|
|
362
|
+
async function handleRpc(request: RpcRequest, meta: SessionMeta, ws: WebSocket, wallet: WalletClient): Promise<void> {
|
|
336
363
|
const sendResponse = async (response: RpcResponse) => {
|
|
337
364
|
try {
|
|
338
365
|
const ciphertext = await encryptPayload(
|
|
339
|
-
wallet,
|
|
366
|
+
wallet,
|
|
367
|
+
meta.protocolID,
|
|
368
|
+
meta.topic,
|
|
369
|
+
meta.backendIdentityKey,
|
|
370
|
+
JSON.stringify(response)
|
|
340
371
|
)
|
|
341
372
|
ws.send(JSON.stringify({ topic: meta.topic, ciphertext } satisfies WireEnvelope))
|
|
342
373
|
} catch (err) {
|
|
@@ -345,8 +376,11 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
345
376
|
}
|
|
346
377
|
|
|
347
378
|
if (!IMPLEMENTED_METHODS.has(request.method)) {
|
|
348
|
-
await sendResponse({
|
|
349
|
-
|
|
379
|
+
await sendResponse({
|
|
380
|
+
id: request.id,
|
|
381
|
+
seq: request.seq,
|
|
382
|
+
error: { code: 501, message: `Method "${request.method}" is not implemented` }
|
|
383
|
+
})
|
|
350
384
|
return
|
|
351
385
|
}
|
|
352
386
|
|
|
@@ -365,9 +399,8 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
365
399
|
error = { code, message }
|
|
366
400
|
}
|
|
367
401
|
|
|
368
|
-
await sendResponse(
|
|
369
|
-
? { id: request.id, seq: request.seq, error }
|
|
370
|
-
: { id: request.id, seq: request.seq, result },
|
|
402
|
+
await sendResponse(
|
|
403
|
+
error ? { id: request.id, seq: request.seq, error } : { id: request.id, seq: request.seq, result }
|
|
371
404
|
)
|
|
372
405
|
}
|
|
373
406
|
|
|
@@ -385,9 +418,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
385
418
|
// from a socket superseded in the meantime is guarded exactly like
|
|
386
419
|
// onmessage/onerror/onclose below.
|
|
387
420
|
myGeneration: number,
|
|
388
|
-
onFirstMessage: () => void
|
|
421
|
+
onFirstMessage: () => void
|
|
389
422
|
) {
|
|
390
|
-
wsRef.current
|
|
423
|
+
wsRef.current = ws
|
|
391
424
|
lastSeqRef.current = initialSeq
|
|
392
425
|
let firstMessageFired = false
|
|
393
426
|
let inFlightRpc = 0
|
|
@@ -428,7 +461,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
428
461
|
// attempted — decoding the ciphertext into a number[] alone already
|
|
429
462
|
// allocates memory proportional to its size, before the wallet can
|
|
430
463
|
// authenticate it.
|
|
431
|
-
const estimatedBytes = Math.floor(envelope.ciphertext.length * 3 / 4)
|
|
464
|
+
const estimatedBytes = Math.floor((envelope.ciphertext.length * 3) / 4)
|
|
432
465
|
if (inFlightBytes + estimatedBytes > MAX_IN_FLIGHT_RPC_BYTES) {
|
|
433
466
|
console.warn('[WalletConnection] dropping message: too many in-flight bytes')
|
|
434
467
|
return
|
|
@@ -439,7 +472,11 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
439
472
|
let plaintext: string
|
|
440
473
|
try {
|
|
441
474
|
plaintext = await decryptPayload(
|
|
442
|
-
wallet,
|
|
475
|
+
wallet,
|
|
476
|
+
meta.protocolID,
|
|
477
|
+
meta.topic,
|
|
478
|
+
meta.backendIdentityKey,
|
|
479
|
+
envelope.ciphertext
|
|
443
480
|
)
|
|
444
481
|
} catch (err) {
|
|
445
482
|
console.warn('[WalletConnection] decryptPayload failed:', err)
|
|
@@ -447,9 +484,8 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
447
484
|
}
|
|
448
485
|
|
|
449
486
|
const msg = JSON.parse(plaintext) as RpcRequest | RpcResponse
|
|
450
|
-
const sequence =
|
|
451
|
-
? (msg as { seq?: unknown }).seq
|
|
452
|
-
: undefined
|
|
487
|
+
const sequence =
|
|
488
|
+
msg !== null && typeof msg === 'object' && !Array.isArray(msg) ? (msg as { seq?: unknown }).seq : undefined
|
|
453
489
|
if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence <= lastSeqRef.current) {
|
|
454
490
|
console.warn('[WalletConnection] dropping message: seq', sequence, '<= lastSeq', lastSeqRef.current)
|
|
455
491
|
return
|
|
@@ -502,8 +538,13 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
502
538
|
}
|
|
503
539
|
|
|
504
540
|
if ('method' in msg && msg.method === 'pairing_ack') return
|
|
505
|
-
if (
|
|
506
|
-
|
|
541
|
+
if (
|
|
542
|
+
'method' in msg &&
|
|
543
|
+
typeof msg.method === 'string' &&
|
|
544
|
+
typeof msg.id === 'string' &&
|
|
545
|
+
msg.id.length > 0 &&
|
|
546
|
+
msg.id.length <= 128
|
|
547
|
+
) {
|
|
507
548
|
await handleRpc(msg as RpcRequest, meta, ws, wallet)
|
|
508
549
|
}
|
|
509
550
|
} catch {
|
|
@@ -545,8 +586,14 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
545
586
|
}
|
|
546
587
|
wsRef.current = null
|
|
547
588
|
lastSeqRef.current = 0
|
|
548
|
-
if (navTimerRef.current)
|
|
549
|
-
|
|
589
|
+
if (navTimerRef.current) {
|
|
590
|
+
clearTimeout(navTimerRef.current)
|
|
591
|
+
navTimerRef.current = null
|
|
592
|
+
}
|
|
593
|
+
if (appStateTimerRef.current) {
|
|
594
|
+
clearTimeout(appStateTimerRef.current)
|
|
595
|
+
appStateTimerRef.current = null
|
|
596
|
+
}
|
|
550
597
|
setSessionMeta(null)
|
|
551
598
|
// Don't override the 'idle' status that disconnect() already set
|
|
552
599
|
if (!wasIntentional) {
|
|
@@ -563,169 +610,204 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
|
|
|
563
610
|
|
|
564
611
|
// ── connect (fresh pairing) ───────────────────────────────────────────────
|
|
565
612
|
|
|
566
|
-
const connect = useCallback(
|
|
567
|
-
|
|
568
|
-
|
|
613
|
+
const connect = useCallback(
|
|
614
|
+
async (params: ConnectParams, wallet: WalletClient) => {
|
|
615
|
+
setStatus('connecting')
|
|
616
|
+
setErrorMsg(null)
|
|
569
617
|
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
const protocolID = validated.protocolID
|
|
588
|
-
const identityResult = await wallet.getPublicKey({ identityKey: true })
|
|
589
|
-
const mobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
|
|
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
|
|
618
|
+
let relay: string
|
|
619
|
+
let validated: ReturnType<typeof validateConnectParams>
|
|
620
|
+
try {
|
|
621
|
+
// This provider is a public embedding boundary. Validate every field here
|
|
622
|
+
// even when a host screen already parsed the QR.
|
|
623
|
+
validated = validateConnectParams(params)
|
|
624
|
+
// Verify QR signature before trusting the origin or opening any connection
|
|
625
|
+
await verifyQrSignature(validated.params)
|
|
626
|
+
|
|
627
|
+
// Fetch relay URL from origin over HTTPS — TLS cert is the trust anchor
|
|
628
|
+
relay = await fetchRelay(validated.external.origin, validated.params.topic)
|
|
629
|
+
} catch (err) {
|
|
630
|
+
setErrorMsg(err instanceof Error ? err.message : 'Connection failed')
|
|
631
|
+
setStatus('error')
|
|
632
|
+
throw err
|
|
633
|
+
}
|
|
597
634
|
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
635
|
+
const protocolID = validated.protocolID
|
|
636
|
+
const identityResult = await wallet.getPublicKey({ identityKey: true })
|
|
637
|
+
const mobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
|
|
638
|
+
|
|
639
|
+
// XR-018: tear down any live socket for a DIFFERENT prior session before
|
|
640
|
+
// wiring this one — see supersedeExistingSocket for why. myGeneration is
|
|
641
|
+
// allocated right after, so this connection's onopen AND wireSocket's
|
|
642
|
+
// handlers all guard against the same supersede event.
|
|
643
|
+
supersedeExistingSocket()
|
|
644
|
+
const myGeneration = ++connectionGenerationRef.current
|
|
645
|
+
|
|
646
|
+
const meta: SessionMeta = {
|
|
647
|
+
topic: validated.params.topic,
|
|
648
|
+
origin: validated.external.origin,
|
|
649
|
+
relay,
|
|
650
|
+
backendIdentityKey: validated.params.backendIdentityKey,
|
|
651
|
+
mobileIdentityKey,
|
|
652
|
+
protocolID
|
|
653
|
+
}
|
|
654
|
+
setSessionMeta(meta)
|
|
604
655
|
|
|
605
|
-
|
|
656
|
+
const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.params.topic))
|
|
606
657
|
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
if (connectionGenerationRef.current !== myGeneration) return
|
|
613
|
-
try {
|
|
614
|
-
const payload = JSON.stringify({
|
|
615
|
-
id: crypto.randomUUID(), seq: 1, method: 'pairing_approved',
|
|
616
|
-
params: {
|
|
617
|
-
mobileIdentityKey,
|
|
618
|
-
protocolID: validated.params.protocolID,
|
|
619
|
-
walletMeta: { name: walletName, platform: 'mobile' },
|
|
620
|
-
permissions: Array.from(IMPLEMENTED_METHODS),
|
|
621
|
-
},
|
|
622
|
-
})
|
|
623
|
-
const ciphertext = await encryptPayload(
|
|
624
|
-
wallet, protocolID, validated.params.topic, validated.params.backendIdentityKey, payload
|
|
625
|
-
)
|
|
626
|
-
if (connectionGenerationRef.current !== myGeneration) return
|
|
627
|
-
ws.send(JSON.stringify({ topic: validated.params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope))
|
|
628
|
-
} catch {
|
|
658
|
+
ws.onopen = async () => {
|
|
659
|
+
// XR-018: this connection attempt may already have been superseded by
|
|
660
|
+
// a later connect()/reconnect()/disconnect() while relay/verify above
|
|
661
|
+
// were in flight — a stale send here must not touch the new session's
|
|
662
|
+
// state, and must not fire on an already-detached socket.
|
|
629
663
|
if (connectionGenerationRef.current !== myGeneration) return
|
|
630
|
-
|
|
631
|
-
|
|
664
|
+
try {
|
|
665
|
+
const payload = JSON.stringify({
|
|
666
|
+
id: crypto.randomUUID(),
|
|
667
|
+
seq: 1,
|
|
668
|
+
method: 'pairing_approved',
|
|
669
|
+
params: {
|
|
670
|
+
mobileIdentityKey,
|
|
671
|
+
protocolID: validated.params.protocolID,
|
|
672
|
+
walletMeta: { name: walletName, platform: 'mobile' },
|
|
673
|
+
permissions: Array.from(IMPLEMENTED_METHODS)
|
|
674
|
+
}
|
|
675
|
+
})
|
|
676
|
+
const ciphertext = await encryptPayload(
|
|
677
|
+
wallet,
|
|
678
|
+
protocolID,
|
|
679
|
+
validated.params.topic,
|
|
680
|
+
validated.params.backendIdentityKey,
|
|
681
|
+
payload
|
|
682
|
+
)
|
|
683
|
+
if (connectionGenerationRef.current !== myGeneration) return
|
|
684
|
+
ws.send(
|
|
685
|
+
JSON.stringify({ topic: validated.params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope)
|
|
686
|
+
)
|
|
687
|
+
} catch {
|
|
688
|
+
if (connectionGenerationRef.current !== myGeneration) return
|
|
689
|
+
setErrorMsg('Failed to send pairing message')
|
|
690
|
+
setStatus('error')
|
|
691
|
+
}
|
|
632
692
|
}
|
|
633
|
-
}
|
|
634
693
|
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
694
|
+
wireSocket(ws, wallet, meta, 0, myGeneration, () => {
|
|
695
|
+
connectionStore.add({
|
|
696
|
+
sessionId: validated.params.topic,
|
|
697
|
+
origin: validated.external.origin,
|
|
698
|
+
relay,
|
|
699
|
+
backendIdentityKey: validated.params.backendIdentityKey,
|
|
700
|
+
mobileIdentityKey,
|
|
701
|
+
protocolID: validated.params.protocolID,
|
|
702
|
+
connectedAt: Date.now(),
|
|
703
|
+
status: 'active'
|
|
704
|
+
})
|
|
705
|
+
setStatus('connected')
|
|
641
706
|
})
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
707
|
+
},
|
|
708
|
+
[walletName, supersedeExistingSocket]
|
|
709
|
+
) // eslint-disable-line react-hooks/exhaustive-deps
|
|
645
710
|
|
|
646
711
|
// ── reconnect (resume from stored session) ────────────────────────────────
|
|
647
712
|
|
|
648
|
-
const reconnect = useCallback(
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
713
|
+
const reconnect = useCallback(
|
|
714
|
+
async (connection: Connection, wallet: WalletClient) => {
|
|
715
|
+
setStatus('connecting')
|
|
716
|
+
setErrorMsg(null)
|
|
717
|
+
|
|
718
|
+
// Stored connection data is untrusted after import or database tampering.
|
|
719
|
+
const validated = validateStoredConnectionFields(connection)
|
|
720
|
+
const identityResult = await wallet.getPublicKey({ identityKey: true })
|
|
721
|
+
const currentMobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
|
|
722
|
+
if (currentMobileIdentityKey !== validated.mobileIdentityKey) {
|
|
723
|
+
throw new Error('Stored connection belongs to a different wallet identity')
|
|
724
|
+
}
|
|
725
|
+
// Fetch relay URL from origin over HTTPS — relay may have moved since last connection
|
|
726
|
+
const relay = await fetchRelay(validated.external.origin, validated.topic)
|
|
727
|
+
|
|
728
|
+
const protocolID = validated.protocolID
|
|
729
|
+
const storedSeq = await SecureStore.getItemAsync(lastSeqKey(validated.topic))
|
|
730
|
+
const initialSeq = validateStoredConnectionSequence(storedSeq)
|
|
731
|
+
|
|
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
|
+
const meta: SessionMeta = {
|
|
740
|
+
topic: validated.topic,
|
|
741
|
+
origin: validated.external.origin,
|
|
742
|
+
relay,
|
|
743
|
+
backendIdentityKey: validated.backendIdentityKey,
|
|
744
|
+
mobileIdentityKey: validated.mobileIdentityKey,
|
|
745
|
+
protocolID
|
|
746
|
+
}
|
|
747
|
+
setSessionMeta(meta)
|
|
680
748
|
|
|
681
|
-
|
|
749
|
+
const ws = new WebSocket(buildRelayWebSocketUrl(relay, validated.topic))
|
|
682
750
|
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
if (connectionGenerationRef.current !== myGeneration) return
|
|
686
|
-
try {
|
|
687
|
-
const payload = JSON.stringify({
|
|
688
|
-
id: crypto.randomUUID(), seq: initialSeq + 1, method: 'pairing_approved',
|
|
689
|
-
params: {
|
|
690
|
-
mobileIdentityKey: validated.mobileIdentityKey,
|
|
691
|
-
protocolID: validated.protocolIDRaw,
|
|
692
|
-
walletMeta: { name: walletName, platform: 'mobile' },
|
|
693
|
-
permissions: Array.from(IMPLEMENTED_METHODS),
|
|
694
|
-
},
|
|
695
|
-
})
|
|
696
|
-
const ciphertext = await encryptPayload(
|
|
697
|
-
wallet, protocolID, validated.topic, validated.backendIdentityKey, payload,
|
|
698
|
-
)
|
|
751
|
+
ws.onopen = async () => {
|
|
752
|
+
// XR-018: see the identical guard in connect()'s onopen.
|
|
699
753
|
if (connectionGenerationRef.current !== myGeneration) return
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
754
|
+
try {
|
|
755
|
+
const payload = JSON.stringify({
|
|
756
|
+
id: crypto.randomUUID(),
|
|
757
|
+
seq: initialSeq + 1,
|
|
758
|
+
method: 'pairing_approved',
|
|
759
|
+
params: {
|
|
760
|
+
mobileIdentityKey: validated.mobileIdentityKey,
|
|
761
|
+
protocolID: validated.protocolIDRaw,
|
|
762
|
+
walletMeta: { name: walletName, platform: 'mobile' },
|
|
763
|
+
permissions: Array.from(IMPLEMENTED_METHODS)
|
|
764
|
+
}
|
|
765
|
+
})
|
|
766
|
+
const ciphertext = await encryptPayload(
|
|
767
|
+
wallet,
|
|
768
|
+
protocolID,
|
|
769
|
+
validated.topic,
|
|
770
|
+
validated.backendIdentityKey,
|
|
771
|
+
payload
|
|
772
|
+
)
|
|
773
|
+
if (connectionGenerationRef.current !== myGeneration) return
|
|
774
|
+
ws.send(
|
|
775
|
+
JSON.stringify({
|
|
776
|
+
topic: validated.topic,
|
|
777
|
+
mobileIdentityKey: validated.mobileIdentityKey,
|
|
778
|
+
ciphertext
|
|
779
|
+
} satisfies WireEnvelope)
|
|
780
|
+
)
|
|
781
|
+
} catch {
|
|
782
|
+
if (connectionGenerationRef.current !== myGeneration) return
|
|
783
|
+
setErrorMsg('Failed to send reconnect message')
|
|
784
|
+
setStatus('error')
|
|
785
|
+
}
|
|
709
786
|
}
|
|
710
|
-
}
|
|
711
787
|
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
788
|
+
wireSocket(ws, wallet, meta, initialSeq, myGeneration, () => {
|
|
789
|
+
connectionStore.setStatus(validated.topic, 'active')
|
|
790
|
+
setStatus('connected')
|
|
791
|
+
})
|
|
792
|
+
},
|
|
793
|
+
[walletName, supersedeExistingSocket]
|
|
794
|
+
) // eslint-disable-line react-hooks/exhaustive-deps
|
|
717
795
|
|
|
718
796
|
// ── Provider ──────────────────────────────────────────────────────────────
|
|
719
797
|
|
|
720
|
-
const value = useMemo<WalletConnectionContextValue>(
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
798
|
+
const value = useMemo<WalletConnectionContextValue>(
|
|
799
|
+
() => ({
|
|
800
|
+
status,
|
|
801
|
+
sessionMeta,
|
|
802
|
+
errorMsg,
|
|
803
|
+
connect,
|
|
804
|
+
reconnect,
|
|
805
|
+
disconnect,
|
|
806
|
+
startNavTimer,
|
|
807
|
+
cancelNavTimer
|
|
808
|
+
}),
|
|
809
|
+
[status, sessionMeta, errorMsg, connect, reconnect, disconnect, startNavTimer, cancelNavTimer]
|
|
730
810
|
)
|
|
811
|
+
|
|
812
|
+
return <WalletConnectionContext.Provider value={value}>{children}</WalletConnectionContext.Provider>
|
|
731
813
|
}
|