@meshconnect/uwc-injected-connector 0.23.3 → 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.
@@ -34,18 +34,111 @@ import { resolveInjectedProperty } from '../../legacy-injected-solana-adapter'
34
34
  * than imported from `@wallet-standard/features`, matching this codebase's
35
35
  * existing convention of not adding a new dependency for a few fields.
36
36
  */
37
+ /**
38
+ * A wallet-standard `change` event stream. Aliased because bip122 wallets
39
+ * publish it under two different feature keys and the shape is identical for
40
+ * both — writing the signature out twice invites them drifting apart.
41
+ */
42
+ interface Bip122ChangeEvents {
43
+ on?: (
44
+ event: 'change',
45
+ listener: (properties: { accounts?: readonly unknown[] }) => void
46
+ ) => () => void
47
+ }
48
+
37
49
  interface StandardEventsCapableWallet {
38
50
  accounts?: readonly { address: string }[]
39
51
  features?: {
40
- 'standard:events'?: {
41
- on?: (
42
- event: 'change',
43
- listener: (properties: { accounts?: readonly unknown[] }) => void
44
- ) => () => void
45
- }
52
+ 'standard:events'?: Bip122ChangeEvents
53
+ // MetaMask publishes its bitcoin account-change stream under
54
+ // `bitcoin:events`, NOT `standard:events` (Trust uses the latter). Same
55
+ // `on('change', …)` contract, different key — so both are read. Mirrors
56
+ // `BridgeParent.ts`'s identically-named type.
57
+ 'bitcoin:events'?: Bip122ChangeEvents
46
58
  }
47
59
  }
48
60
 
61
+ /**
62
+ * Bech32 human-readable parts for the bip122 networks this connector supports.
63
+ * Bech32/bech32m is case-INSENSITIVE by spec (BIP-173: a valid address is all
64
+ * lower or all upper), so folding case is correct for these and only these.
65
+ */
66
+ const BECH32_PREFIXES = ['bc1', 'tb1', 'bcrt1']
67
+
68
+ /**
69
+ * Normalize one address for pin comparison.
70
+ *
71
+ * Case is folded ONLY for bech32. Base58Check (legacy `1…`/`3…`) is
72
+ * case-SENSITIVE: its characters carry different values per case, so a
73
+ * differently-cased string decodes to a different payload and fails its
74
+ * checksum. Folding those would let a mis-cased pin match a real address —
75
+ * silently accepting a corrupted allow-list entry instead of reporting the
76
+ * mismatch. (It could never equate two *valid* distinct addresses, which is why
77
+ * this is a correctness-hygiene fix rather than a live conflation bug.)
78
+ */
79
+ function normalizeAddress(address: string): string {
80
+ const trimmed = address.trim()
81
+ const lower = trimmed.toLowerCase()
82
+ const isBech32 = BECH32_PREFIXES.some(prefix => lower.startsWith(prefix))
83
+ // BIP-173 forbids MIXED case outright ("Decoders MUST NOT accept strings
84
+ // where some characters are uppercase and some are lowercase"), so only a
85
+ // uniformly-cased string is a valid bech32 address worth folding. Folding a
86
+ // mixed-case one would let an INVALID pin match a valid wallet address —
87
+ // the same false-accept this function exists to prevent for base58.
88
+ const uniformCase = trimmed === lower || trimmed === trimmed.toUpperCase()
89
+ return isBech32 && uniformCase ? lower : trimmed
90
+ }
91
+
92
+ /** Comparison key for an account-shaped value. */
93
+ const addressKey = (account: { address: string }): string =>
94
+ normalizeAddress(account.address)
95
+
96
+ /**
97
+ * Normalize a caller's pinned address allow-list to a lower-cased lookup set,
98
+ * or `undefined` when there is no real constraint.
99
+ *
100
+ * Blank entries are dropped first: a stray `''` would otherwise match nothing
101
+ * while still making the list look non-empty, silently failing every account.
102
+ * An all-blank list therefore behaves exactly like no list at all.
103
+ *
104
+ * Entries are keyed with {@link normalizeAddress}, so bech32 compares
105
+ * case-insensitively (per BIP-173) while legacy Base58Check compares exactly.
106
+ */
107
+ export function normalizeRequiredAddresses(
108
+ requiredAddresses?: readonly string[]
109
+ ): Set<string> | undefined {
110
+ if (!requiredAddresses?.length) return undefined
111
+ const normalized = requiredAddresses
112
+ .filter(address => address.trim().length > 0)
113
+ .map(normalizeAddress)
114
+ return normalized.length > 0 ? new Set(normalized) : undefined
115
+ }
116
+
117
+ /** Does `address` satisfy a normalized pin set? */
118
+ export function pinIncludes(pinned: Set<string>, address: string): boolean {
119
+ return pinned.has(normalizeAddress(address))
120
+ }
121
+
122
+ /**
123
+ * What happened when a pinned-address connect tried to re-authorize.
124
+ *
125
+ * Without this a declined re-prompt is indistinguishable from an ordinary
126
+ * connect failure, and an `unsupported` revoke — the framed case, where the
127
+ * bridge may not carry `bitcoin:disconnect` — looks identical to a wallet that
128
+ * simply returned the wrong account. Carries no address; wallet name only.
129
+ *
130
+ * - `revoked` — grant dropped and the wallet re-prompted.
131
+ * - `declined` — grant dropped, then the user rejected the re-prompt. The
132
+ * connect fails; there is no prior grant left to fall back to.
133
+ * - `unsupported` — no revoke available, so the grant is intact and the pin
134
+ * cannot be satisfied. The connect succeeds with the granted account.
135
+ */
136
+ export interface BitcoinReauthorizeInfo {
137
+ walletName: string
138
+ revoked: boolean
139
+ outcome: 'revoked' | 'declined' | 'unsupported'
140
+ }
141
+
49
142
  /**
50
143
  * Bitcoin (bip122) wallet service for the injected transport — the peer of
51
144
  * `EthereumWalletService` / `SolanaWalletService` / `TronWalletService` /
@@ -83,8 +176,28 @@ export class BitcoinWalletService {
83
176
  * read and account-change subscription go through this provider instead.
84
177
  */
85
178
  private connectedOkxProvider: OkxBitcoinProvider | null = null
179
+ /**
180
+ * Number of re-authorizations currently in flight — non-zero only while
181
+ * `connect()` is revoking a grant to re-prompt for a pinned address. Wallets
182
+ * emit an empty account list when a grant is revoked, and core reads `[]` as a
183
+ * namespace disconnect — see {@link guardReauthorizeTeardown}.
184
+ *
185
+ * A COUNTER, not a boolean, because two pinned connects can overlap: core
186
+ * supersedes a re-entrant `connect()` by aborting the previous attempt's
187
+ * wrapper (`connection-service.ts:106`), which cannot cancel the wallet prompt
188
+ * already open, and both attempts share this connector instance. With a
189
+ * boolean, the older attempt's `finally` cleared the newer attempt's guard and
190
+ * let the revoke teardown through — the exact event this exists to absorb.
191
+ */
192
+ private reauthorizing = 0
86
193
 
87
- constructor(private readonly config?: BitcoinConfig) {}
194
+ constructor(
195
+ private readonly config?: BitcoinConfig,
196
+ /** Telemetry sink for re-authorization outcomes (see {@link BitcoinReauthorizeInfo}). */
197
+ private readonly reportReauthorize?: (
198
+ info: BitcoinReauthorizeInfo
199
+ ) => void | undefined
200
+ ) {}
88
201
 
89
202
  /**
90
203
  * Initialize wallet discovery from the Wallet Standard `bitcoin:*` registry,
@@ -113,19 +226,40 @@ export class BitcoinWalletService {
113
226
  * Check if a Bitcoin wallet is already authorized (non-prompting). Reads
114
227
  * the Wallet Standard wallet's already-exposed `accounts` directly — never
115
228
  * calls `bitcoin:connect`, which pops a wallet dialog.
229
+ *
230
+ * `requiredAddresses` (the caller's pinned allow-list, e.g. a verify flow's
231
+ * `addresses`) makes the probe address-AWARE. `wallet.accounts` is the
232
+ * PER-ORIGIN authorized set, not the wallet's current UI selection: MetaMask
233
+ * keeps serving the account this origin first authorized even after the user
234
+ * selects a different one in the extension. Returning `accounts[0]`
235
+ * unconditionally therefore pinned the session to that first-authorized
236
+ * account and left the user no way to reach any other one — the connect that
237
+ * could re-authorize was skipped precisely because this probe "succeeded".
238
+ *
239
+ * So: when the caller pinned addresses and none of the authorized accounts
240
+ * match, report NO existing connection. The caller then falls through to the
241
+ * prompting `connect()`, which is the only path that can authorize a
242
+ * different account. With no pins, behaviour is unchanged (`accounts[0]`).
116
243
  */
117
244
  async checkExistingConnection(
118
- detectedWallet: DetectedBitcoinWallet
245
+ detectedWallet: DetectedBitcoinWallet,
246
+ requiredAddresses?: readonly string[]
119
247
  ): Promise<string | null> {
120
248
  const wallet =
121
249
  detectedWallet.wallet as unknown as WalletStandardBitcoinWallet
122
- const account = wallet.accounts?.[0]
123
- return account?.address ?? null
250
+ const accounts = wallet.accounts ?? []
251
+ const pinned = normalizeRequiredAddresses(requiredAddresses)
252
+ if (pinned) {
253
+ const matched = accounts.find(account => pinned.has(addressKey(account)))
254
+ return matched?.address ?? null
255
+ }
256
+ return accounts[0]?.address ?? null
124
257
  }
125
258
 
126
259
  async connect(
127
260
  network: Network,
128
- provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
261
+ provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
262
+ requiredAddresses?: readonly string[]
129
263
  ): Promise<ConnectorResult> {
130
264
  // Resolve the SPECIFIC wallet the session matched by uuid (mirrors every
131
265
  // other service) — fails closed rather than picking an arbitrary wallet.
@@ -139,8 +273,116 @@ export class BitcoinWalletService {
139
273
  const { namespace, okxProvider } = this.buildNamespace(detected)
140
274
  namespace.assertSupportedNetwork(network)
141
275
 
142
- const accounts = await namespace.getAccounts()
143
- const primary = accounts[0]
276
+ // Did this origin already hold a grant BEFORE this connect? Two sources,
277
+ // because neither alone is sufficient:
278
+ //
279
+ // - `wallet.accounts` must be read BEFORE `getAccounts()`. That calls
280
+ // `bitcoin:connect`, and a wallet's `accounts` reflects the authorization
281
+ // live (MetaMask sets its account before the connect resolves), so
282
+ // reading it afterwards always reports "granted" and the guard below
283
+ // would never gate anything.
284
+ // - FRAMED, `wallet.accounts` is a one-time snapshot marshaled by
285
+ // `BridgeChild` — proxied `bitcoin:connect` calls never update it. A
286
+ // bridge that started with no grant therefore reports empty forever, even
287
+ // after this session authorized an account. `this.account` is the
288
+ // connector's own live record and covers exactly that gap.
289
+ //
290
+ // Either signal means the origin was already granted, so a pin that the
291
+ // wallet won't satisfy needs a revoke rather than a silent stale account.
292
+ const previouslyGranted =
293
+ ((detected.wallet as unknown as { accounts?: readonly unknown[] })
294
+ .accounts?.length ?? 0) > 0 || this.account !== null
295
+
296
+ let accounts = await namespace.getAccounts()
297
+ // Honour the caller's pinned allow-list when the wallet authorized more
298
+ // than one account. `accounts[0]` is the wallet's own ordering, which has
299
+ // no relationship to what the caller asked for — picking it blindly put
300
+ // the requested address in `availableAddresses` while making some OTHER
301
+ // account the session's active one. (MetaMask exposes only one account, so
302
+ // this preference is inert there; it matters for multi-account wallets.)
303
+ const pinned = normalizeRequiredAddresses(requiredAddresses)
304
+ const matches = (list: BitcoinAccount[]): BitcoinAccount | undefined =>
305
+ pinned ? list.find(account => pinned.has(addressKey(account))) : undefined
306
+
307
+ let primary = (pinned && matches(accounts)) || accounts[0]
308
+
309
+ // Pin unsatisfiable: re-authorize so the wallet can offer its account
310
+ // picker. `bitcoin:connect` alone cannot fix this — it is authorization,
311
+ // not account selection, so once an origin holds a grant the wallet
312
+ // answers from that grant and returns the SAME account no matter how many
313
+ // times it is called. Revoking first makes the next connect a real prompt,
314
+ // where the user can pick the pinned account.
315
+ //
316
+ // Gated on a PRE-EXISTING grant: only a cached grant can block the pin.
317
+ // With no grant, the `getAccounts()` above already showed the picker, and
318
+ // re-prompting would ask the user to choose again immediately after they
319
+ // just chose — confusing, and it cannot surface any account the first
320
+ // prompt did not already offer.
321
+ if (pinned && !matches(accounts) && previouslyGranted) {
322
+ // The revoke below makes the wallet emit an empty account list, which
323
+ // core would act on as a disconnect — mid-connect. Suppress just that
324
+ // for the duration; see `guardReauthorizeTeardown`.
325
+ this.reauthorizing++
326
+ try {
327
+ // A REJECTED revoke means nothing happened at the wallet, so the grant
328
+ // is intact — the same situation as a wallet with no revoke feature.
329
+ // Treat it that way instead of letting it propagate: throwing here would
330
+ // fail a connect whose authorization is still perfectly good, which
331
+ // contradicts the branch-on-what-actually-happened rule below.
332
+ let revoked = false
333
+ try {
334
+ ;({ revoked } = await namespace.disconnect())
335
+ } catch {
336
+ revoked = false
337
+ }
338
+ this.reportReauthorize?.({
339
+ walletName: detected.name,
340
+ revoked,
341
+ outcome: revoked ? 'revoked' : 'unsupported'
342
+ })
343
+
344
+ if (revoked) {
345
+ // Tear down any LIVE session before awaiting the new authorization.
346
+ // Session state is committed at the end of a successful connect, so a
347
+ // reconnect (the case this feature exists for) still holds the previous
348
+ // account here — and the revoke above just invalidated it at the wallet.
349
+ // Without this, a declined re-prompt throws while `isConnected()` still
350
+ // reports the revoked account as connected, and the next `signMessage`
351
+ // would address an account the wallet no longer authorizes.
352
+ this.setConnectionState(null, null)
353
+
354
+ // The grant is GONE. A rejection here has nothing to fall back to:
355
+ // committing the pre-revoke accounts would report a live session the
356
+ // wallet just revoked, and report success for a connect the user
357
+ // declined. So let it propagate.
358
+ try {
359
+ accounts = await namespace.getAccounts()
360
+ } catch (error) {
361
+ this.reportReauthorize?.({
362
+ walletName: detected.name,
363
+ revoked: true,
364
+ outcome: 'declined'
365
+ })
366
+ throw error
367
+ }
368
+ // Still no match (user picked something else, or the wallet exposes a
369
+ // single account): fall back to position rather than failing a connect
370
+ // that succeeded. The caller compares against its own pin and shows the
371
+ // mismatch — throwing here would lose `availableAddresses`.
372
+ primary = matches(accounts) || accounts[0]
373
+ }
374
+ // Not revoked (wallet exposes no `bitcoin:disconnect`, e.g. OKX, or a
375
+ // bridge that doesn't marshal it): the grant is intact, so re-connecting
376
+ // would return the same accounts. Keep what we have rather than burning a
377
+ // prompt — the caller surfaces the mismatch.
378
+ } finally {
379
+ // Also on the declined-re-prompt throw above: that path already tore
380
+ // the session down, so later events must flow normally again. Decrement
381
+ // rather than clear, so an overlapping attempt keeps its own guard.
382
+ this.reauthorizing--
383
+ }
384
+ }
385
+
144
386
  if (!primary) {
145
387
  throw new Error('Bitcoin wallet returned no accounts')
146
388
  }
@@ -286,13 +528,17 @@ export class BitcoinWalletService {
286
528
  onAccountsChanged(
287
529
  listener: (accounts: string[]) => void
288
530
  ): (() => void) | undefined {
531
+ // Applied to every transport below, so a revoke-driven `[]` is dropped the
532
+ // same way whether it arrives via OKX, the bridge, or `standard:events`.
533
+ const guarded = this.guardReauthorizeTeardown(listener)
534
+
289
535
  // OKX (legacy-injected) is always in-frame — subscribe to its own
290
536
  // `accountsChanged` event directly, never the bridge. The provider emits
291
537
  // `accountsChanged` with the new address list.
292
538
  if (this.connectedOkxProvider) {
293
539
  const provider = this.connectedOkxProvider
294
540
  const handler = (accounts: string[]) =>
295
- listener(Array.isArray(accounts) ? accounts : [])
541
+ guarded(Array.isArray(accounts) ? accounts : [])
296
542
  provider.on('accountsChanged', handler)
297
543
  return () => {
298
544
  try {
@@ -308,19 +554,32 @@ export class BitcoinWalletService {
308
554
  (window as unknown as { UWCBridgeChildInitialized?: boolean })
309
555
  .UWCBridgeChildInitialized === true
310
556
  ) {
311
- return this.subscribeAccountsChangedViaBridge(listener)
557
+ return this.subscribeAccountsChangedViaBridge(guarded)
312
558
  }
313
559
 
314
560
  const wallet = this
315
561
  .connectedWallet as unknown as StandardEventsCapableWallet | null
316
- const standardEvents = wallet?.features?.['standard:events']
317
- if (!wallet || typeof standardEvents?.on !== 'function') return undefined
318
-
319
- const off = standardEvents.on('change', properties => {
562
+ // Wallets disagree on where the bitcoin account-change stream lives: Trust
563
+ // publishes `standard:events`, MetaMask publishes `bitcoin:events`. Both
564
+ // expose the same `on('change', …)` contract, so try the standard key
565
+ // first and fall back to the namespaced one — without this, a MetaMask
566
+ // account switch was silently unobservable.
567
+ // Select on CALLABILITY, not presence: a wallet exposing a malformed
568
+ // `standard:events` (no `on`) alongside a working `bitcoin:events` would
569
+ // otherwise lose its subscription entirely. Same selection as the bridge's
570
+ // `subscribeBip122WalletEvent`, so framed and direct behave identically.
571
+ const features = wallet?.features
572
+ const changeEvents =
573
+ typeof features?.['standard:events']?.on === 'function'
574
+ ? features['standard:events']
575
+ : features?.['bitcoin:events']
576
+ if (!wallet || typeof changeEvents?.on !== 'function') return undefined
577
+
578
+ const off = changeEvents.on('change', properties => {
320
579
  // React only to account-set changes; ignore pure chain/feature deltas.
321
580
  if (!properties || !('accounts' in properties)) return
322
581
  const address = wallet.accounts?.[0]?.address ?? null
323
- listener(address ? [address] : [])
582
+ guarded(address ? [address] : [])
324
583
  })
325
584
  return () => {
326
585
  try {
@@ -331,6 +590,29 @@ export class BitcoinWalletService {
331
590
  }
332
591
  }
333
592
 
593
+ /**
594
+ * Drop the empty-account event a wallet emits while `connect()` is revoking
595
+ * a grant in order to re-prompt for a pinned address.
596
+ *
597
+ * Core treats `[]` as a namespace disconnect and calls `finishDisconnect()`.
598
+ * During a pinned reconnect that teardown lands in the middle of the very
599
+ * connect that asked for the revoke, so the caller gets a resolved connect
600
+ * with no session behind it.
601
+ *
602
+ * Only `[]` is suppressed — a real account list still flows through, so an
603
+ * account switch during the window is not lost. A genuine user disconnect in
604
+ * that window is not lost either: a successful connect commits fresh state
605
+ * over it, and a declined one has already torn the session down itself.
606
+ */
607
+ private guardReauthorizeTeardown(
608
+ listener: (accounts: string[]) => void
609
+ ): (accounts: string[]) => void {
610
+ return accounts => {
611
+ if (this.reauthorizing > 0 && accounts.length === 0) return
612
+ listener(accounts)
613
+ }
614
+ }
615
+
334
616
  /**
335
617
  * Bridge half of `onAccountsChanged`. `walletId` is `connectedWalletUuid`
336
618
  * — the SAME id `BridgeParent`'s `bip122Wallets[].uuid` publishes (see
@@ -444,10 +726,19 @@ export class BitcoinWalletService {
444
726
  this.connectedWallet = wallet
445
727
  }
446
728
 
447
- async disconnect(): Promise<void> {
448
- if (this.namespace) {
449
- await this.namespace.disconnect()
450
- }
729
+ /**
730
+ * Drop local session state WITHOUT revoking at the wallet.
731
+ *
732
+ * `ConnectionManager.releaseOtherWalletConnections` runs on EVERY connect and
733
+ * releases whichever namespaces belong to a different wallet. Now that
734
+ * `disconnect()` genuinely revokes, calling it from there would revoke the
735
+ * user's Bitcoin grant as a side effect of connecting an unrelated wallet —
736
+ * connect Phantom, lose the bip122 authorization. Releasing is a local-state
737
+ * concern; only an explicit disconnect (or a pinned re-authorization) means to
738
+ * revoke. This keeps the release path behaving as it did before `disconnect`
739
+ * started reaching the wallet.
740
+ */
741
+ releaseLocalSession(): void {
451
742
  this.namespace = null
452
743
  this.account = null
453
744
  this.connectedWalletUuid = null
@@ -455,6 +746,20 @@ export class BitcoinWalletService {
455
746
  this.connectedOkxProvider = null
456
747
  }
457
748
 
749
+ async disconnect(): Promise<void> {
750
+ if (this.namespace) {
751
+ try {
752
+ await this.namespace.disconnect()
753
+ } catch {
754
+ // Best effort, mirroring `TonWalletService.disconnect`: the wallet may
755
+ // already be disconnected. Local state must be cleared either way —
756
+ // with the resets after an un-caught await, a rejected revoke left the
757
+ // service still reporting `isConnected()` on a dead session.
758
+ }
759
+ }
760
+ this.releaseLocalSession()
761
+ }
762
+
458
763
  /**
459
764
  * Build the namespace for a detected wallet, selecting the adapter by its
460
765
  * kind: OKX legacy-injected (`legacyInjectedId` set) → `OkxBitcoinAdapter`
@@ -1195,6 +1195,44 @@ describe('ConnectionManager — wallet switch releases the other wallet’s conn
1195
1195
  })
1196
1196
  })
1197
1197
 
1198
+ // FRAMED, the wallet handle's `accounts` is a one-time snapshot marshaled by
1199
+ // `BridgeChild`; proxied connects never refresh it. A LIVE account that misses
1200
+ // the pin is therefore authoritative evidence the session moved past that
1201
+ // snapshot — probing it anyway could "find" the pin in obsolete data and
1202
+ // restore an account the wallet has since revoked, skipping the real connect.
1203
+ it('does not consult the wallet snapshot when a live bip122 account misses the pin', async () => {
1204
+ bitcoinService.getAccount.mockReturnValue('bc1qstale')
1205
+ bitcoinService.findWalletByUuid.mockReturnValue({ uuid: 'mm-bip122' })
1206
+ // The snapshot DOES contain the pin — this must not be trusted.
1207
+ bitcoinService.checkExistingConnection.mockResolvedValue('bc1qwanted')
1208
+
1209
+ const result = await manager.checkExistingConnections(
1210
+ 'bip122',
1211
+ makeProvider({ bip122: { detectedWallet: { uuid: 'mm-bip122' } } }),
1212
+ ['bc1qwanted']
1213
+ )
1214
+
1215
+ expect(bitcoinService.checkExistingConnection).not.toHaveBeenCalled()
1216
+ expect(bitcoinService.setConnectionState).not.toHaveBeenCalled()
1217
+ // No address reported → the caller falls through to the prompting connect.
1218
+ expect(result.address).toBeNull()
1219
+ })
1220
+
1221
+ it('does consult the snapshot when there is no live bip122 account', async () => {
1222
+ bitcoinService.getAccount.mockReturnValue(null)
1223
+ bitcoinService.findWalletByUuid.mockReturnValue({ uuid: 'mm-bip122' })
1224
+ bitcoinService.checkExistingConnection.mockResolvedValue('bc1qwanted')
1225
+
1226
+ const result = await manager.checkExistingConnections(
1227
+ 'bip122',
1228
+ makeProvider({ bip122: { detectedWallet: { uuid: 'mm-bip122' } } }),
1229
+ ['bc1qwanted']
1230
+ )
1231
+
1232
+ expect(bitcoinService.checkExistingConnection).toHaveBeenCalled()
1233
+ expect(result.address).toBe('bc1qwanted')
1234
+ })
1235
+
1198
1236
  it('keeps the same wallet’s EVM connection (no release, no re-check)', async () => {
1199
1237
  const walletAProvider = { isWalletA: true }
1200
1238
  ethService.getAccount.mockReturnValue('0xAAA')
@@ -15,7 +15,11 @@ import { EthereumWalletService } from './ethereum/ethereum-wallet-service'
15
15
  import { SolanaWalletService } from './solana/solana-wallet-service'
16
16
  import { TronWalletService } from './tron/tron-wallet-service'
17
17
  import { TonWalletService } from './ton/ton-wallet-service'
18
- import { BitcoinWalletService } from './bitcoin/bitcoin-wallet-service'
18
+ import {
19
+ BitcoinWalletService,
20
+ normalizeRequiredAddresses,
21
+ pinIncludes
22
+ } from './bitcoin/bitcoin-wallet-service'
19
23
  import { assertBitcoinNetwork } from '@meshconnect/uwc-bitcoin'
20
24
  import { parseError } from '../utils/error-utils'
21
25
 
@@ -192,6 +196,22 @@ export interface SecondarySolanaConnectGatheredInfo {
192
196
  */
193
197
  const MAX_INJECTED_ID_LENGTH = 64
194
198
 
199
+ /**
200
+ * Does `address` satisfy the caller's pinned allow-list?
201
+ *
202
+ * Shares `normalizeRequiredAddresses` with `BitcoinWalletService` so the
203
+ * normalization rule (trim, lower-case, drop blanks, all-blank means no
204
+ * constraint) is defined once — two copies would be free to drift apart and
205
+ * silently disagree about whether a given address matches.
206
+ */
207
+ function matchesExpectedAddress(
208
+ address: string,
209
+ requiredAddresses?: readonly string[]
210
+ ): boolean {
211
+ const pinned = normalizeRequiredAddresses(requiredAddresses)
212
+ return !pinned || pinIncludes(pinned, address)
213
+ }
214
+
195
215
  /** Optional collaborators for {@link ConnectionManager}. */
196
216
  export interface ConnectionManagerOptions {
197
217
  /**
@@ -439,7 +459,11 @@ export class ConnectionManager {
439
459
  if (this.bitcoinService.isConnected()) {
440
460
  const uuid = provider.namespaceMetaData?.bip122?.detectedWallet?.uuid
441
461
  if (!uuid || this.bitcoinService.getConnectedWalletUuid() !== uuid) {
442
- await this.bitcoinService.disconnect()
462
+ // LOCAL release only — never `disconnect()`, which now revokes at the
463
+ // wallet. This runs on every connect, so revoking here would drop the
464
+ // user's Bitcoin grant as a side effect of connecting an unrelated
465
+ // wallet (and a rejected revoke would fail that unrelated connect).
466
+ this.bitcoinService.releaseLocalSession()
443
467
  released.push('bip122')
444
468
  }
445
469
  }
@@ -457,7 +481,8 @@ export class ConnectionManager {
457
481
  */
458
482
  async checkExistingConnections(
459
483
  targetNamespace: Namespace,
460
- provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
484
+ provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
485
+ requiredAddresses?: readonly string[]
461
486
  ): Promise<{
462
487
  address: string | null
463
488
  availableAddresses: AvailableAddress[]
@@ -619,17 +644,38 @@ export class ConnectionManager {
619
644
  availableAddresses
620
645
  )
621
646
  } else if (targetNamespace === 'bip122') {
647
+ // A live session only counts as "already connected" when it satisfies the
648
+ // caller's pinned allow-list. Otherwise fall through so the prompting
649
+ // connect below can authorize the account actually asked for — adopting a
650
+ // non-matching live account leaves the caller stuck with an address it
651
+ // already told us is wrong, with no path to change it.
622
652
  const bitcoinAccount = this.bitcoinService.getAccount()
623
- if (bitcoinAccount) {
653
+ if (
654
+ bitcoinAccount &&
655
+ matchesExpectedAddress(bitcoinAccount, requiredAddresses)
656
+ ) {
624
657
  currentAddress = bitcoinAccount
625
- } else {
658
+ } else if (!bitcoinAccount) {
659
+ // Probe the wallet's exposed accounts ONLY when there is no live
660
+ // session. A live account that misses the pin means the session has
661
+ // already moved past whatever the wallet handle reports — and FRAMED,
662
+ // that handle is a one-time snapshot marshaled by `BridgeChild` which
663
+ // proxied connects never update. Consulting it here could "find" the
664
+ // pin in an obsolete snapshot and restore an account the wallet has
665
+ // since revoked, skipping the real connect entirely. A live mismatch
666
+ // therefore falls straight through to `connect()`, which reads the
667
+ // wallet through the proxied feature.
626
668
  const walletUuid =
627
669
  provider.namespaceMetaData?.bip122?.detectedWallet?.uuid
628
670
  if (walletUuid) {
629
671
  const wallet = this.bitcoinService.findWalletByUuid(walletUuid)
630
672
  if (wallet) {
631
- const address =
632
- await this.bitcoinService.checkExistingConnection(wallet)
673
+ // Address-aware, still non-prompting: returns null when pins are
674
+ // set and no ALREADY-AUTHORIZED account matches.
675
+ const address = await this.bitcoinService.checkExistingConnection(
676
+ wallet,
677
+ requiredAddresses
678
+ )
633
679
  if (address) {
634
680
  currentAddress = address
635
681
  this.bitcoinService.setConnectionState(wallet, address)
@@ -1330,10 +1376,15 @@ export class ConnectionManager {
1330
1376
  */
1331
1377
  async connectBitcoin(
1332
1378
  network: Network,
1333
- provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
1379
+ provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
1380
+ requiredAddresses?: readonly string[]
1334
1381
  ): Promise<ConnectorResult> {
1335
1382
  try {
1336
- const connectResult = await this.bitcoinService.connect(network, provider)
1383
+ const connectResult = await this.bitcoinService.connect(
1384
+ network,
1385
+ provider,
1386
+ requiredAddresses
1387
+ )
1337
1388
  this.currentNetworkId = network.id
1338
1389
 
1339
1390
  const availableAddresses: AvailableAddress[] = [