From 61a08da52addfdea37b776303ae56a6e63de6538 Mon Sep 17 00:00:00 2001 From: Cody Crozier Date: Mon, 9 Nov 2026 19:52:01 -0700 Subject: [PATCH] fix: reject pending requests when the popup is closed without PopupUnload A popup closed before the wallet page loads never posts PopupLoadedV2 or PopupUnload, so the handshake and any pending request waited forever and their listeners stayed attached. A later popup's PopupLoadedV2 could then resolve the stale waiter. Poll popup.closed while the communicator holds a popup and run the existing disconnect path when it reports closed, so pending requests reject with the same user-rejected error as an unload. The poll is cleared on disconnect. --- .../core/transport/popup/Communicator.test.ts | 122 +++++++++++++++++- .../src/core/transport/popup/Communicator.ts | 21 +++ 2 files changed, 142 insertions(+), 1 deletion(-) diff --git a/packages/wallet-sdk/src/core/transport/popup/Communicator.test.ts b/packages/wallet-sdk/src/core/transport/popup/Communicator.test.ts index e8c79da398..ab359d255b 100644 --- a/packages/wallet-sdk/src/core/transport/popup/Communicator.test.ts +++ b/packages/wallet-sdk/src/core/transport/popup/Communicator.test.ts @@ -5,11 +5,12 @@ import { AppMetadata, Preference } from ':core/provider/interface.js'; import { CB_KEYS_URL, PACKAGE_NAME, PACKAGE_VERSION } from ':core/constants.js'; import { standardErrorCodes } from ':core/error/constants.js'; import { Message, MessageID } from ':core/message/Message.js'; -import { openPopup } from ':util/web.js'; +import { closePopup, openPopup } from ':util/web.js'; import { Communicator } from './Communicator.js'; vi.mock(':util/web', () => ({ openPopup: vi.fn(), + closePopup: vi.fn(), })); // Dispatches a message event to simulate postMessage calls from the popup @@ -291,4 +292,123 @@ describe('Communicator', () => { expect(openPopup).toHaveBeenCalledTimes(2); }); }); + + describe('popup closed without PopupUnload', () => { + const userRejected = { + code: standardErrorCodes.provider.userRejectedRequest, + message: 'Request rejected', + }; + + // Earlier tests leave communicators listening on `window`, so count only this popup + const closePopupCalls = () => + vi.mocked(closePopup).mock.calls.filter(([popup]) => popup === mockPopup).length; + + // Opens the popup and completes the handshake under fake timers + async function loadPopup() { + const loaded = communicator.waitForPopupLoaded(); + await vi.advanceTimersByTimeAsync(0); + dispatchMessageEvent({ ...popupLoadedMessage, origin: urlOrigin }); + await loaded; + } + + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('rejects the handshake when the popup is closed before it loads', async () => { + const loaded = communicator.waitForPopupLoaded(); + const rejection = expect(loaded).rejects.toMatchObject(userRejected); + await vi.advanceTimersByTimeAsync(0); + + (mockPopup as { closed: boolean }).closed = true; + await vi.advanceTimersByTimeAsync(500); + + await rejection; + expect(removeEventListenerSpy).toHaveBeenCalledTimes(addEventListenerSpy.mock.calls.length); + expect(vi.getTimerCount()).toBe(0); + }); + + it('does not let a later popup resolve the closed popup handshake', async () => { + const firstPopup = mockPopup; + const first = communicator.waitForPopupLoaded(); + first.catch(() => {}); + await vi.advanceTimersByTimeAsync(0); + (firstPopup as { closed: boolean }).closed = true; + await vi.advanceTimersByTimeAsync(500); + + // Earlier tests' communicators may also open popups on this event; give them their own + const newPopup = () => ({ + postMessage: vi.fn(), + close: vi.fn(), + closed: false, + focus: vi.fn(), + }); + const secondPopup = newPopup(); + (openPopup as Mock).mockImplementation(newPopup).mockImplementationOnce(() => secondPopup); + await loadPopup(); + + expect(firstPopup.postMessage).not.toHaveBeenCalled(); + expect(secondPopup.postMessage).toHaveBeenCalledTimes(1); + }); + + it('rejects a pending request when the popup is closed after it was posted', async () => { + await loadPopup(); + const response = communicator.postRequestAndWaitForResponse({ + id: 'mock-request-id-1-2', + data: {}, + }); + const rejection = expect(response).rejects.toMatchObject(userRejected); + await vi.advanceTimersByTimeAsync(0); + expect(mockPopup.postMessage).toHaveBeenCalledWith( + { id: 'mock-request-id-1-2', data: {} }, + urlOrigin + ); + + (mockPopup as { closed: boolean }).closed = true; + await vi.advanceTimersByTimeAsync(500); + + await rejection; + expect(vi.getTimerCount()).toBe(0); + }); + + it('keeps waiting while the popup stays open', async () => { + await loadPopup(); + let settled = false; + const response = communicator + .postRequestAndWaitForResponse({ id: 'mock-request-id-1-2', data: {} }) + .finally(() => { + settled = true; + }); + + await vi.advanceTimersByTimeAsync(10_000); + expect(settled).toBe(false); + expect(closePopupCalls()).toBe(0); + + dispatchMessageEvent({ data: { requestId: 'mock-request-id-1-2' }, origin: urlOrigin }); + await expect(response).resolves.toEqual({ requestId: 'mock-request-id-1-2' }); + }); + + it('disconnects once on PopupUnload and stops polling', async () => { + await loadPopup(); + const response = communicator.postRequestAndWaitForResponse({ + id: 'mock-request-id-1-2', + data: {}, + }); + const rejection = expect(response).rejects.toMatchObject(userRejected); + await vi.advanceTimersByTimeAsync(0); + + dispatchMessageEvent({ data: { event: 'PopupUnload' }, origin: urlOrigin }); + await rejection; + expect(closePopupCalls()).toBe(1); + expect(vi.getTimerCount()).toBe(0); + + (mockPopup as { closed: boolean }).closed = true; + await vi.advanceTimersByTimeAsync(1_000); + expect(closePopupCalls()).toBe(1); + }); + }); }); diff --git a/packages/wallet-sdk/src/core/transport/popup/Communicator.ts b/packages/wallet-sdk/src/core/transport/popup/Communicator.ts index a85a071a73..5da3065cc1 100644 --- a/packages/wallet-sdk/src/core/transport/popup/Communicator.ts +++ b/packages/wallet-sdk/src/core/transport/popup/Communicator.ts @@ -11,6 +11,10 @@ import { ConfigMessage, PopupSetupV2Message } from ':core/message/ConfigMessage. import { Message, MessageID } from ':core/message/Message.js'; import type { AppMetadata, Preference } from '../../../storage/schema.js'; +// How often to check whether the popup was closed without posting `PopupUnload`, +// e.g. when the user closes it before the wallet page has loaded. +const POPUP_CLOSED_POLL_INTERVAL_MS = 500; + export type CommunicatorOptions = { url?: string; metadata: AppMetadata; @@ -30,6 +34,7 @@ export class Communicator { private readonly url: URL; private readonly openFn?: OpenFn; private popup: Window | null = null; + private popupClosedPoll: ReturnType | undefined; private listeners = new Map<(_: MessageEvent) => void, { reject: (_: Error) => void }>(); constructor({ url = CB_KEYS_URL, metadata, preference, openFn }: CommunicatorOptions) { @@ -83,6 +88,9 @@ export class Communicator { * Closes the popup, rejects all requests and clears the listeners */ private disconnect = () => { + clearInterval(this.popupClosedPoll); + this.popupClosedPoll = undefined; + // Note: keys popup handles closing itself. this is a fallback. closePopup(this.popup); this.popup = null; @@ -107,6 +115,19 @@ export class Communicator { logPopupSetupStarted(); this.popup = await openPopup(this.url, this.openFn); + // A popup closed before the wallet posts `PopupUnload` sends no message at all, so + // poll `closed` and reject pending requests the same way an unload does. + clearInterval(this.popupClosedPoll); + this.popupClosedPoll = setInterval(() => { + let closed: boolean; + try { + closed = !this.popup || this.popup.closed; + } catch { + return; // unreadable for now; check again on the next tick + } + if (closed) this.disconnect(); + }, POPUP_CLOSED_POLL_INTERVAL_MS); + this.onMessage(({ event }) => event === 'PopupUnload') .then(() => { this.disconnect();