Spaces:
Running
Running
File size: 6,891 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 | // 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);
|