Skip to content

fix(connect-multichain): wipe MWP pairing on full disconnect (MCWP-822) - #348

Merged
joaoloureirop merged 6 commits into
mainfrom
chore/mwp-pairing-on-disconnect
Dec 2, 2026
Merged

joaoloureirop merged 6 commits into
mainfrom
chore/mwp-pairing-on-disconnect

Conversation

@tommasini

@tommasini tommasini commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Explanation

MWPTransport.disconnect()'s full-disconnect branch only called dappClient.disconnect(), relying on the wallet-protocol client's in-memory session to be non-null. dappClient.disconnect() is a no-op when that in-memory session is already null — e.g. after a prior failed resume(), which nulls the session without clearing SessionStore. In that case the pairing (relay channel + ECIES keys) survived in SessionStore.

The next connect() reads that leftover pairing via getActiveSession() (SessionStore.list()[0]), takes the resume path, and tries to resume a pairing the wallet has already revoked. That resume attempt times out, and the dapp is stuck — surviving even a page refresh, since the CAIP-25 session cache and the MWP pairing are two independent persisted stores. Only wiping storage manually recovered.

This reproduced for Fireblocks (@metamask/connect-multichain@1.2.0) on a successful connect → sign → disconnect() → connect().

Fix

  • Added MWPTransport.#clearMwpPairing(): on a full disconnect (no remaining scopes), list and delete every SessionStore entry directly, independent of dappClient's in-memory session state. dappClient.disconnect() is still called afterward for transport/channel cleanup, and its rejection is intentionally left to propagate — this preserves the existing behavior where a failed disconnect surfaces to callers (see MWPTransport.disconnect()'s existing should handle disconnect errors test).
  • Full disconnect now also clears the persisted pending_session_request, matching what connect() already does in its finally, so a later connect() can't pick up a dead handshake URI.
  • Defense in depth: if #resumeSession fails (e.g. the wallet already revoked the pairing out-of-band), that specific pairing is now deleted from SessionStore before rethrowing. This complements fix(connect-multichain): clean up MWP session on connection rejection #180's existing reject-path cleanup on #startSession.
  • Added unit test coverage for disconnect() in mwp/index.test.ts (previously untested): full disconnect wipes the pairing and getActiveSession() resolves undefined afterward, partial disconnect leaves the pairing untouched, and a subsequent connect() takes #startSession rather than resume.

Scope is intentionally limited to @metamask/connect-multichain in this repo — the leftover pairing lives in the dapp-side adapter (localStorage / IndexedDB / AsyncStorage), not in any Mobile wallet-side store, so app/core/SDKConnectV2 in metamask-mobile is unaffected and out of scope here.

image

References

  • Fixes MCWP-822
  • Related to MCWP-823 (status=connected with #transport undefined) and MCWP-821 (stale IndexedDB handle) — same underlying report, not fixed by this change
  • Complements #180 (cleans SessionStore on connect rejection); this PR closes the same gap on the disconnect path
  • Epic: MCWP-769

Checklist

  • I've updated the test suite for new or updated code as appropriate
  • I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate
  • I've communicated my changes to consumers by updating changelogs for packages I've changed, highlighting breaking changes as necessary
  • I've prepared draft pull requests for clients and consumer packages to resolve any breaking changes

Full disconnect() previously only called dappClient.disconnect(), which is
a no-op when dappClient's in-memory session is already null (e.g. after a
prior failed resume()). That left the pairing (relay channel + ECIES keys)
in SessionStore, so a subsequent connect() would resume an already-revoked
pairing via getActiveSession(), time out, and leave the dapp stuck even
after a page refresh.

- Add #clearMwpPairing(): on full disconnect, list+delete every SessionStore
  entry directly (independent of dappClient.session), then still call
  dappClient.disconnect() for transport/channel cleanup. Its rejection is
  intentionally left to propagate so existing disconnect-error behavior is
  unchanged.
- Full disconnect now also clears pending_session_request so a later
  connect() can't pick up a dead handshake URI.
- Defense in depth: if #resumeSession fails, delete that specific pairing
  from SessionStore before rethrowing (complements PR #180's reject-path
  cleanup on #startSession).
- Add disconnect() unit test coverage: full disconnect wipes the pairing
  and getActiveSession() resolves undefined afterward; partial disconnect
  leaves the pairing untouched; a subsequent connect() takes #startSession
  rather than resume.
- Add CHANGELOG entry.

Co-authored-by: Cursor <cursoragent@cursor.com>
@tommasini
tommasini requested a review from a team as a code owner September 10, 2026 23:56
@tommasini
tommasini marked this pull request as draft September 11, 2026 00:03
@tommasini

Copy link
Copy Markdown
Contributor Author

Real validation of the fix (real SessionStore, not mocked)

In addition to the unit tests added in this PR (which mock SessionStore via vi.spyOn), I wrote a throwaway script that exercises MWPTransport against the real, installed @metamask/mobile-wallet-protocol-core SessionStore class (no mocking of the storage layer at all). Only the DappClient is faked, and the fake faithfully reproduces the documented, no-op-when-null behavior of the real BaseClient.disconnect():

// @metamask/mobile-wallet-protocol-core BaseClient (external dependency)
public async disconnect(): Promise<void> {
  if (!this.session) return; // <-- root cause: SessionStore keys survive
  ...
}

Scenario: seed a real pairing in SessionStore, set the fake dappClient.session = null (simulating the exact precondition from the ticket — a prior failed resume() already nulled the in-memory session), then call transport.disconnect() followed by transport.connect(), and observe what actually happens to the persisted pairing and which code path connect() takes.

I ran this scenario against both the pre-fix code (98cb7ee, this PR's parent commit) and the fix in this PR, with the tree restored and git diff clean afterward (no test artifacts were committed).

❌ Before this fix (98cb7ee) — bug reproduces exactly as described in MCWP-822

[setup] Seeded SessionStore with a pairing: pairing-mcwp-822-demo
[setup] SessionStore.list() -> [ 'pairing-mcwp-822-demo' ]

[precondition] dappClient.session = null (simulating a prior failed resume())
[precondition] transport.getActiveSession() -> pairing-mcwp-822-demo

[step] Calling transport.disconnect() ...
[step] dappClient.disconnect() was called 1 time(s)

[RESULT] SessionStore.list() after disconnect() -> [ 'pairing-mcwp-822-demo' ]
[RESULT] transport.getActiveSession() after disconnect() -> { id: 'pairing-mcwp-822-demo', channel: 'demo-channel', ... }
[RESULT] ❌ BUG REPRODUCED -- pairing survived disconnect() despite dappClient.session being null.

[step] Calling transport.connect() again ...
[step] transport.connect() REJECTED: SESSION_NOT_FOUND: wallet has already revoked pairing "pairing-mcwp-822-demo"

[RESULT] dappClient.resume() call count: 1
[RESULT] dappClient.connect() call count: 0
[RESULT] ❌ connect() took the RESUME path against a pairing the wallet already revoked (the stuck/timeout scenario from the ticket).

[final] SessionStore.list() -> [ 'pairing-mcwp-822-demo' ]

disconnect() left the dead pairing in SessionStore, so the very next connect() tried to resume it, got rejected (in real life this eventually times out instead), and the dapp is stuck — exactly the bug reported in the ticket, and it would keep repeating on every subsequent connect() attempt (including after a page refresh, since SessionStore is backed by persistent storage).

✅ After this fix — pairing is wiped, next connect() starts fresh

[setup] Seeded SessionStore with a pairing: pairing-mcwp-822-demo
[setup] SessionStore.list() -> [ 'pairing-mcwp-822-demo' ]

[precondition] dappClient.session = null (simulating a prior failed resume())
[precondition] transport.getActiveSession() -> pairing-mcwp-822-demo

[step] Calling transport.disconnect() ...
[step] dappClient.disconnect() was called 1 time(s)

[RESULT] SessionStore.list() after disconnect() -> []
[RESULT] transport.getActiveSession() after disconnect() -> undefined
[RESULT] ✅ Pairing was wiped -- getActiveSession() correctly resolves undefined.

[step] Calling transport.connect() again ...
[step] transport.connect() resolved successfully.

[RESULT] dappClient.resume() call count: 0
[RESULT] dappClient.connect() call count: 1
[RESULT] ✅ connect() took the START path (#startSession) -- no attempt to resume a dead pairing.

[final] SessionStore.list() -> []

Same precondition, same fake wallet behavior — but now disconnect() unconditionally wipes the pairing from SessionStore (independent of dappClient's in-memory session state), so getActiveSession() correctly returns undefined, and the subsequent connect() goes straight to #startSession instead of retrying a pairing the wallet already revoked. No more stuck/timeout state.

Methodology notes

  • Storage layer (SessionStore) is the real class from the installed @metamask/mobile-wallet-protocol-core dependency — not mocked or spied.
  • Only DappClient is faked, and only to deterministically reproduce the documented disconnect()/resume() behavior from the external package (no real relay/device connection is available in this environment).
  • Verified with git diff that swapping in the pre-fix file and back left the working tree byte-identical to HEAD — this was a temporary, non-committed repro, not a code change.
  • Full permanent test suite (packages/connect-multichain/src/multichain/transports/mwp/index.test.ts, 29 tests) still passes against the restored fixed code.

@tommasini
tommasini marked this pull request as ready for review September 14, 2026 09:26
Comment on lines +467 to +469
if (session.id) {
await this.#deleteMwpSession(session.id);
}

@adonesky1 adonesky1 Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this will force a fresh QR/deeplink on any resume failure, not just a dead pairing. connect() already wipes SessionStore via dappClient.disconnect() when the in-memory session is still set, including the 10s timeout path. The hole is only resume() nulling that session without deleting storage, so move this delete into the dappClient.resume().catch.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The wipe now runs only when dappClient.resume() rejects. Timeouts and #onResumeHandler failures no longer touch SessionStore. Addressed in 6861123. Added a test for the hung-resume timeout.

Comment on lines +813 to +815
} catch (error) {
logger('error clearing MWP pairing from SessionStore', error);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we want to swallow list/delete failures here. If dappClient.session is already null, the disconnect() below is a no-op, so we return success while the pairing is still in SessionStore.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#clearMwpPairing() now propagates list() and delete() failures, and dappClient.disconnect() runs only after the wipe succeeds. Addressed in 2802639. Added a test for a rejected delete().

* @param sessionId - The id of the `SessionStore` entry to delete.
* @returns Nothing
*/
async #deleteMwpSession(sessionId: string): Promise<void> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multiple sessions aren't actually supported on the dapp side. I wonder if it makes sense to just use #clearMwpPairing instead which deletes all sessions just to be safe

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed #deleteMwpSession(). A rejected resume() now clears every stored pairing, since getActiveSession() reads list()[0]. Addressed in 4380b15. Added a test with two pairings.

joaoloureirop and others added 3 commits November 5, 2026 18:14
Move the failed-resume cleanup from the outer race catch into the dappClient.resume() rejection handler, so timeouts no longer delete the pairing and trigger a fresh QR.

Co-authored-by: Cursor <cursoragent@cursor.com>
Use the delete-all pairing cleanup when dappClient.resume() rejects instead of deleting only the resumed session id, since the dapp side does not support multiple pairings.

Co-authored-by: Cursor <cursoragent@cursor.com>
Stop swallowing SessionStore list/delete failures in the MWP pairing wipe so disconnect() rejects instead of reporting success while the pairing remains. Adds tests for propagated delete failures, clearing every pairing on resume rejection, and not clearing on resume timeout.

Co-authored-by: Cursor <cursoragent@cursor.com>
@joaoloureirop

Copy link
Copy Markdown
Contributor

Tested this by hand in the browser playground, connecting over QR code with Ethereum Mainnet and the extension turned off.

On this branch, a QR connect followed by disconnect removes the session: entry and sessions:master-list from mmconnect-kv-store. I also corrupted theirPublicKeyB64 in a stored pairing and reloaded. The resume was rejected, the stored pairing was removed, and the next connect started a new pairing.

For the case in the ticket, I paused disconnect() at if (!this.session) return, set this.session = null, and let it continue. The session: entry was still removed. On main, the same steps leave the entry behind, and the next connect times out, which reproduces the bug.

- Notify listeners of the empty session even if full-disconnect cleanup
  rejects, then rethrow the original error.
- Add a test that the SessionStore wipe survives a dappClient.disconnect()
  rejection, and one for the notification on cleanup failure.
- Document why the double dappClient.disconnect() on a rejected resume is
  harmless.
- Shorten the changelog entry and link it to the PR.

Co-authored-by: Cursor <cursoragent@cursor.com>

@NicolasMassart NicolasMassart left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick fixes. All my comments are addressed. The security-scan failure is a SARIF upload server error, so a re-run should clear it.

@joaoloureirop
joaoloureirop merged commit 50eeecf into main Dec 2, 2026
16 of 18 checks passed
@joaoloureirop
joaoloureirop deleted the chore/mwp-pairing-on-disconnect branch December 2, 2026 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants