import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import puppeteer, { type Browser } from "puppeteer-core"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { ensureBrowser } from "../browser/manager.js"; import { startLoopback } from "./loopback.js"; // A real browser walks the whole trip: start page, a sign-in page on another site, and back. let browser: Browser; const servers: Server[] = []; /** Stands in for the sign-in page: another site that always redirects to `returnTo`. */ async function signInPage(returnTo: () => string): Promise { const server = createServer((_req, res) => res.writeHead(302, { Location: returnTo() }).end()); servers.push(server); await new Promise((done) => server.listen(0, "127.0.0.1", done)); return `http://localhost:${(server.address() as AddressInfo).port}/authorize`; } beforeAll(async () => { const { executablePath } = await ensureBrowser(); browser = await puppeteer.launch({ executablePath, headless: true, args: ["--no-sandbox"] }); }, 120_000); afterAll(async () => { await browser?.close(); for (const server of servers) server.close(); }); describe("auth/loopback in a browser", () => { it("finishes for the browser that opened the start page", async () => { const handle = await startLoopback({ state: "s", timeoutMs: 20_000 }); const start = handle.startUrl( await signInPage(() => `${handle.redirectUri}?code=c0de&state=s`), ); const page = await browser.newPage(); await page.goto(start); await expect(handle.result).resolves.toMatchObject({ code: "c0de" }); expect(await page.content()).toContain("You're connected"); }, 30_000); it("keeps waiting when another browser profile brings the callback", async () => { const handle = await startLoopback({ state: "s", timeoutMs: 20_000 }); const back = `${handle.redirectUri}?code=c0de&state=s`; const start = handle.startUrl(await signInPage(() => back)); const other = await (await browser.createBrowserContext()).newPage(); const refused = await other.goto(back); expect(refused?.status()).toBe(400); await (await browser.newPage()).goto(start); await expect(handle.result).resolves.toMatchObject({ code: "c0de" }); }, 30_000); });