Files
HiveGrid-Wireframes/hivegrid-cloud/scripts/lighthouse-puppeteer-auth.cjs
T

53 lines
2.2 KiB
JavaScript

/**
* Puppeteer auth script used by Lighthouse-CI to log in before collecting
* audits against authenticated/admin routes. The script is loaded via
* `.lighthouserc.json`'s `puppeteerScript` field; LHCI invokes it with the
* browser instance and the URL it is about to audit.
*
* Auth strategy:
* - For public/marketing routes (no `/app` or `/admin` prefix) we do not
* attempt login; the script is a no-op so audits still run.
* - For `/app/*` and `/admin/*` routes the script POSTs the boilerplate's
* session cookie (provisioned by the staging Lighthouse runner via
* `LIGHTHOUSE_SESSION_COOKIE`) directly into the browser context. This
* mirrors the spec's "auth-via-cookie" strategy and avoids brittle UI
* login flows.
*
* Required env vars (set by the CI workflow):
* - `LIGHTHOUSE_SESSION_COOKIE` — value of the staging session cookie for a
* Lighthouse test user. Minted by the CI workflow before LHCI starts.
* - `LIGHTHOUSE_SESSION_COOKIE_NAME` (optional) — session cookie name.
* Defaults to `RJ_session`.
* - `LIGHTHOUSE_COOKIE_DOMAIN` (optional) — overrides the cookie domain.
* Defaults to the host of the audited URL.
*
* Refs: docs/improvement-plan/10-compliance-polish/lighthouse.md (Step (g)).
*/
/** @type {(browser: import('puppeteer').Browser, ctx: { url: string, options: object }) => Promise<void>} */
module.exports = async (browser, context) => {
const sessionCookie = process.env.LIGHTHOUSE_SESSION_COOKIE;
const sessionCookieName = process.env.LIGHTHOUSE_SESSION_COOKIE_NAME || "RJ_session";
const targetUrl = context && context.url ? context.url : "";
const isAuthenticatedRoute = /\/(app|admin)(\/|$)/.test(new URL(targetUrl).pathname);
if (!isAuthenticatedRoute || !sessionCookie) {
return;
}
const parsed = new URL(targetUrl);
const domain = process.env.LIGHTHOUSE_COOKIE_DOMAIN || parsed.hostname;
// Set the session cookie before LHCI navigates to the URL.
const page = await browser.newPage();
await page.setCookie({
name: sessionCookieName,
value: sessionCookie,
domain,
path: "/",
httpOnly: true,
secure: parsed.protocol === "https:",
});
await page.close();
};