Skip to content

armgit / axuse

Public Imported from GitHub
0

Accessibility-first browser & computer use for AI agents — one MCP server for every harness (Codex, Claude Code, OpenCode, Antigravity). Instruments the DOM/accessibility tree via CDP instead of screenshot loops: diffed snapshots, stable element refs, trusted input, typed errors. Zero dependencies

Server mode round 2 — SOTA posture: persona coherence, fleet hygiene, source-level webdriver fix

CTOL Team BJ708a1221e7a1
diff --git a/README.md b/README.md
index 3f3c3c4..5eea57d 100644
--- a/README.md
+++ b/README.md
@@ -84,9 +84,11 @@ element refs like `[ref=e7]`. Each action returns only what changed.
| variable | effect |
|---|---|
| `AXUSE_SERVER_MODE` | `auto` (default): on a display-less Linux server, boot a private Xvfb and keep Chrome fully **headed** on it (anti-bot-safe; see [Servers, no desktop](docs/server-mode.md)) |
-| `AXUSE_DISPLAY_SIZE` | virtual display geometry for server mode (default `1920x1080x24`) |
+| `AXUSE_DISPLAY_SIZE` | virtual display geometry for server mode (default `1920x1080x24`; `random` = a stable geometry per machine, so a fleet is not all 1920x1080) |
+| `AXUSE_TIMEZONE` | IANA `TZ` for the Chrome process — `Date`/`Intl` in pages and workers match the egress persona (validated by `doctor`) |
+| `AXUSE_LANG` | `--accept-lang` for Chrome — `navigator.language(s)` and the `Accept-Language` header match the egress persona |
| `AXUSE_NO_SANDBOX=1` | force `--no-sandbox` (auto for root/container server runs) |
-| `AXUSE_NEUTRALIZE_WEBDRIVER=0` | disable the `navigator.webdriver` neutralizer (restores the human-browser value `false`) |
+| `AXUSE_NEUTRALIZE_WEBDRIVER=0` | disable the `navigator.webdriver` posture-fix fallback (the `AutomationControlled` launch flag already fixes it at the source) |
| `AXUSE_HEADLESS=1` | launch the browser without a window — **trusted internal pages only**: challenge/anti-bot pages detect headless first; servers get server mode instead |
| `AXUSE_BROWSER` | path to the browser binary |
| `AXUSE_PROFILE_DIR` | where temporary browser profiles go (default: OS temp; they are deleted on exit) |
@@ -105,11 +107,16 @@ first, so server mode never uses `--headless`: it boots a private Xvfb and
runs Chrome **fully headed** on it — real headed build, no headless
fingerprint (verified live against Turnstile: `ax_solve_captcha` solves on a
server with no desktop, and the slider engine's human-curve drags land
-10/10). Solver plugins that need vision call a multimodal model through any
-OpenAI-compatible API; keys come from env vars or an owner-only secrets
-file. One-time setup, systemd wiring, env reference and scale notes:
-[`docs/server-mode.md`](docs/server-mode.md) — and `node src/cli.js doctor`
-verifies the whole lane (it prints the measured anti-bot posture).
+10/10). Beyond headed-vs-headless, server mode covers **persona
+coherence** (`AXUSE_TIMEZONE`/`AXUSE_LANG` matching the egress persona,
+`AXUSE_DISPLAY_SIZE=random` fleet diversity, `--disable-blink-features=
+AutomationControlled` so `navigator.webdriver` stays `false` at the source)
+and fleet hygiene (zombie-Xvfb sweep). Solver plugins that need vision call
+a multimodal model through any OpenAI-compatible API; keys come from env
+vars or an owner-only secrets file. One-time setup, systemd wiring, env
+reference and scale notes: [`docs/server-mode.md`](docs/server-mode.md) —
+and `node src/cli.js doctor` verifies the whole lane (it prints the measured
+anti-bot posture and persona).
## Benchmark
diff --git a/SKILL.md b/SKILL.md
index b9579ea..89be229 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -64,10 +64,12 @@ loaded package together with its contributed tool names.
**Servers (no desktop):** on a display-less Linux host axuse auto-boots a
private Xvfb and keeps Chrome fully **headed** on it — never pass
`headless: true` for challenge/anti-bot pages (they check headless first).
-The `ax_open` result reports the fact: `display: :N (virtual …)`. Solvers
-work unchanged; vision needs `<PREFIX>_VISION_KEY` (any OpenAI-compatible
-endpoint) or the owner-only `~/.config/axuse/secrets.json`. Full lane:
-`docs/server-mode.md`.
+The `ax_open` result reports the fact: `display: :N (virtual …)`. Persona
+coherence with the egress persona is configured server-side
+(`AXUSE_TIMEZONE`, `AXUSE_LANG`; `navigator.webdriver` stays `false` via the
+`AutomationControlled` launch flag). Solvers work unchanged; vision needs
+`<PREFIX>_VISION_KEY` (any OpenAI-compatible endpoint) or the owner-only
+`~/.config/axuse/secrets.json`. Full lane: `docs/server-mode.md`.
## Error vocabulary (typed — read `code`, `hint`, `retry`)
diff --git a/docs/server-mode.md b/docs/server-mode.md
index d4a095d..155fabb 100644
--- a/docs/server-mode.md
+++ b/docs/server-mode.md
@@ -91,11 +91,14 @@ For one-shot / cron-style runs no service is needed — `axuse solve`,
| variable | effect |
|---|---|
| `AXUSE_SERVER_MODE` | `auto` (default) — boot a private Xvfb when Linux + no live display. `0`/`off` disables it (headed launches then fail typed with guidance). |
-| `AXUSE_DISPLAY_SIZE` | Virtual display geometry, default `1920x1080x24`. |
+| `AXUSE_DISPLAY_SIZE` | Virtual display geometry, default `1920x1080x24`. `random` = fleet lane: one **stable geometry per machine** (hostname+uid hash), spread across the weighted common-consumer list — identical fleet viewports are a cross-account correlation signal. |
+| `AXUSE_TIMEZONE` | IANA zone for the Chrome process (`TZ`): drives `Date`/`Intl` in pages AND workers. Set it to the **egress persona's** zone — a UTC server behind a US residential exit is a classic timezone-mismatch score. Validated by `doctor`. |
+| `AXUSE_LANG` | `--accept-lang` for Chrome (verified live: `--lang` alone does **not** move `navigator.language`): sets `navigator.language`/`languages` **and** the `Accept-Language` header. |
+| `AXUSE_FP_CORES` / `AXUSE_FP_MEMORY` | Opt-in persona caps: a 96-core server's honest `hardwareConcurrency` is a persona mismatch for residential-looking traffic. `AXUSE_FP_CORES=8` overrides `navigator.hardwareConcurrency`; `AXUSE_FP_MEMORY` overrides `navigator.deviceMemory` — only where the platform exposes the API (never invents it). Honest hardware stays the default. |
| `AXUSE_NO_SANDBOX` | `1` forces `--no-sandbox`. Auto-applied anyway when running as root (containers) — Chrome refuses root otherwise. |
| `AXUSE_BROWSER` | Path to the browser binary (as on any host). |
| `AXUSE_PROFILE_DIR` | Where browser profiles go (defaults to the OS temp dir). |
-| `AXUSE_NEUTRALIZE_WEBDRIVER` | `0` disables the `navigator.webdriver` neutralizer (see below). Default: on. |
+| `AXUSE_NEUTRALIZE_WEBDRIVER` | `0` disables the `navigator.webdriver` posture fix (see below). Default: on. |
| `AXUSE_HEADLESS` | **Do not set on servers with challenge traffic.** Forces `--headless` for every launch — the exact signal anti-bot systems look for. It stays available for trusted internal pages. |
Every knob is checked by `node src/cli.js doctor` — run it first, it tells
@@ -139,6 +142,34 @@ chmod 600 ~/.config/axuse/secrets.json
`AXUSE_SECRETS_FILE` overrides the path. A file the group/world can read is
refused (fix: `chmod 600`). Typed failure messages name the exact options.
+## Persona coherence (the parts headless-vs-headed does not cover)
+
+Being headed removes the *headless* class of signals. A second class is
+**persona coherence**: the browser's persona must match the egress persona
+(the IP it leaves through). Servers fail this class by default — a UTC
+clock behind a US residential exit, `en-US` behind a German IP, 96 cores in
+a "consumer" session, a fleet where every account shows the exact same
+1920x1080 canvas hash:
+
+```bash
+AXUSE_TIMEZONE=America/New_York # Date/Intl in pages AND workers (TZ)
+AXUSE_LANG=en-GB # navigator.language(s) + Accept-Language
+AXUSE_DISPLAY_SIZE=random # stable geometry per machine, fleet spread
+AXUSE_FP_CORES=8 # optional persona cap for big servers
+AXUSE_FP_MEMORY=8 # optional; only where the API exists
+```
+
+`--disable-blink-features=AutomationControlled` is passed on every launch
+(verified live on Chrome 151): with remote debugging active, Chrome reports
+`navigator.webdriver === true` in **every context** — main frames and
+cross-origin iframes — a fingerprint the *harness itself* creates, present
+on no human-driven Chrome. The flag turns it off **at the source**; a
+pre-document script is the fallback for builds that ignore the flag
+(`AXUSE_NEUTRALIZE_WEBDRIVER=0` opts out of the fallback).
+
+Everything is measured and printed by `doctor` (posture + persona lines in
+the smoke test), and asserted by `test/server-mode.test.js`.
+
## Scaling out (massive operations)
- **One private Xvfb per axuse process** (display numbers are picked away
@@ -156,17 +187,31 @@ refused (fix: `chmod 600`). Typed failure messages name the exact options.
`doctor` reports both.
- **Cleanup**: the Xvfb is a child of the axuse process — normal exits and
process-group kills reap it; under systemd use `KillMode=control-group`.
+ A `kill -9`ed harness can still leak an orphaned Xvfb; server mode sweeps
+ those at the next boot (only processes matching axuse's exact Xvfb launch
+ signature whose parent is gone — verified by pattern tests, never a
+ foreign X server). `doctor` reports them without killing.
## What is deliberately NOT done
- **No headless for challenge pages.** Ever. That is the whole point.
- **No DOM tampering with challenge logic.** The only page-level patch is
- the `navigator.webdriver` neutralizer: modern Chrome sets it to `true`
+ the `navigator.webdriver` posture fix, applied at the source via a launch
+ flag (a pre-document script as fallback): modern Chrome sets it to `true`
merely because a DevTools client is attached — a fingerprint of *our own
plumbing*, present on no human-driven Chrome. axuse restores the exact
- value a human browser reports (`false`), before any page script runs.
- It does not fake, answer or shortcut any challenge — solvers still click
- real widgets with trusted input. Opt out: `AXUSE_NEUTRALIZE_WEBDRIVER=0`.
+ value a human browser reports (`false`), in every frame. It does not
+ fake, answer or shortcut any challenge — solvers still click real
+ widgets with trusted input. Opt out: `AXUSE_NEUTRALIZE_WEBDRIVER=0`.
+- **No invented hardware.** The WebGL renderer string stays the honest
+ one (SwiftShader/ANGLE software — what every GPU-less Linux desktop
+ reports too); `hardwareConcurrency`/`deviceMemory` stay honest unless the
+ operator opts into the persona caps. The deviceMemory override only
+ applies on platforms that expose the API — never inventing an API surface
+ the platform's real Chrome lacks.
+- **No egress-traffic tricks.** JA4/TLS and HTTP/2 fingerprinting live
+ below the page layer — the customer's proxy vendor's product (documented
+ integration point: bring your own egress).
- **No fabricated results.** Solvers report `solved: false` honestly when
a page hard-blocks; `doctor` and tests state measured numbers.
@@ -176,10 +221,14 @@ refused (fix: `chmod 600`). Typed failure messages name the exact options.
node src/cli.js doctor
# server mode: ready — no live X display; headed Chrome will auto-boot a
# private Xvfb (1920x1080x24, NOT headless — anti-bot-safe; …)
+# persona: timezone not overridden (Chrome uses this host's TZ, currently …)
+# — set AXUSE_TIMEZONE to the egress persona's zone when routing through a proxy
+# stale Xvfb zombies: N leaked … (only printed when found; swept at next boot)
# fonts: … (only printed when fonts are missing)
# smoke test: server mode — booting a virtual display, launching HEADED Chrome…
-# server-mode facts: display :762 (virtual) · UA headed (no Headless substring)
-# · navigator.webdriver false · viewport 1919x992 · WebGL present (SwiftShader)
+# server-mode facts: display :895 (virtual) · UA headed (no Headless substring)
+# · navigator.webdriver false · viewport 1919x992 · WebGL present (ANGLE (Google, Vulkan … SwiftShader))
+# server-mode persona: tz Europe/Vienna · language en-US · cores 16 · deviceMemory undefined
# server-mode anti-bot posture: OK — indistinguishable headed build
node --test test/server-mode.test.js # the same assertions, in CI and locally
diff --git a/src/cli.js b/src/cli.js
index 51e1844..3b42d1a 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -332,7 +332,7 @@ async function doctor() {
} else {
serverModeReady = true;
const geo = vd.displayGeometry();
- out(`server mode: ready — no live X display; headed Chrome will auto-boot a private Xvfb (${geo.w}x${geo.h}x${geo.d}, NOT headless — anti-bot-safe; AXUSE_DISPLAY_SIZE to change, AXUSE_SERVER_MODE=0 to disable)`);
+ out(`server mode: ready — no live X display; headed Chrome will auto-boot a private Xvfb (${geo.w}x${geo.h}x${geo.d}, NOT headless — anti-bot-safe; AXUSE_DISPLAY_SIZE to change — 'random' picks a stable geometry per machine so a fleet is not all 1920x1080; AXUSE_SERVER_MODE=0 to disable)`);
}
serverModeActive = vd.virtualDisplayStatus().active;
const fonts = vd.fontHint(vd.fontProbe());
@@ -343,6 +343,24 @@ async function doctor() {
if (/^(1|true)$/i.test(process.env.AXUSE_HEADLESS ?? "")) {
out("AXUSE_HEADLESS=1 is set: EVERY launch runs --headless and challenge/anti-bot pages WILL detect it — unset it on servers (server mode keeps Chrome headed for free)");
}
+ // Persona coherence: the browser persona must match the egress persona
+ // (timezone/locale mismatches vs the exit IP are classic scores).
+ if (process.env.AXUSE_TIMEZONE) {
+ const ok = vd.validTimezone(process.env.AXUSE_TIMEZONE);
+ out(`AXUSE_TIMEZONE=${process.env.AXUSE_TIMEZONE}: ${ok ? "valid — Chrome runs with this TZ (Date/Intl match the egress persona)" : `INVALID (not an IANA zone Chrome accepts) — fix it or unset it; Intl rejects it`}`);
+ } else {
+ out(`persona: timezone not overridden (Chrome uses this host's TZ, currently ${new Intl.DateTimeFormat().resolvedOptions().timeZone}) — set AXUSE_TIMEZONE to the egress persona's zone when routing through a proxy`);
+ }
+ if (process.env.AXUSE_LANG) {
+ out(`AXUSE_LANG=${process.env.AXUSE_LANG}: drives --lang (navigator.language(s) + Accept-Language)`);
+ }
+ if (process.env.AXUSE_FP_CORES || process.env.AXUSE_FP_MEMORY) {
+ out(`persona overrides active: hardwareConcurrency=${process.env.AXUSE_FP_CORES ?? "(honest)"} · deviceMemory=${process.env.AXUSE_FP_MEMORY ?? "(honest)"} — a big server's honest cores are a persona mismatch for residential-looking traffic`);
+ }
+ const zombies = vd.sweepStaleXvfb({ kill: () => {} });
+ if (zombies.length) {
+ out(`stale Xvfb zombies: ${zombies.length} leaked axuse Xvfb process(es) (${zombies.map((z) => z.display).join(", ")}) — SIGKILLed harness processes; they are swept automatically at the next server-mode boot`);
+ }
}
if (process.platform === "win32" || process.platform === "darwin") {
if (process.platform === "darwin" && !/^(1|true)$/i.test(process.env.AXUSE_ENABLE_MACOS_CUA ?? "")) {
@@ -443,9 +461,19 @@ async function doctor() {
const obs = r.observation;
if (useServerMode) {
const ua = JSON.parse((await c.execute("evaluate", { expression: "navigator.userAgent" })).value ?? '""');
- const fp = JSON.parse((await c.execute("evaluate", { expression: "({webdriver: navigator.webdriver, w: innerWidth, h: innerHeight, webgl: !!document.createElement('canvas').getContext('webgl')})" })).value ?? "{}");
+ const fp = JSON.parse((await c.execute("evaluate", {
+ expression: `(() => {
+ const g = document.createElement('canvas').getContext('webgl');
+ const dbg = g && g.getExtension('WEBGL_debug_renderer_info');
+ return { webdriver: navigator.webdriver, w: innerWidth, h: innerHeight, webgl: !!g,
+ renderer: dbg ? g.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : null,
+ tz: Intl.DateTimeFormat().resolvedOptions().timeZone, lang: navigator.language,
+ cores: navigator.hardwareConcurrency, mem: navigator.deviceMemory };
+ })()`,
+ })).value ?? "{}");
const antiBotOk = !/headless/i.test(String(ua)) && fp.webdriver === false && fp.w >= 1200;
- out(`server-mode facts: display ${r.display?.id} (virtual) · UA ${/headless/i.test(String(ua)) ? "CONTAINS Headless (BAD)" : "headed (no Headless substring)"} · navigator.webdriver ${fp.webdriver} · viewport ${fp.w}x${fp.h} · WebGL ${fp.webgl ? "present (SwiftShader)" : "absent"}`);
+ out(`server-mode facts: display ${r.display?.id} (virtual) · UA ${/headless/i.test(String(ua)) ? "CONTAINS Headless (BAD)" : "headed (no Headless substring)"} · navigator.webdriver ${fp.webdriver} · viewport ${fp.w}x${fp.h} · WebGL ${fp.webgl ? `present (${String(fp.renderer).slice(0, 40)})` : "absent"}`);
+ out(`server-mode persona: tz ${fp.tz} · language ${fp.lang} · cores ${fp.cores} · deviceMemory ${fp.mem}${process.env.AXUSE_TIMEZONE ? " (AXUSE_TIMEZONE set)" : ""}`);
out(`server-mode anti-bot posture: ${antiBotOk && fp.webgl ? "OK — indistinguishable headed build" : "CHECK the facts above"}`);
}
const click = await c.execute("click", { target: { ref: "e1" }, settle_ms: 100 });
diff --git a/src/core/cdp.js b/src/core/cdp.js
index e90e3ec..153225c 100644
--- a/src/core/cdp.js
+++ b/src/core/cdp.js
@@ -17,6 +17,42 @@ import { ensureVirtualDisplay, needsNoSandbox, serverModePlan, virtualDisplaySta
const SEND_TIMEOUT_MS = 30_000;
+/** The pre-document posture script: restores values a human-driven Chrome
+ * reports but a CDP-driven one does not. `--disable-blink-features=
+ * AutomationControlled` already fixes navigator.webdriver at the SOURCE
+ * (all contexts — main frames, cross-origin iframes); this script is the
+ * belt-and-suspenders fallback for builds where the flag is not honored.
+ * Optional persona overrides (AXUSE_FP_CORES / AXUSE_FP_MEMORY): a
+ * 96-core server's honest hardwareConcurrency is a persona mismatch for a
+ * residential-looking session — the operator may cap it. Opt-in, honest
+ * hardware stays the default. Exported for tests. */
+export function postureScript(env = process.env) {
+ const parts = [
+ "try { delete navigator.webdriver; } catch {}",
+ "Object.defineProperty(Navigator.prototype, 'webdriver', { get: () => false, configurable: true });",
+ ];
+ const cores = Number(env.AXUSE_FP_CORES);
+ if (Number.isFinite(cores) && cores > 0 && Number.isInteger(cores)) {
+ parts.push(
+ `try { Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => ${cores}, configurable: true }); } catch {}`,
+ `try { Object.defineProperty(Navigator.prototype, 'hardwareConcurrency', { get: () => ${cores}, configurable: true }); } catch {}`,
+ );
+ }
+ const mem = Number(env.AXUSE_FP_MEMORY);
+ if (Number.isFinite(mem) && mem > 0) {
+ // deviceMemory is Chrome-reported in the 0.25/0.5/1/2/4/8 buckets — and
+ // only on platforms that expose the API at all (undefined on this very
+ // Linux build). Overriding only where it EXISTS keeps the platform
+ // honest: creating it on a platform that lacks it would be a stronger
+ // deviation than the value it replaces.
+ const bucket = [0.25, 0.5, 1, 2, 4, 8].reduce((a, b) => (mem >= b ? b : a), 0.25);
+ parts.push(
+ `if ('deviceMemory' in navigator) { try { Object.defineProperty(navigator, 'deviceMemory', { get: () => ${bucket}, configurable: true }); } catch {} }`,
+ );
+ }
+ return parts.join("\n");
+}
+
/** Chromium keeps its discardable/shared-memory segment in /dev/shm (tmpfs).
* When that mount is full or missing, the browser aborts during startup —
* on Linux with a bare "Browser exited during startup (code null)" and one
@@ -343,6 +379,19 @@ export class BrowserHandle {
"--remote-allow-origins=*", // modern Chrome rejects unknown ws Origins
];
if (headless) args.push("--headless");
+ // Source-level posture fix (verified live, Chrome 151): with remote
+ // debugging active, Chrome otherwise reports navigator.webdriver ===
+ // true in EVERY context (main frames, cross-origin iframes) — a
+ // fingerprint our own plumbing creates, present on no human-driven
+ // Chrome. This flag turns it off at the source; the per-document script
+ // in attachTab is the fallback for builds that ignore the flag.
+ args.push("--disable-blink-features=AutomationControlled");
+ // Persona coherence: --accept-lang drives navigator.language AND
+ // navigator.languages AND the Accept-Language header (verified live:
+ // --lang alone does NOT — Chrome persists the OS-derived preference).
+ if (process.env.AXUSE_LANG && /^[\w,-]{2,32}$/.test(process.env.AXUSE_LANG)) {
+ args.push(`--accept-lang=${process.env.AXUSE_LANG}`);
+ }
const vd = virtualDisplayStatus();
if (vd.active) {
// No monitor is attached to a virtual display: give Chrome a real
@@ -362,7 +411,13 @@ export class BrowserHandle {
args.push("--disable-dev-shm-usage");
}
args.push(...extraArgs);
- const proc = spawn(exe, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: false });
+ // Persona coherence (opt-in): TZ drives Date/Intl in the page AND in
+ // workers — set it on the child environment so it matches the egress
+ // persona (a UTC server behind a US residential exit is a classic
+ // timezone-mismatch score).
+ const childEnv = { ...process.env };
+ if (process.env.AXUSE_TIMEZONE) childEnv.TZ = process.env.AXUSE_TIMEZONE;
+ const proc = spawn(exe, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: false, env: childEnv });
let wsUrl;
try {
wsUrl = await new Promise((resolve, reject) => {
@@ -466,19 +521,15 @@ export class BrowserHandle {
await this.conn.send("Page.enable", {}, sessionId);
await this.conn.send("Runtime.enable", {}, sessionId);
await this.conn.send("Log.enable", {}, sessionId);
- // Fingerprint neutralizer (NOT challenge tampering): modern Chrome sets
- // navigator.webdriver=true merely because a DevTools client exists —
- // a fingerprint OUR OWN plumbing creates, present on no human-driven
- // Chrome. This runs before any page script on every new document and
- // restores the exact value a human-driven browser reports (false).
- // It does not fake, answer or shortcut any challenge — solvers still
- // click real widgets with trusted input. Opt out: AXUSE_NEUTRALIZE_WEBDRIVER=0.
+ // Posture script (NOT challenge tampering): the AutomationControlled
+ // launch flag already restores navigator.webdriver at the source; this
+ // pre-document script is the fallback for builds that ignore the flag,
+ // plus the optional persona overrides (AXUSE_FP_CORES / AXUSE_FP_MEMORY).
+ // It never fakes, answers or shortcuts a challenge — solvers still click
+ // real widgets with trusted input. Opt out: AXUSE_NEUTRALIZE_WEBDRIVER=0.
if (!/^(0|false|off|no)$/i.test(process.env.AXUSE_NEUTRALIZE_WEBDRIVER ?? "")) {
try {
- await this.conn.send("Page.addScriptToEvaluateOnNewDocument", {
- source: "try { delete navigator.webdriver; } catch {} "
- + "Object.defineProperty(Navigator.prototype, 'webdriver', { get: () => false, configurable: true });",
- }, sessionId);
+ await this.conn.send("Page.addScriptToEvaluateOnNewDocument", { source: postureScript() }, sessionId);
} catch { /* older builds: skip, never fail the attach */ }
}
// File inputs: intercept the native chooser (it would block forever) and
diff --git a/src/core/vdisplay.js b/src/core/vdisplay.js
index a2e42df..cb6099f 100644
--- a/src/core/vdisplay.js
+++ b/src/core/vdisplay.js
@@ -39,7 +39,8 @@
* anti-bot signal you WANT to keep)
*/
import { spawn, spawnSync } from "node:child_process";
-import { accessSync, existsSync, readdirSync } from "node:fs";
+import { accessSync, existsSync, readdirSync, readFileSync } from "node:fs";
+import { hostname } from "node:os";
import { join } from "node:path";
import { AxError, Codes } from "./errors.js";
@@ -48,6 +49,41 @@ const X11_SOCKET_DIR = "/tmp/.X11-unix";
const XVFB_BOOT_TIMEOUT_MS = 5000;
const XVFB_ATTEMPTS = 3;
+/** Weighted common-consumer resolutions for fleet diversity ("random"): a
+ * fleet of identical 1920x1080 viewports is a cross-account correlation
+ * signal; real desktops spread across these. */
+export const COMMON_DISPLAY_SIZES = [
+ { w: 1920, h: 1080, d: 24, weight: 45 },
+ { w: 1366, h: 768, d: 24, weight: 25 },
+ { w: 1600, h: 900, d: 24, weight: 10 },
+ { w: 1680, h: 1050, d: 24, weight: 8 },
+ { w: 1440, h: 900, d: 24, weight: 7 },
+ { w: 2560, h: 1440, d: 24, weight: 5 },
+];
+
+/** Stable 31-bit hash (FNV-1a) — machine identity → one fleet geometry. */
+function stableHash(s) {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h >>> 0;
+}
+
+/** Pick the fleet geometry for this machine: deterministic per machine
+ * (hostname + uid), so one machine keeps one persona across boots while a
+ * fleet spreads across the weighted list. */
+export function pickFleetDisplaySize(seed = `${hostname() ?? ""}:${typeof process.getuid === "function" ? process.getuid() : ""}`) {
+ const total = COMMON_DISPLAY_SIZES.reduce((a, s) => a + s.weight, 0);
+ let slot = stableHash(String(seed)) % total;
+ for (const s of COMMON_DISPLAY_SIZES) {
+ if (slot < s.weight) return { w: s.w, h: s.h, d: s.d };
+ slot -= s.weight;
+ }
+ return { w: 1920, h: 1080, d: 24 };
+}
+
/* ------------------------------------------------------------------ config */
/** AXUSE_SERVER_MODE: unset/"auto"/"1" → enabled; "0"/"off"/"false"/"no" → off. */
@@ -66,11 +102,27 @@ export function parseDisplaySize(s) {
return { w, h, d };
}
-/** The effective virtual-display geometry (AXUSE_DISPLAY_SIZE, validated). */
+/** The effective virtual-display geometry (AXUSE_DISPLAY_SIZE, validated).
+ * "random" = the fleet lane: one stable geometry per machine, spread
+ * across the weighted common-consumer list (identical fleet viewports are
+ * a cross-account correlation signal). */
export function displayGeometry(env = process.env) {
+ const raw = String(env.AXUSE_DISPLAY_SIZE ?? "").trim();
+ if (/^random$/i.test(raw)) return pickFleetDisplaySize();
return parseDisplaySize(env.AXUSE_DISPLAY_SIZE) ?? parseDisplaySize(DEFAULT_DISPLAY_SIZE);
}
+/** Validate an IANA timezone the way the browser will resolve it (Intl —
+ * the same engine Chrome uses for Date/Intl). null when invalid. */
+export function validTimezone(tz) {
+ try {
+ const resolved = new Intl.DateTimeFormat("en-US", { timeZone: String(tz) }).resolvedOptions().timeZone;
+ return resolved ? tz : null;
+ } catch {
+ return null;
+ }
+}
+
/* ------------------------------------------------------- display discovery */
/** DISPLAY ":1", "localhost:10.0", "unix:0" → display number, or null. */
@@ -193,6 +245,49 @@ export function __resetVirtualDisplay() {
active = null;
}
+/* --------------------------------------------------------- zombie hygiene */
+
+/** Read one /proc/<pid> entry: { pid, ppid, argv } or null. Injectable for tests. */
+function procEntry(pid, { readFile = (p) => readFileSync(p, "utf8") } = {}) {
+ const stat = (() => { try { return readFile(`/proc/${pid}/stat`); } catch { return null; } })();
+ const cmd = (() => { try { return readFile(`/proc/${pid}/cmdline`); } catch { return null; } })();
+ if (!stat || !cmd) return null;
+ // ppid is stat field 4 — after comm, which may contain spaces/parens.
+ const after = stat.slice(stat.lastIndexOf(")") + 2).trim().split(/\s+/);
+ return { pid, ppid: Number(after[1]), argv: cmd.split("\0").filter(Boolean) };
+}
+
+/** Does one /proc entry look like an axuse-spawned Xvfb (our exact launch
+ * signature) whose parent is gone (reparented to init — a leaked zombie
+ * from a SIGKILLed harness)? Conservative by construction: the full arg
+ * set must match and the parent must be dead. */
+export function isStaleAxuseXvfb(entry) {
+ if (!entry || typeof entry.pid !== "number") return false;
+ const a = entry.argv ?? [];
+ if (!/Xvfb$/.test(a[0] ?? "")) return false;
+ if (!/^:\d+$/.test(a[1] ?? "")) return false;
+ for (const need of ["-screen", "0", "-ac", "-nolisten", "tcp", "-noreset"]) {
+ if (!a.includes(need)) return false;
+ }
+ return entry.ppid === 1;
+}
+
+/** Sweep leaked axuse Xvfb zombies (SIGKILLed harness processes leave an
+ * orphaned X server behind: ~10 MB each and a display number gone, which
+ * matters at fleet scale). Only OUR exact-signature orphans die; a display
+ * still owned by a live process has a live parent, not ppid 1. */
+export function sweepStaleXvfb({ listDir = readdirSync, readFile, kill = (pid) => process.kill(pid, "SIGTERM") } = {}) {
+ const swept = [];
+ let pids;
+ try { pids = listDir("/proc").filter((n) => /^\d+$/.test(n)); } catch { return swept; }
+ for (const pid of pids) {
+ const entry = procEntry(Number(pid), { readFile });
+ if (!isStaleAxuseXvfb(entry)) continue;
+ try { kill(entry.pid); swept.push({ pid: entry.pid, display: entry.argv[1] }); } catch {}
+ }
+ return swept;
+}
+
function sleep(ms) { return new Promise((ok) => setTimeout(ok, ms)); }
/** Wait for Xvfb's X socket (its readiness signal) or its early death. */
@@ -226,6 +321,11 @@ export async function ensureVirtualDisplay({ force = false } = {}) {
throw new AxError(Codes.LAUNCH_FAILED, `Cannot boot server mode: Xvfb was not found. ${plan.hint ?? ""}`, { retry: "never" });
}
const geo = displayGeometry();
+ // Zombie hygiene first: a SIGKILLed harness leaves an orphaned Xvfb
+ // (~10 MB, one display number gone each time — fleet scale poison).
+ // Freed displays then rejoin the pickable pool.
+ const swept = sweepStaleXvfb();
+ if (swept.length) await sleep(400);
const taken = takenDisplayNumbers();
for (let attempt = 1; attempt <= XVFB_ATTEMPTS; attempt++) {
const n = pickDisplayNumber({ taken });
@@ -253,6 +353,7 @@ export async function ensureVirtualDisplay({ force = false } = {}) {
active = {
display, width: geo.w, height: geo.h, depth: geo.d,
pid: proc.pid, virtual: true, startedAt: Date.now(), proc,
+ ...(swept.length ? { swept } : {}),
};
// Cleanup: normal exits kill our Xvfb. Signal deaths are covered by
// process-group kills (the norm for harness/CLI teardown) and by
diff --git a/test/server-mode.test.js b/test/server-mode.test.js
index db72d44..f290b77 100644
--- a/test/server-mode.test.js
+++ b/test/server-mode.test.js
@@ -21,8 +21,10 @@ import {
parseDisplaySize, displayNumber, displayUsable, displayGeometry,
serverModeEnabled, serverModePlan, pickDisplayNumber, takenDisplayNumbers,
needsNoSandbox, virtualDisplayStatus, __resetVirtualDisplay,
+ COMMON_DISPLAY_SIZES, pickFleetDisplaySize, validTimezone,
+ isStaleAxuseXvfb, sweepStaleXvfb,
} from "../src/core/vdisplay.js";
-import { locateBrowser } from "../src/core/cdp.js";
+import { locateBrowser, postureScript } from "../src/core/cdp.js";
import { Controller } from "../src/core/controller.js";
/* ------------------------------------------------------------ unit lane */
@@ -104,6 +106,81 @@ test("server mode: AXUSE_SERVER_MODE / no-sandbox env parsing", () => {
assert.equal(needsNoSandbox({ uid: 1000, env: {} }).add, false);
});
+test("server mode: fleet display diversity — 'random' is stable per machine and stays in the common list", () => {
+ // Deterministic per machine (seed) — one persona per machine across boots.
+ const a = pickFleetDisplaySize("host-a:1000");
+ const b = pickFleetDisplaySize("host-a:1000");
+ assert.deepEqual(a, b, "same machine → same geometry");
+ assert.ok(COMMON_DISPLAY_SIZES.some((s) => s.w === a.w && s.h === a.h), "picked from the weighted common list");
+ // A fleet spreads: 24 machines cover ≥3 distinct geometries.
+ const distinct = new Set(Array.from({ length: 24 }, (_, i) => {
+ const g = pickFleetDisplaySize(`host-${i}:1000`);
+ return `${g.w}x${g.h}`;
+ }));
+ assert.ok(distinct.size >= 3, `24 machines spread across only ${distinct.size} geometries`);
+ // displayGeometry honors 'random' (case-insensitive) and rejects garbage.
+ assert.ok(COMMON_DISPLAY_SIZES.some((s) => {
+ const g = displayGeometry({ AXUSE_DISPLAY_SIZE: "RANDOM" });
+ return s.w === g.w && s.h === g.h;
+ }));
+ assert.deepEqual(displayGeometry({ AXUSE_DISPLAY_SIZE: "nonsense" }), { w: 1920, h: 1080, d: 24 });
+});
+
+test("server mode: IANA timezone validation (the same engine Chrome uses)", () => {
+ assert.equal(validTimezone("Europe/Amsterdam"), "Europe/Amsterdam");
+ assert.equal(validTimezone("America/New_York"), "America/New_York");
+ assert.equal(validTimezone("Not/AZone"), null);
+ assert.equal(validTimezone(""), null);
+ assert.equal(validTimezone(null), null);
+});
+
+test("server mode: posture script — webdriver fallback plus opt-in persona overrides", () => {
+ const base = postureScript({});
+ assert.match(base, /navigator\.webdriver/);
+ assert.doesNotMatch(base, /hardwareConcurrency/, "honest cores stay the default");
+ assert.doesNotMatch(base, /deviceMemory/, "honest memory stays the default");
+ const cores = postureScript({ AXUSE_FP_CORES: "8" });
+ assert.match(cores, /hardwareConcurrency[^]+=> 8/);
+ assert.doesNotMatch(cores, /deviceMemory/);
+ // deviceMemory lands in Chrome's 0.25/0.5/1/2/4/8 buckets (16 GB input → 8).
+ const mem = postureScript({ AXUSE_FP_MEMORY: "3" });
+ assert.match(mem, /'deviceMemory' in navigator[^]+=> 2/);
+ // Garbage values are ignored, never a broken page.
+ const junk = postureScript({ AXUSE_FP_CORES: "zero", AXUSE_FP_MEMORY: "-1" });
+ assert.doesNotMatch(junk, /hardwareConcurrency/);
+ assert.doesNotMatch(junk, /deviceMemory/);
+});
+
+test("server mode: Xvfb zombie sweep — only our exact-signature orphans die", () => {
+ const mk = (pid, ppid, argv, first = "Xvfb") => ({ pid, ppid, argv: [first, ...argv] });
+ const ours = mk(101, 1, [":311", "-screen", "0", "1920x1080x24", "-ac", "-nolisten", "tcp", "-noreset"]);
+ const liveParent = mk(102, 900, [":312", "-screen", "0", "1920x1080x24", "-ac", "-nolisten", "tcp", "-noreset"]);
+ const noReset = mk(103, 1, [":313", "-screen", "0", "1920x1080x24", "-ac", "-nolisten", "tcp"]); // not ours (no -noreset)
+ const otherName = mk(104, 1, [":314", "-screen", "0", "1920x1080x24", "-ac", "-nolisten", "tcp", "-noreset"], "Xvfb-run-wrapper");
+ assert.equal(isStaleAxuseXvfb(ours), true);
+ assert.equal(isStaleAxuseXvfb(liveParent), false, "a live parent owns it — never touched");
+ assert.equal(isStaleAxuseXvfb(noReset), false, "no -noreset: not our signature");
+ assert.equal(isStaleAxuseXvfb(otherName), false, "argv[0] must be exactly Xvfb");
+ // sweepStaleXvfb: fake /proc, only the orphan is killed.
+ const killed = [];
+ const stat = { 101: ours, 102: liveParent, 103: noReset, 104: otherName };
+ const swept = sweepStaleXvfb({
+ listDir: () => Object.keys(stat),
+ readFile: (p) => {
+ const m = /^\/proc\/(\d+)\/(stat|cmdline)$/.exec(p);
+ const e = stat[Number(m[1])];
+ return m[2] === "stat"
+ ? `Xvfb (x) S ${e.ppid}`
+ : e.argv.join("\0");
+ },
+ kill: (pid) => { killed.push(pid); },
+ });
+ assert.deepEqual(swept, [{ pid: 101, display: ":311" }]);
+ assert.deepEqual(killed, [101]);
+ // No /proc (non-Linux-shaped hosts): sweep is a silent no-op.
+ assert.deepEqual(sweepStaleXvfb({ listDir: () => { throw new Error("ENOENT"); }, kill: () => assert.fail("must not kill") }), []);
+});
+
/* ------------------------------------------------------------ live lane */
const linux = process.platform === "linux";
@@ -184,6 +261,48 @@ test("server mode: headed Chrome auto-boots a virtual display (anti-bot posture)
assert.ok(clicked, "input dispatch on the virtual display is fine");
});
+test("server mode: persona coherence — TZ, language and core/memory overrides reach the page", { skip: liveSkip }, async (t) => {
+ const restore = withDeadDisplay();
+ t.after(restore);
+ const saved = ["AXUSE_TIMEZONE", "AXUSE_LANG", "AXUSE_FP_CORES", "AXUSE_FP_MEMORY"].map((k) => [k, process.env[k]]);
+ process.env.AXUSE_TIMEZONE = "Europe/Amsterdam";
+ process.env.AXUSE_LANG = "en-GB";
+ process.env.AXUSE_FP_CORES = "8";
+ process.env.AXUSE_FP_MEMORY = "4";
+ t.after(() => {
+ for (const [k, v] of saved) { if (v === undefined) delete process.env[k]; else process.env[k] = v; }
+ });
+ __resetVirtualDisplay();
+ const c = new Controller();
+ t.after(() => c.dispose());
+ const r = await c.execute("open", { url: "data:text/html,<h1>persona</h1>", settle_ms: 150 });
+ assert.equal(r.display?.virtual, true, "server mode still boots (persona overrides change no lane)");
+ const p = JSON.parse((await c.execute("evaluate", {
+ expression: `(() => {
+ const g = document.createElement('canvas').getContext('webgl');
+ const dbg = g && g.getExtension('WEBGL_debug_renderer_info');
+ return { tz: Intl.DateTimeFormat().resolvedOptions().timeZone, lang: navigator.language,
+ langs: navigator.languages && navigator.languages[0], cores: navigator.hardwareConcurrency,
+ mem: navigator.deviceMemory, webdriver: navigator.webdriver,
+ renderer: dbg ? g.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : null, webgl: !!g };
+ })()`,
+ })).value ?? "{}");
+ // TZ reaches Date/Intl in the page (matches the egress persona).
+ assert.equal(p.tz, "Europe/Amsterdam");
+ // --lang drives navigator.language AND the Accept-Language header source.
+ assert.equal(p.lang, "en-GB");
+ // Persona overrides land (opt-in caps for high-core servers). deviceMemory
+ // only exists on platforms that expose the API (this Linux build does not)
+ // — the override applies exactly there, never inventing an API surface
+ // the platform's honest Chrome lacks.
+ assert.equal(p.cores, 8);
+ assert.ok(p.mem === 4 || p.mem === undefined, `deviceMemory: ${p.mem}`);
+ // And the posture facts still hold under the persona.
+ assert.equal(p.webdriver, false);
+ assert.equal(p.webgl, true);
+ assert.ok(typeof p.renderer === "string" && p.renderer.length > 0, `renderer reported honestly: ${p.renderer}`);
+});
+
test("server mode: AXUSE_HEADLESS=1 lane still opens headless on a dead display", { skip: liveSkip }, async (t) => {
const restore = withDeadDisplay();
t.after(restore);