Spaces:
Running
Running
File size: 8,276 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | import { execFile } from "node:child_process";
import net from "node:net";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
import { HARDENING_FLAGS, PERMISSION_FLAG } from "./pageChallengeSolver.ts";
/**
* The solver script runs under Node's permission model, so these tests
* spawn it the way `solvePageChallenge` does, hardening flags included.
* The module's own path resolution is exercised through a nested plain-`node`
* import, because a test runner serves modules over http and the spawner
* deliberately gives up when it cannot find its script on disk.
*/
const REPO = process.cwd();
const SOLVER_SCRIPT = path.join(REPO, "server/pageChallengeSolver.mjs");
const SOLVER_MODULE = path.join(REPO, "server/pageChallengeSolver.ts");
function runSolverScript(page: unknown): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
execFile(
process.execPath,
[
PERMISSION_FLAG,
`--allow-fs-read=${REPO}/node_modules/*,${REPO}/package.json,${SOLVER_SCRIPT}`,
...HARDENING_FLAGS,
"--max-old-space-size=512",
SOLVER_SCRIPT,
],
{ env: {} },
(error, stdout) => {
if (error !== null) return reject(error);
try {
resolve(JSON.parse(stdout) as Record<string, unknown>);
} catch (cause) {
reject(cause);
}
},
).stdin?.end(JSON.stringify(page));
});
}
const CHECK_URL = "https://example.com/check";
const shell = (script: string) =>
`<html><body><script>${script}</script></body></html>`;
describe("pageChallengeSolver script", () => {
it("reports the navigation a challenge page triggers, with the cookie it set", async () => {
const answer = await runSolverScript({
url: CHECK_URL,
html: shell(
`document.cookie = "session=abc123; path=/"; setTimeout(() => { location.href = "/verify?t=1"; }, 50);`,
),
waitMs: 3_000,
});
expect(answer).toMatchObject({
method: "GET",
url: "https://example.com/verify?t=1",
cookie: "session=abc123",
});
});
it("reports a form POST with urlencoded fields", async () => {
const answer = await runSolverScript({
url: CHECK_URL,
html: `<html><body><form id="f" method="POST" action="/answer"><input name="k" value="v"></form><script>document.getElementById("f").submit();</script></body></html>`,
waitMs: 3_000,
});
expect(answer).toMatchObject({
method: "POST",
url: "https://example.com/answer",
body: "k=v",
type: "application/x-www-form-urlencoded",
});
});
it("serves the page's own fetch nothing at all and lets nothing out", async () => {
const html = shell(
`fetch("/api/leak").then((r) => r.text()).then((t) => { location.href = "/len/" + t.length; });`,
);
const answer = await runSolverScript({
url: CHECK_URL,
html,
waitMs: 3_000,
});
// Every request after the page load is answered 204 with no body: the
// fetch read zero bytes from the network, because none was ever made.
expect(answer).toMatchObject({
url: "https://example.com/len/0",
});
});
it("answers every transport a page script reaches with the same 204", async () => {
// The interceptor is one of the solver's two network gates, so every
// transport a page can name has to run through it: async fetch and
// async XHR here, sync XHR through `beforeSyncRequest`.
const html = shell(`
var out = [];
function check() { if (out.length === 2) location.href = "/done?" + out.sort().join("&"); }
fetch("/f").then(function (r) { out.push("f" + r.status); check(); });
var x = new XMLHttpRequest();
x.open("GET", "/x");
x.onload = function () { out.push("x" + x.status); check(); };
x.send();
setTimeout(function () { location.href = "/stuck?" + out.sort().join("&"); }, 1_500);
`);
const answer = await runSolverScript({
url: CHECK_URL,
html,
waitMs: 3_000,
});
expect(answer).toMatchObject({ url: "https://example.com/done?f204&x204" });
});
it("reports nothing for a page that triggers no navigation", async () => {
const answer = await runSolverScript({
url: CHECK_URL,
html: shell("console.log('idle')"),
waitMs: 500,
});
expect(answer).toEqual({});
});
it("reports nothing when the navigation comes after the wait", async () => {
const answer = await runSolverScript({
url: CHECK_URL,
html: shell(`setTimeout(() => { location.href = "/late"; }, 1_500);`),
waitMs: 200,
});
expect(answer).toEqual({});
});
});
/**
* Runs `solvePageChallenge` through a nested plain-`node` import, so the
* spawner sees its script on disk the way the server does.
*/
function runSpawner(html: string, waitMs: number): Promise<unknown> {
const harness = `
const { solvePageChallenge } = await import(${JSON.stringify(pathToFileURL(SOLVER_MODULE).href)});
const navigation = await solvePageChallenge({
url: ${JSON.stringify(CHECK_URL)},
html: ${JSON.stringify(html)},
waitMs: ${waitMs},
});
process.stdout.write(JSON.stringify(navigation ?? null));
`;
return new Promise((resolve, reject) => {
execFile(
process.execPath,
["--input-type=module", "-e", harness],
(error, stdout) => {
if (error !== null) return reject(error);
resolve(JSON.parse(stdout) as unknown);
},
);
});
}
describe("solvePageChallenge", () => {
it("spawns the sandboxed solver and parses its answer", async () => {
const answer = await runSpawner(shell(`location.href = "/ok";`), 3_000);
expect(answer).toMatchObject({
method: "GET",
url: "https://example.com/ok",
});
});
it("treats a solver that dies on a broken page as no navigation", async () => {
// A script that will not compile takes the solver down with it; the
// spawner reads that as a challenge that solved to nothing.
const answer = await runSpawner(shell("location.href = ;"), 1_000);
expect(answer).toBeNull();
});
it("kills a solver whose page never lets the event loop run", async () => {
// `while (true)` blocks the solver's own wait, so only the spawner's
// SIGKILL backstop ends it; without the backstop this test would hang.
expect(await runSpawner(shell("while (true) {}"), 300)).toBeNull();
});
it("gives a page script no way out to the host realm", async () => {
// The known escapes from happy-dom's VM reach the host realm through
// the constructor chain of a host function or a host class; the
// hardening flags make both of those throw. The page reports which way
// it went, so a passing test proves the code ran, not that it timed out.
const answer = await runSpawner(
shell(`
var held = true;
try { if (setTimeout.constructor("return process")()) held = false; } catch (e) {}
try {
if (document.createElement("div").constructor.constructor("return process")()) held = false;
} catch (e) {}
location.href = held ? "/held" : "/escaped";
`),
3_000,
);
expect(answer).toMatchObject({ url: "https://example.com/held" });
});
it("gives a page script no socket to open", async () => {
// happy-dom's WebSocket connects through the `ws` package, which goes
// straight to the network around the interceptor. The solver stubs the
// transports, so nothing may reach this listener.
let hits = 0;
const listener = net.createServer((socket) => {
hits++;
socket.destroy();
});
await new Promise<void>((resolve) =>
listener.listen(0, "127.0.0.1", resolve),
);
const port = (listener.address() as net.AddressInfo).port;
try {
const answer = await runSpawner(
shell(
`try { new WebSocket("ws://127.0.0.1:${port}/"); } catch (e) {} setTimeout(() => { location.href = "/done"; }, 800);`,
),
3_000,
);
expect(answer).toMatchObject({ url: "https://example.com/done" });
expect(hits).toBe(0);
} finally {
listener.close();
}
});
});
|