@meshconnect/uwc-injected-connector 0.17.1 → 0.19.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.
@@ -1,10 +1,12 @@
1
1
  import type {
2
2
  Network,
3
+ Namespace,
3
4
  ExtensionInjectedProvider,
4
5
  IntegratedBrowserInjectedProvider,
5
6
  ConnectorResult,
6
7
  SwitchNetworkResult,
7
- AvailableAddress
8
+ AvailableAddress,
9
+ SolanaMetadata
8
10
  } from '@meshconnect/uwc-types'
9
11
  import { EthereumWalletService } from './ethereum/ethereum-wallet-service'
10
12
  import { SolanaWalletService } from './solana/solana-wallet-service'
@@ -60,15 +62,246 @@ function skipFramedSecondaryConnect(namespaceSafeFramed = false): boolean {
60
62
  return isFramedEmbed() && !namespaceSafeFramed
61
63
  }
62
64
 
65
+ /**
66
+ * Exception to Solana's `namespaceSafeFramed` exemption above (ONC-3536
67
+ * follow-up): wallets that declare a legacy `solana.injectedId` (currently
68
+ * Coinbase/Base Wallet's `coinbaseSolana`) treat the ACTIVE NAMESPACE as
69
+ * exclusive inside their own in-app browser. Any secondary Solana connect
70
+ * after an EVM connect — the eager gather OR the silent storage-flag
71
+ * reconnect — parks the wallet's active namespace on Solana; the later
72
+ * `wallet_switchEthereumChain` moves `window.ethereum`'s chain but not the
73
+ * wallet's active namespace, so the EVM `eth_sendTransaction` never surfaces
74
+ * an approval sheet (60s `walletTimedOut`). Proven with a Mesh-free PoC on
75
+ * Coinbase Wallet 30.3.3: EVM connect → send = sheet shown; EVM connect →
76
+ * `window.coinbaseSolana` connect → send = hang.
77
+ *
78
+ * The harm condition is RUNNING INSIDE THE WALLET'S OWN BROWSER, in either
79
+ * frame position:
80
+ * - `usingIntegratedBrowser` — the consumer runs TOP-LEVEL in the in-app
81
+ * browser (the dapp deep-link flow). `isFramedEmbed()` is false there, so
82
+ * an iframe-only gate misses exactly the flow that reproduced the hang.
83
+ * - `isFramedEmbed()` — the consumer is embedded in a client page opened
84
+ * inside the in-app browser.
85
+ *
86
+ * When the gate is on, a legacy-`injectedId` wallet gets NO secondary Solana
87
+ * connect of any kind (the passive already-connected check still runs).
88
+ * Wallet-Standard-only wallets (no `injectedId`, e.g. Phantom) keep the
89
+ * gather, PRIMARY Solana connects (`connectSolana`) are untouched — the
90
+ * ONC-3536 legacy fallback keeps working — and the desktop extension
91
+ * (top frame, not an integrated browser) is unchanged.
92
+ */
93
+ function skipLegacyInjectedSolanaSecondaryConnect(
94
+ solanaMeta: SolanaMetadata | undefined,
95
+ usingIntegratedBrowser: boolean
96
+ ): boolean {
97
+ return (
98
+ (isFramedEmbed() || usingIntegratedBrowser) &&
99
+ Boolean(solanaMeta?.injectedId)
100
+ )
101
+ }
102
+
103
+ /**
104
+ * Payload for the `onSecondarySolanaConnectSkipped` triage sink: the ONC-3536
105
+ * gate was active for a legacy-`injectedId` wallet's secondary Solana gather —
106
+ * in a framed embed OR top-level in the wallet's in-app browser (`framed`
107
+ * distinguishes the two). Metadata key + discovery/runtime facets only —
108
+ * never an address.
109
+ */
110
+ export interface SecondarySolanaConnectSkippedInfo {
111
+ /** The `solana.injectedId` metadata key that triggered the skip (e.g. `coinbaseSolana`). */
112
+ injectedId: string
113
+ /**
114
+ * What the active gate observed: `connectSuppressed` = a would-be connect
115
+ * was skipped; `alreadyConnected` = the passive check found the provider
116
+ * already authorized (no connect was needed or made) — if a hang still
117
+ * follows, the parking predates the gather and is wallet-side state.
118
+ */
119
+ outcome: 'connectSuppressed' | 'alreadyConnected'
120
+ /**
121
+ * True when the wallet was discovered via the legacy injected fallback
122
+ * (true "Legacy mode"); false when it registered via the Wallet Standard.
123
+ */
124
+ legacyInjected: boolean
125
+ /**
126
+ * True when the skip happened in a framed embed; false when it happened
127
+ * top-level in the wallet's in-app browser (the dapp deep-link flow).
128
+ */
129
+ framed: boolean
130
+ }
131
+
132
+ /**
133
+ * Cap for `injectedId` before it enters the dedup Set key or the triage
134
+ * callback payload. The value originates in catalog metadata (not live wallet
135
+ * input), but bound it here anyway — aligned with core telemetry's 64-char
136
+ * egress cap — so an oversized value can't bloat the Set or reach consumers.
137
+ */
138
+ const MAX_INJECTED_ID_LENGTH = 64
139
+
140
+ /** Optional collaborators for {@link ConnectionManager}. */
141
+ export interface ConnectionManagerOptions {
142
+ /**
143
+ * Whether this session runs inside a wallet's in-app browser (same flag the
144
+ * `InjectedConnector` receives) — one of the two triggers of the ONC-3536
145
+ * legacy-Solana gather gate, see
146
+ * {@link skipLegacyInjectedSolanaSecondaryConnect}.
147
+ */
148
+ usingIntegratedBrowser?: boolean | undefined
149
+ /**
150
+ * Triage telemetry sink (ONC-3536 follow-up): invoked when the ONC-3536
151
+ * gate is active for a legacy-`injectedId` wallet. Fires once per
152
+ * injectedId × outcome per instance — so it can fire twice for the same
153
+ * injectedId (`connectSuppressed` and `alreadyConnected`).
154
+ */
155
+ onSecondarySolanaConnectSkipped?:
156
+ | ((info: SecondarySolanaConnectSkippedInfo) => void)
157
+ | undefined
158
+ /**
159
+ * Telemetry sink: the wallet-switch guard released live per-namespace state
160
+ * that belonged to a different wallet (see
161
+ * {@link ConnectionManager.checkExistingConnections}). Fires once per
162
+ * connect attempt that released anything, with the released namespaces —
163
+ * never an address. Observability only; the release happens regardless.
164
+ */
165
+ onWalletConnectionsReleased?:
166
+ | ((info: { namespaces: Namespace[] }) => void)
167
+ | undefined
168
+ }
169
+
63
170
  export class ConnectionManager {
64
171
  private currentNetworkId: string | null = null
65
172
 
173
+ /** `${injectedId}:${outcome}` keys already reported via
174
+ * `onSecondarySolanaConnectSkipped` — dedupes the emit across repeated
175
+ * gathers per outcome (mirrors the legacy-discovery failure dedup in
176
+ * `InjectedConnector`, which keys on injectedId alone). */
177
+ private readonly reportedSolanaGatherSkips = new Set<string>()
178
+
179
+ private readonly usingIntegratedBrowser: boolean
180
+ private readonly onSecondarySolanaConnectSkipped?:
181
+ | ((info: SecondarySolanaConnectSkippedInfo) => void)
182
+ | undefined
183
+ private readonly onWalletConnectionsReleased?:
184
+ | ((info: { namespaces: Namespace[] }) => void)
185
+ | undefined
186
+
66
187
  constructor(
67
188
  private ethereumService: EthereumWalletService,
68
189
  private solanaService: SolanaWalletService,
69
190
  private tronService: TronWalletService,
70
- private tonService: TonWalletService
71
- ) {}
191
+ private tonService: TonWalletService,
192
+ options: ConnectionManagerOptions = {}
193
+ ) {
194
+ this.usingIntegratedBrowser = options.usingIntegratedBrowser ?? false
195
+ this.onSecondarySolanaConnectSkipped =
196
+ options.onSecondarySolanaConnectSkipped
197
+ this.onWalletConnectionsReleased = options.onWalletConnectionsReleased
198
+ }
199
+
200
+ /** Report the ACTIVE gate's observation, once per injectedId x outcome. */
201
+ private reportSecondarySolanaConnectSkipped(
202
+ meta: SolanaMetadata,
203
+ outcome: SecondarySolanaConnectSkippedInfo['outcome']
204
+ ): void {
205
+ const injectedId = meta.injectedId?.slice(0, MAX_INJECTED_ID_LENGTH)
206
+ if (!injectedId) return
207
+ const key = `${injectedId}:${outcome}`
208
+ if (this.reportedSolanaGatherSkips.has(key)) return
209
+ this.reportedSolanaGatherSkips.add(key)
210
+ this.onSecondarySolanaConnectSkipped?.({
211
+ injectedId,
212
+ outcome,
213
+ legacyInjected: meta.detectedWallet?.legacyInjected ?? false,
214
+ framed: isFramedEmbed()
215
+ })
216
+ }
217
+
218
+ /**
219
+ * Release any live per-namespace connection that does NOT belong to the
220
+ * wallet being connected (identified by `provider`'s detected metadata).
221
+ * Connecting wallet B while wallet A is still connected must behave like a
222
+ * fresh connect for B: without this, the in-memory reuse shortcuts below
223
+ * (and the cross-namespace gathers) hand B's session wallet A's account —
224
+ * the session shows A's address under B's name, signing keeps routing to
225
+ * A's provider, and A's other-namespace addresses leak into B's
226
+ * availableAddresses. Identity is compared per namespace on the live
227
+ * surface (EVM/Tron provider, Solana adapter, TON jsBridgeKey), so a
228
+ * same-wallet reconnect releases nothing and keeps its fast path. Local
229
+ * state only — A's wallet-side permissions are untouched (the disconnect()
230
+ * contract); TON is the exception, where the stale session is explicitly
231
+ * ended over the JS Bridge so the old wallet doesn't keep a live session.
232
+ *
233
+ * Fail-closed by design: when the target wallet's identity for a namespace
234
+ * can't be established (no `detectedWallet` uuid, or the uuid no longer
235
+ * resolves), a live connection is released rather than reused — reusing
236
+ * state we can't attribute to the requested wallet is exactly the
237
+ * cross-wallet mixup this guard exists to prevent. This cannot strand a
238
+ * same-wallet reconnect: every path that reaches the connected state
239
+ * (`connect*` throws, the silent checks skip) requires the detected uuid,
240
+ * and detection stamps that uuid on the same metadata object `connect()`
241
+ * passes back in, so a wallet that was ever connected presents a uuid that
242
+ * resolves to its own live surface. The one benign spurious release is
243
+ * Solana adapter-instance churn (a consumer re-running discovery replaces
244
+ * adapter instances): the follow-up silent check re-binds the fresh adapter
245
+ * from `wallet.accounts` without a wallet round-trip.
246
+ */
247
+ private async releaseOtherWalletConnections(
248
+ provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
249
+ ): Promise<void> {
250
+ const released: Namespace[] = []
251
+
252
+ const connectedEthProvider = this.ethereumService.getConnectedProvider()
253
+ if (connectedEthProvider) {
254
+ const uuid = provider.namespaceMetaData?.eip155?.detectedWallet?.uuid
255
+ const target = uuid
256
+ ? this.ethereumService.findWalletByUuid(uuid)
257
+ : undefined
258
+ if (target?.provider !== connectedEthProvider) {
259
+ this.ethereumService.disconnect()
260
+ released.push('eip155')
261
+ }
262
+ }
263
+
264
+ const connectedAdapter = this.solanaService.getConnectedAdapter()
265
+ if (connectedAdapter) {
266
+ const uuid = provider.namespaceMetaData?.solana?.detectedWallet?.uuid
267
+ const target = uuid
268
+ ? this.solanaService.findWalletByUuid(uuid)
269
+ : undefined
270
+ if (target?.adapter !== connectedAdapter) {
271
+ this.solanaService.disconnect()
272
+ released.push('solana')
273
+ }
274
+ }
275
+
276
+ const connectedTronProvider = this.tronService.getConnectedProvider()
277
+ if (connectedTronProvider) {
278
+ const uuid = provider.namespaceMetaData?.tron?.detectedWallet?.uuid
279
+ const target = uuid ? this.tronService.findWalletByUuid(uuid) : undefined
280
+ if (target?.provider !== connectedTronProvider) {
281
+ this.tronService.disconnect()
282
+ released.push('tron')
283
+ }
284
+ }
285
+
286
+ if (this.tonService.isConnected()) {
287
+ const jsBridgeKey =
288
+ provider.namespaceMetaData?.tvm?.detectedWallet?.jsBridgeKey
289
+ if (
290
+ !jsBridgeKey ||
291
+ this.tonService.getConnectedJsBridgeKey() !== jsBridgeKey
292
+ ) {
293
+ await this.tonService.disconnect()
294
+ released.push('tvm')
295
+ }
296
+ }
297
+
298
+ // Surface the release (observability only — it already happened). An
299
+ // unexpected emit, e.g. during a same-wallet reconnect, is the prod
300
+ // signal that a namespace's identity comparison broke.
301
+ if (released.length > 0) {
302
+ this.onWalletConnectionsReleased?.({ namespaces: released })
303
+ }
304
+ }
72
305
 
73
306
  /**
74
307
  * Check and add existing connections from other namespaces
@@ -80,6 +313,11 @@ export class ConnectionManager {
80
313
  address: string | null
81
314
  availableAddresses: AvailableAddress[]
82
315
  }> {
316
+ // A different wallet's live state must not be reused as "already
317
+ // connected" — drop it first so every branch below only ever sees state
318
+ // belonging to the wallet actually being connected.
319
+ await this.releaseOtherWalletConnections(provider)
320
+
83
321
  const availableAddresses: AvailableAddress[] = []
84
322
  let currentAddress: string | null = null
85
323
 
@@ -296,9 +534,16 @@ export class ConnectionManager {
296
534
 
297
535
  // If not connected, try to check existing connection
298
536
  if (!solanaAccount) {
299
- const solanaWalletUuid =
300
- provider.namespaceMetaData?.solana?.detectedWallet?.uuid
537
+ const solanaMeta = provider.namespaceMetaData?.solana
538
+ const solanaWalletUuid = solanaMeta?.detectedWallet?.uuid
301
539
  if (solanaWalletUuid) {
540
+ // Legacy-`injectedId` wallets inside the wallet's own browser (framed
541
+ // OR top-level in-app) get NO secondary Solana connect (eager or
542
+ // silent reconnect) — see skipLegacyInjectedSolanaSecondaryConnect.
543
+ const skipLegacyConnect = skipLegacyInjectedSolanaSecondaryConnect(
544
+ solanaMeta,
545
+ this.usingIntegratedBrowser
546
+ )
302
547
  const solanaWallet =
303
548
  this.solanaService.findWalletByUuid(solanaWalletUuid)
304
549
  if (solanaWallet?.adapter) {
@@ -306,9 +551,11 @@ export class ConnectionManager {
306
551
  const solanaAddress =
307
552
  (await this.solanaService.checkExistingConnection(
308
553
  solanaWallet.adapter,
309
- solanaWalletUuid
554
+ solanaWalletUuid,
555
+ { allowSilentReconnect: !skipLegacyConnect }
310
556
  )) ||
311
- (skipFramedSecondaryConnect(/* namespaceSafeFramed */ true)
557
+ (skipLegacyConnect ||
558
+ skipFramedSecondaryConnect(/* namespaceSafeFramed */ true)
312
559
  ? undefined
313
560
  : await this.solanaService.connect(
314
561
  solanaWallet.adapter,
@@ -321,6 +568,20 @@ export class ConnectionManager {
321
568
  solanaAddress,
322
569
  solanaWalletUuid
323
570
  )
571
+ if (skipLegacyConnect && solanaMeta) {
572
+ // Gate active but the provider was ALREADY authorized — no
573
+ // connect was made; a hang after this is wallet-side state.
574
+ this.reportSecondarySolanaConnectSkipped(
575
+ solanaMeta,
576
+ 'alreadyConnected'
577
+ )
578
+ }
579
+ } else if (skipLegacyConnect && solanaMeta) {
580
+ // The gate suppressed a would-be connect — surface it.
581
+ this.reportSecondarySolanaConnectSkipped(
582
+ solanaMeta,
583
+ 'connectSuppressed'
584
+ )
324
585
  }
325
586
  } catch {
326
587
  // Solana namespace not available — continue without it
@@ -0,0 +1,67 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { SolanaWalletService } from './solana-wallet-service'
3
+ import { StorageService } from '../storage-service'
4
+ import type { SolanaAdapter } from '../../wallet-standard-discovery'
5
+
6
+ // ONC-3536 follow-up: `checkExistingConnection`'s storage-flag reconnect is a
7
+ // REAL provider connect — for a legacy-`injectedId` wallet inside its own
8
+ // in-app browser it parks the wallet's active namespace on Solana and the next
9
+ // EVM send never surfaces an approval sheet. `allowSilentReconnect: false`
10
+ // makes the check purely passive so the secondary gather can stay safe.
11
+ describe('SolanaWalletService.checkExistingConnection — allowSilentReconnect', () => {
12
+ function setup({ previouslyConnected }: { previouslyConnected: boolean }) {
13
+ const storage = new StorageService()
14
+ vi.spyOn(storage, 'wasSolanaWalletPreviouslyConnected').mockReturnValue(
15
+ previouslyConnected
16
+ )
17
+ const service = new SolanaWalletService(storage)
18
+ const connect = vi.fn().mockImplementation(async () => {
19
+ adapter.publicKey = { toBase58: () => 'SolAddr1' }
20
+ })
21
+ const adapter = {
22
+ publicKey: undefined as { toBase58(): string } | undefined,
23
+ connecting: false,
24
+ connect
25
+ }
26
+ return { service, adapter, connect }
27
+ }
28
+
29
+ it('silently reconnects a previously-connected wallet by default', async () => {
30
+ const { service, adapter, connect } = setup({ previouslyConnected: true })
31
+
32
+ const address = await service.checkExistingConnection(
33
+ adapter as unknown as SolanaAdapter,
34
+ 'wallet-1'
35
+ )
36
+
37
+ expect(connect).toHaveBeenCalled()
38
+ expect(address).toBe('SolAddr1')
39
+ })
40
+
41
+ it('stays purely passive when allowSilentReconnect is false (no adapter.connect)', async () => {
42
+ const { service, adapter, connect } = setup({ previouslyConnected: true })
43
+
44
+ const address = await service.checkExistingConnection(
45
+ adapter as unknown as SolanaAdapter,
46
+ 'wallet-1',
47
+ { allowSilentReconnect: false }
48
+ )
49
+
50
+ expect(connect).not.toHaveBeenCalled()
51
+ expect(address).toBeNull()
52
+ })
53
+
54
+ it('still returns an already-present publicKey without connecting, even when reconnect is disallowed', async () => {
55
+ const { service, adapter, connect } = setup({ previouslyConnected: true })
56
+ adapter.publicKey = { toBase58: () => 'SolAddr2' }
57
+
58
+ const address = await service.checkExistingConnection(
59
+ adapter as unknown as SolanaAdapter,
60
+ 'wallet-1',
61
+ { allowSilentReconnect: false }
62
+ )
63
+
64
+ expect(connect).not.toHaveBeenCalled()
65
+ expect(address).toBe('SolAddr2')
66
+ })
67
+ })
@@ -55,12 +55,20 @@ export class SolanaWalletService {
55
55
  }
56
56
 
57
57
  /**
58
- * Check if a Solana wallet is already connected
58
+ * Check if a Solana wallet is already connected.
59
+ *
60
+ * `allowSilentReconnect` (default true) gates the storage-flag reconnect
61
+ * below: even a "silent" `adapter.connect()` is a REAL provider connect —
62
+ * for a legacy-`injectedId` wallet in its in-app browser it parks the
63
+ * wallet's active namespace on Solana and swallows the next EVM send
64
+ * (ONC-3536 follow-up). Pass false to make this check purely passive.
59
65
  */
60
66
  async checkExistingConnection(
61
67
  adapter: SolanaAdapter,
62
- walletUuid: string
68
+ walletUuid: string,
69
+ options?: { allowSilentReconnect?: boolean }
63
70
  ): Promise<string | null> {
71
+ const allowSilentReconnect = options?.allowSilentReconnect ?? true
64
72
  try {
65
73
  const base58PublicKey = await adapter.publicKey?.toBase58()
66
74
  // Check if adapter has a publicKey (means it's connected)
@@ -70,7 +78,10 @@ export class SolanaWalletService {
70
78
 
71
79
  // If this wallet was previously connected, try to reconnect
72
80
  // This should work without prompting for wallets that support it
73
- if (this.storageService.wasSolanaWalletPreviouslyConnected(walletUuid)) {
81
+ if (
82
+ allowSilentReconnect &&
83
+ this.storageService.wasSolanaWalletPreviouslyConnected(walletUuid)
84
+ ) {
74
85
  const walletIsConnecting = await adapter.connecting
75
86
  if (!walletIsConnecting) {
76
87
  try {