Spaces:
Running
Running
Download server/pageChallengeSolver.mjs from Felladrin/MiniSearch: direct link, hf CLI and curl.
- Browser
- Download file 6.89 kB
-
https://huggingface.co/spaces/Felladrin/MiniSearch/resolve/main/server/pageChallengeSolver.mjs
- Command line
-
hf download hf://spaces/Felladrin/MiniSearch/server/pageChallengeSolver.mjs
-
curl -L -o pageChallengeSolver.mjs https://huggingface.co/spaces/Felladrin/MiniSearch/resolve/main/server/pageChallengeSolver.mjs
6.89 kB
| // Solves a JavaScript bot check without a browser. Reads {"url", "html", | |
| // "waitMs"} on stdin, runs the page's scripts offline with no network access, | |
| // and prints the first navigation they trigger as | |
| // {"method", "url", "body"?, "type"?, "cookie"?}, or {} if none comes within | |
| // waitMs. pageContentService calls this for scripted pages that yielded no | |
| // text: a check like Anubis computes its answer in the page's own JavaScript, | |
| // so running that JavaScript is what passes it. | |
| // | |
| // The page's scripts are untrusted. pageChallengeSolver.ts spawns this 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) with an empty environment, and that holds even if a | |
| // script escapes happy-dom's VM. | |
| // | |
| // The permission model does not gate network access on Node 22 to 24, so | |
| // this process keeps two network gates of its own. The stubs below remove | |
| // the transports that carry data: TCP, TLS and UDP sockets and the global | |
| // fetch, whatever a script reaches, escaped or not. What they do not cover | |
| // is DNS: an escaped script can still resolve a name, but there is nothing | |
| // left to connect to. On top of the stubs the interceptor in the browser | |
| // settings answers the page's own requests: the first is served the page's | |
| // own HTML, every later one is a 204 with no body. The follow-up request is | |
| // made by the parent process, after re-validating the navigation reported | |
| // here. Node's permission model is expected to gate the network itself from | |
| // Node 25 on; the stubs stay as the version-independent gate. | |
| import dgram from "node:dgram"; | |
| import fs from "node:fs"; | |
| import net from "node:net"; | |
| import process from "node:process"; | |
| import tls from "node:tls"; | |
| function blockTransport(name) { | |
| return () => { | |
| throw new Error(`pageChallengeSolver has no network: ${name} is blocked`); | |
| }; | |
| } | |
| // Imported by the page's scripts through happy-dom's WebSocket (the `ws` | |
| // package) and by anything that escapes the VM, so the prototypes and the | |
| // module entry points are stubbed alike. | |
| net.Socket.prototype.connect = blockTransport("net.Socket.prototype.connect"); | |
| net.connect = blockTransport("net.connect"); | |
| net.createConnection = blockTransport("net.createConnection"); | |
| tls.connect = blockTransport("tls.connect"); | |
| dgram.createSocket = blockTransport("dgram.createSocket"); | |
| globalThis.fetch = blockTransport("globalThis.fetch"); | |
| // Imported after the stubs so happy-dom and its `ws` dependency only ever | |
| // see the blocked transports. | |
| const { Browser, HTMLFormElement } = await import("happy-dom"); | |
| const page = JSON.parse(fs.readFileSync(0, "utf8")); | |
| // happy-dom reports the form's method attribute as written; the spec | |
| // normalizes it to get, post or dialog, and sites read the normalized value. | |
| Object.defineProperty(HTMLFormElement.prototype, "method", { | |
| get() { | |
| const method = (this.getAttribute("method") || "").toLowerCase(); | |
| return ["post", "dialog"].includes(method) ? method : "get"; | |
| }, | |
| }); | |
| let pageWindow = null; | |
| let navigation = null; | |
| let navigationSeen; | |
| const waitForNavigation = new Promise((resolve) => { | |
| navigationSeen = resolve; | |
| }); | |
| // The parent's kill timer counts from spawn; this process only starts its | |
| // own wait once Node has booted and imported happy-dom, so the wait gives | |
| // back whatever the boot already spent. Without this a navigation near the | |
| // end of the wait would lose the race to the kill instead of being reported. | |
| const bootMs = Math.round(performance.now()); | |
| const waitExpired = new Promise((resolve) => | |
| setTimeout(resolve, Math.max(0, page.waitMs - bootMs)), | |
| ); | |
| const browser = new Browser({ | |
| settings: { | |
| enableJavaScriptEvaluation: true, | |
| // The sandbox is the permission model, not happy-dom's VM. | |
| suppressInsecureJavaScriptEnvironmentWarning: true, | |
| disableJavaScriptFileLoading: true, | |
| disableCSSFileLoading: true, | |
| disableIframePageLoading: true, | |
| disableComputedStyleRendering: true, | |
| errorCapture: "processLevel", | |
| fetch: { | |
| interceptor: { | |
| async beforeAsyncRequest({ request, window }) { | |
| // The first request is the page loading itself: serve it its HTML. | |
| if (pageWindow === null) { | |
| pageWindow = window; | |
| return new window.Response(page.html, { | |
| headers: { "content-type": "text/html; charset=utf-8" }, | |
| }); | |
| } | |
| // happy-dom opens a new window for a navigation, so the first | |
| // request from a window other than the page's is the navigation the | |
| // scripts triggered. Requests the page makes from its own window | |
| // (fetch, beacons) are not navigations and get nothing. | |
| if (navigation === null && window !== pageWindow) { | |
| navigation = { | |
| method: request.method, | |
| url: request.url, | |
| cookie: window.document.cookie || undefined, | |
| }; | |
| if (!["GET", "HEAD"].includes(request.method)) { | |
| navigation.type = | |
| request.headers.get("content-type") ?? undefined; | |
| // happy-dom submits every form as multipart; a browser uses | |
| // urlencoded when all the fields are text, and that is what | |
| // the site behind the check expects. | |
| const fields = navigation.type?.startsWith("multipart/form-data") | |
| ? [...(await request.clone().formData())] | |
| : []; | |
| if ( | |
| fields.length > 0 && | |
| fields.every(([, value]) => typeof value === "string") | |
| ) { | |
| navigation.body = new URLSearchParams(fields).toString(); | |
| navigation.type = "application/x-www-form-urlencoded"; | |
| } else { | |
| navigation.body = await request.text(); | |
| } | |
| } | |
| navigationSeen(); | |
| } | |
| return new window.Response(null, { status: 204 }); | |
| }, | |
| beforeSyncRequest({ window }) { | |
| return new window.Response(null, { status: 204 }); | |
| }, | |
| }, | |
| }, | |
| }, | |
| }); | |
| try { | |
| const tab = browser.newPage(); | |
| await tab.goto(page.url); | |
| // happy-dom does not fire DOMContentLoaded on its own. | |
| tab.mainFrame.document.dispatchEvent( | |
| new tab.mainFrame.window.Event("DOMContentLoaded", { bubbles: true }), | |
| ); | |
| // Wait until the page is idle. If it has started navigating, wait for that | |
| // request instead, but never past the caller's wait. | |
| await Promise.race([waitForNavigation, tab.waitUntilComplete(), waitExpired]); | |
| if (navigation === null && tab.mainFrame.window !== pageWindow) { | |
| await Promise.race([waitForNavigation, waitExpired]); | |
| } | |
| } catch { | |
| // A page whose scripts crash the DOM reports no navigation. | |
| } | |
| process.stdout.write(`${JSON.stringify(navigation ?? {})}\n`); | |
| process.exit(0); | |