diff --git a/src/browser/client.ts b/src/browser/client.ts index 0a3f7d6..d4719b8 100644 --- a/src/browser/client.ts +++ b/src/browser/client.ts @@ -133,7 +133,14 @@ export class BrowserClient { /** Returns the username and stable t2 account ID for identity binding. */ async getAuthenticatedIdentity(): Promise { try { - return await this.getRedditIdentity(await this.getPage()); + const page = await this.getPage(); + if (!isRedditPage(page.url())) { + await page.goto('https://www.reddit.com', { + waitUntil: 'domcontentloaded', + timeout: 30000, + }); + } + return await this.getRedditIdentity(page); } catch { return null; } @@ -212,3 +219,12 @@ export class BrowserClient { } } + +function isRedditPage(value: string): boolean { + try { + const hostname = new URL(value).hostname.toLowerCase(); + return hostname === 'reddit.com' || hostname.endsWith('.reddit.com'); + } catch { + return false; + } +} diff --git a/tests/browser-client.test.ts b/tests/browser-client.test.ts index 3709023..a5f3923 100644 --- a/tests/browser-client.test.ts +++ b/tests/browser-client.test.ts @@ -42,7 +42,11 @@ describe('BrowserClient', () => { json: async () => ({ kind: 't2', data: { name: 'bot-account', id: 'abc123' } }), }); vi.stubGlobal('fetch', fetchMock); + let pageUrl = 'about:blank'; + const goto = vi.fn(async (url: string) => { pageUrl = url; }); const page = { + url: () => pageUrl, + goto, evaluate: async (pageFunction: () => Promise) => pageFunction(), } as unknown as Page; const context = { pages: () => [page] } as unknown as BrowserContext; @@ -54,6 +58,11 @@ describe('BrowserClient', () => { username: 'bot-account', accountId: 't2_abc123', }); + expect(goto).toHaveBeenCalledTimes(1); + expect(goto).toHaveBeenCalledWith('https://www.reddit.com', { + waitUntil: 'domcontentloaded', + timeout: 30000, + }); expect(fetchMock).toHaveBeenCalledWith( 'https://www.reddit.com/api/me.json', { credentials: 'include' },