Spaces:
Running
Running
File size: 6,485 Bytes
64a58bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | 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<string, unknown>;
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<PageChallengeNavigation | null> {
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);
});
});
}
|