Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 121 additions & 1 deletion packages/wallet-sdk/src/core/transport/popup/Communicator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
});
});
});
21 changes: 21 additions & 0 deletions packages/wallet-sdk/src/core/transport/popup/Communicator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -30,6 +34,7 @@ export class Communicator {
private readonly url: URL;
private readonly openFn?: OpenFn;
private popup: Window | null = null;
private popupClosedPoll: ReturnType<typeof setInterval> | undefined;
private listeners = new Map<(_: MessageEvent) => void, { reject: (_: Error) => void }>();

constructor({ url = CB_KEYS_URL, metadata, preference, openFn }: CommunicatorOptions) {
Expand Down Expand Up @@ -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;
Expand All @@ -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<ConfigMessage>(({ event }) => event === 'PopupUnload')
.then(() => {
this.disconnect();
Expand Down
Loading