Spaces:
Running
Running
Download server/pageChallengeSolver.test.ts from Felladrin/MiniSearch: direct link, hf CLI and curl.
- Browser
- Download file 8.28 kB
-
https://huggingface.co/spaces/Felladrin/MiniSearch/resolve/main/server/pageChallengeSolver.test.ts
- Command line
-
hf download hf://spaces/Felladrin/MiniSearch/server/pageChallengeSolver.test.ts
-
curl -L -o pageChallengeSolver.test.ts https://huggingface.co/spaces/Felladrin/MiniSearch/resolve/main/server/pageChallengeSolver.test.ts
8.28 kB
| 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(); | |
| } | |
| }); | |
| }); | |