import { spawn } from "node:child_process"; import { dirname } from "node:path"; import { fileURLToPath } from "node:url"; /** * Where the solver script lives, or null when this module was loaded in a * way that hides the file tree from it (a test runner serving modules over * http, say). A solver that cannot find its script solves nothing, which is * the same answer as a page that triggers no navigation. */ function solverPaths(): { script: string; appRoot: string } | null { try { const script = fileURLToPath( new URL("./pageChallengeSolver.mjs", import.meta.url), ); return { script, appRoot: dirname(dirname(script)) }; } catch { return null; } } /** * The solver reserves its DOM up front; a page that grows past this dies with * an out-of-memory instead of eating the container's memory next to the * search server. A dead solver is a solved challenge that found nothing. */ const SOLVER_HEAP_MB = 512; /** Grace between the solver's own wait ending and the kill that replaces it. */ const SOLVER_GRACE_MS = 1_000; /** A navigation answer is a URL, a method, a body and a cookie. Nothing bigger is an answer. */ const MAX_RESULT_BYTES = 64 * 1024; /** * Each solver runs a page's scripts on this process's CPU, and a batch of * reads can ask for one per scripted page. Two at a time keeps a wall that * every result hits from turning the server into a script farm; a read that * finds the solver busy just skips it, the same answer as a page that solves * to nothing. */ const MAX_CONCURRENT_SOLVERS = 2; let runningSolvers = 0; /** Node renamed the permission-model flag in 23; engines allow 22.12. */ export const PERMISSION_FLAG = Number(process.versions.node.split(".")[0]) >= 23 ? "--permission" : "--experimental-permission"; /** * happy-dom's own recommendation for running untrusted page scripts: no * `eval` or `Function` in the host realm, and intrinsics frozen so a script * cannot patch its way out. Page scripts still run: happy-dom compiles them * through `vm`, which these flags do not touch. Exported so the tests spawn * the script under exactly what the server does. */ export const HARDENING_FLAGS = [ "--disallow-code-generation-from-strings", "--frozen-intrinsics", ]; export interface PageChallengeNavigation { /** `GET` or `POST`, as the page's scripts triggered it. */ method: string; url: string; body?: string; type?: string; cookie?: string; } function parseNavigation(stdout: string): PageChallengeNavigation | null { let parsed: unknown; try { parsed = JSON.parse(stdout); } catch { return null; } if (typeof parsed !== "object" || parsed === null) return null; const candidate = parsed as Record; if (typeof candidate["url"] !== "string" || candidate["url"] === "") { return null; } if (typeof candidate["method"] !== "string") return null; const navigation: PageChallengeNavigation = { method: candidate["method"], url: candidate["url"], }; for (const key of ["body", "type", "cookie"] as const) { if (typeof candidate[key] === "string") navigation[key] = candidate[key]; } return navigation; } /** * Runs a bot-check page's scripts offline and returns the navigation they * trigger, or `null` when the page solves to nothing, misbehaves, or outlives * `waitMs`. The caller re-validates and makes the actual request; nothing here * touches the network. * * The page's scripts are untrusted, so they run in a child process under * Node's permission model: no filesystem outside the module tree, no child * processes, no workers, no native addons, no code generation from strings, * frozen intrinsics, and an empty environment, so a script that escapes * happy-dom's VM still finds neither the disk nor the server's secrets. The * permission model does not gate network access on Node 22 to 24, so the * solver script stubs the TCP, TLS and UDP transports and the global fetch * before happy-dom loads, and the interceptor inside it is what answers the * page's own requests. What an escaped script would still have is DNS * lookups, which can name a host but carry nothing to one. */ export function solvePageChallenge({ url, html, waitMs, }: { url: string; html: string; waitMs: number; }): Promise { const paths = solverPaths(); if (paths === null) return Promise.resolve(null); if (runningSolvers >= MAX_CONCURRENT_SOLVERS) return Promise.resolve(null); runningSolvers++; return new Promise((resolve) => { // A spawn that refuses outright is the same answer as a solver that // finds nothing; leaking the slot or throwing into a ladder that runs // outside the read's try would be worse than not solving. const child = (() => { try { return spawn( process.execPath, [ PERMISSION_FLAG, `--allow-fs-read=${paths.appRoot}/node_modules/*,${paths.appRoot}/package.json,${paths.script}`, ...HARDENING_FLAGS, `--max-old-space-size=${SOLVER_HEAP_MB}`, paths.script, ], { stdio: ["pipe", "pipe", "ignore"], env: {} }, ); } catch { return null; } })(); if (child === null) { runningSolvers--; resolve(null); return; } let stdout = ""; let settled = false; const finish = (value: PageChallengeNavigation | null) => { if (settled) return; settled = true; runningSolvers--; clearTimeout(killer); child.kill("SIGKILL"); resolve(value); }; // The solver waits out the page on its own; this is the backstop for one // that hangs past its welcome. const killer = setTimeout( () => child.kill("SIGKILL"), waitMs + SOLVER_GRACE_MS, ); child.stdin.on("error", () => finish(null)); child.stdin.end(JSON.stringify({ url, html, waitMs })); child.stdout.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { stdout += chunk; if (stdout.length > MAX_RESULT_BYTES) { child.kill("SIGKILL"); finish(null); } }); child.on("error", () => finish(null)); child.on("close", (code) => { if (code !== 0 || stdout === "") return finish(null); const navigation = parseNavigation(stdout); // The solver prints {} when the page triggers no navigation. finish(navigation); }); }); }