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 7 — WebRTC leak closed, per-instance personas, tab-sweep hardening

CTOL Team BJ2f4d62faf1e3
diff --git a/README.md b/README.md
index 5e811e7..cd58a22 100644
--- a/README.md
+++ b/README.md
@@ -88,7 +88,7 @@ element refs like `[ref=e7]`. Each action returns only what changed.
| `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_PROXY` | route every launched browser through a proxy (`http://`·`socks5://`, credentials supported — answered over CDP); `ax_open {proxy}` sets it per launch |
+| `AXUSE_PROXY` | route every launched browser through a proxy (`http://`·`socks5://`, credentials supported — answered over CDP); `ax_open {proxy}` sets it per launch, and `ax_open {timezone, lang}` completes the per-instance persona |
| `AXUSE_AMBIENT_MOTION` | `0` disables idle pointer park-fuzz (default: automatic in server mode — the agent's "thinking" pauses still show a live hand) |
| `AXUSE_MAX_BROWSERS` / `AXUSE_MAX_TABS` | governance caps for massive operations (defaults 8 / 48) — typed failures instead of OOM spirals |
| `AXUSE_NO_SANDBOX=1` | force `--no-sandbox` (auto for root/container server runs) |
diff --git a/docs/server-mode.md b/docs/server-mode.md
index 9a6caea..0577576 100644
--- a/docs/server-mode.md
+++ b/docs/server-mode.md
@@ -103,7 +103,7 @@ For one-shot / cron-style runs no service is needed — `axuse solve`,
| `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_PROXY` | Per-process default for the per-launch `proxy` param: `"http://host:port"`, `"socks5://user:pass@host:port"` — one browser instance per spec, credentials answered over CDP. |
-| `AXUSE_PROXY_BYPASS` | Chrome proxy bypass list override (default: loopback bypassed so local fixtures work; `"<-loopback>"` includes localhost). |
+| `AXUSE_PROXY_BYPASS` | Chrome proxy bypass list override (default: loopback bypassed so local fixtures work; `"<-loopback>"` includes localhost). Proxied launches also get the WebRTC `disable_non_proxied_udp` profile pref (measured: the command-line switch is ignored) and quiet-egress flags (no background component/metrics traffic through the persona). |
| `AXUSE_AMBIENT_MOTION` | `0` disables idle pointer park-fuzz; default `auto` = on exactly in server mode. |
| `AXUSE_MAX_BROWSERS` | Governance cap: concurrent launched browsers per process (default 8) — a per-proxy fan-out fails typed at the cap instead of OOM-killing the box. |
| `AXUSE_MAX_TABS` | Governance cap: concurrent tabs per process (default 48). |
@@ -183,6 +183,31 @@ plugins where it matters:
pointer-holding command and whenever a dialog is open — precision always
wins over entropy.
+## Per-instance personas (one process, N exits, N coherent identities)
+
+`ax_open {timezone, lang}` override `AXUSE_TIMEZONE`/`AXUSE_LANG` **per
+browser instance** — with per-launch `proxy`, one agent process hosts one
+coherent persona per exit (a Tokyo-clock browser through the Tokyo exit, a
+New-York-clock browser through the US exit, simultaneously). A different
+persona is a different browser (never a mutation of a live one); the same
+persona reuses its browser. Solver results and `axuse posture` report the
+instance persona.
+
+## WebRTC: the leak beside proxied personas (measured, then closed)
+
+With a proxy, HTTP leaves through the exit — but WebRTC STUN/srflx
+candidates otherwise leave through the **real interface**: the page sees
+the proxy IP on HTTP and the datacenter IP on WebRTC in one session (the
+classic VPN-leak mismatch detector). Measured on Chrome 151: the
+`--force-webrtc-ip-handling-policy` switch is **ignored** by current
+builds (STUN went direct, zero CONNECTs through the proxy); the
+`webrtc.ip_handling_policy` profile pref is **honored** (zero candidates
+through a proxied launch). axuse writes the pref into the profile (merged,
+never clobbering a persistent profile) whenever a launch is proxied —
+mDNS host candidates remain, so the surface is a real Chrome-behind-VPN
+shape, not a disabled one. `axuse posture` probes this live and warns on
+any public candidate beside a proxied exit.
+
## Egress: one browser, one proxy (per-instance routing)
For fleets, each browser instance can leave through its own proxy —
diff --git a/src/core/cdp.js b/src/core/cdp.js
index 0957844..10cc018 100644
--- a/src/core/cdp.js
+++ b/src/core/cdp.js
@@ -9,7 +9,7 @@
* dependency-free — important for a library that harnesses vendor via MCP.
*/
import { spawn } from "node:child_process";
-import { accessSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statfsSync, statSync } from "node:fs";
+import { accessSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statfsSync, statSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { delimiter, join } from "node:path";
import { AxError, Codes } from "./errors.js";
@@ -436,13 +436,14 @@ export class BrowserHandle {
// include localhost for proxy testing.
const bypass = proxyBypass ?? process.env.AXUSE_PROXY_BYPASS;
if (bypass) args.push(`--proxy-bypass-list=${bypass}`);
- // WebRTC leak fix (the classic mismatch detector): without this,
- // STUN/srflx candidates still leave through the REAL interface —
- // the page sees the proxy IP on HTTP and the datacenter IP on
- // WebRTC in the same session. With the policy, WebRTC only uses
- // proxied paths; mDNS-obfuscated host candidates remain, so the
- // surface stays indistinguishable from a real Chrome behind a VPN.
- args.push("--force-webrtc-ip-handling-policy=disable_non_proxied_udp");
+ // WebRTC leak fix (measured live, Chrome 151): STUN/srflx candidates
+ // otherwise leave through the REAL interface — the page sees the
+ // proxy IP on HTTP and the datacenter IP on WebRTC in one session.
+ // The --force-webrtc-ip-handling-policy switch is IGNORED by current
+ // builds (measured: STUN went direct, zero proxy CONNECTs); the
+ // webrtc.ip_handling_policy PROFILE PREF is honored (measured: zero
+ // candidates through a proxied launch). Written below, into the
+ // profile, before spawn.
}
// Quiet egress (server/proxied lanes): Chrome's own background traffic
// (component updates, metrics, domain reliability, phishing lookups,
@@ -513,6 +514,20 @@ export class BrowserHandle {
childEnv.LC_ALL = localeTag;
childEnv.LANG = localeTag;
}
+ // WebRTC leak fix (proxied launches): the honored mechanism is the
+ // webrtc.ip_handling_policy profile PREF (the command-line switch is
+ // ignored by current builds — measured). Merge into an existing
+ // persistent profile's Preferences; write fresh for ephemeral ones.
+ if (proxySpec) {
+ try {
+ const prefsPath = join(dir, "Default", "Preferences");
+ let prefs = {};
+ try { prefs = JSON.parse(readFileSync(prefsPath, "utf8") || "{}"); } catch { /* fresh profile */ }
+ prefs.webrtc = { ...(prefs.webrtc ?? {}), ip_handling_policy: "disable_non_proxied_udp" };
+ mkdirSync(join(dir, "Default"), { recursive: true });
+ writeFileSync(prefsPath, JSON.stringify(prefs));
+ } catch { /* unwritable profile: posture will warn about the leak */ }
+ }
const proc = spawn(exe, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: false, env: childEnv });
let wsUrl;
try {
@@ -634,19 +649,44 @@ export class BrowserHandle {
async createTab(url = "about:blank", { autoAttach = true } = {}) {
const { targetId } = await this.conn.send("Target.createTarget", { url });
const attached = await this.attachTab(targetId, { autoAttach });
- // Now that OUR first tab exists, the browser's startup page(s) can go —
- // every remaining page target is one axuse created and tracks (the
- // "visible tabs, no orphan tabs" promise). Closing them EARLIER, while
- // the startup page is the last page, could terminate the browser.
+ // Close the STARTUP pages recorded at launch — and only those. They
+ // predate every controller tab, so this can never touch a live tab
+ // (the generic sweepStrayPages is for teardown paths, where the
+ // controller passes the registered-tab keep list). Verified with a
+ // re-list and a second pass: under load a single Target.closeTarget
+ // can fail or lag silently.
if (this.startupPages?.length) {
- for (const t of this.startupPages) {
- try { await this.conn.send("Target.closeTarget", { targetId: t }); } catch {}
+ for (let pass = 0; pass < 2; pass++) {
+ const { targetInfos } = await this.conn.send("Target.getTargets", {}).catch(() => ({ targetInfos: [] }));
+ const alive = new Set(targetInfos.filter((ti) => ti.type === "page").map((ti) => ti.targetId));
+ const doomed = this.startupPages.filter((id) => alive.has(id));
+ if (!doomed.length) break;
+ for (const id of doomed) {
+ try { await this.conn.send("Target.closeTarget", { targetId: id }); } catch {}
+ }
}
this.startupPages = [];
}
return attached;
}
+ /** Close every page target not in `keep`, verified with a re-list and a
+ * second pass (under load a single Target.closeTarget can fail or lag
+ * silently; an aborted navigation can also leave a REPLACEMENT target
+ * the caller never saw). Returns how many strays were closed. */
+ async sweepStrayPages(keep = []) {
+ let closed = 0;
+ for (let pass = 0; pass < 2; pass++) {
+ const { targetInfos } = await this.conn.send("Target.getTargets", {}).catch(() => ({ targetInfos: [] }));
+ const strays = targetInfos.filter((ti) => ti.type === "page" && !keep.includes(ti.targetId));
+ if (!strays.length) break;
+ for (const s of strays) {
+ try { await this.conn.send("Target.closeTarget", { targetId: s.targetId }); closed++; } catch {}
+ }
+ }
+ return closed;
+ }
+
/** Attach to an existing page target (e.g. a popup / target=_blank tab). */
async attachTab(targetId, { autoAttach = true } = {}) {
const { sessionId } = await this.conn.send("Target.attachToTarget", { targetId, flatten: true });
diff --git a/src/core/commands.js b/src/core/commands.js
index 43bf258..e2e6680 100644
--- a/src/core/commands.js
+++ b/src/core/commands.js
@@ -30,6 +30,8 @@ export const Contract = Object.freeze({
headless: { t: "boolean", desc: "No window (cdp backend). On a display-less Linux server axuse auto-boots a virtual display and stays headed (anti-bot-safe) — keep headless off for challenge pages; use it only for trusted internal pages." },
proxy: { t: "string", desc: 'Route this browser through a proxy: "http://host:port", "socks5://user:pass@host:port" (per-launch, credentials answered over CDP; loopback bypassed by default; AXUSE_PROXY otherwise).' },
proxy_bypass: { t: "string", desc: 'Chrome proxy bypass list (advanced), e.g. "<-loopback>" to include localhost.' },
+ timezone: { t: "string", desc: 'Per-instance IANA persona zone (e.g. "America/New_York") — Date/Intl in pages and workers; overrides AXUSE_TIMEZONE for this browser (one coherent persona per exit).' },
+ lang: { t: "string", desc: 'Per-instance persona language (e.g. "en-GB") — navigator.languages + Accept-Language + Intl; overrides AXUSE_LANG for this browser.' },
cdp_url: { t: "string", desc: 'Attach instead of launching, e.g. "http://127.0.0.1:9222".' },
backend: { t: "enum", values: ["cdp", "extension"], desc: "Omit for auto (extension when connected, else cdp; AXUSE_BACKEND pins it). cdp = separate, not-signed-in browser." },
executable_path: { t: "string", desc: "Browser binary (default: auto-detect)." },
diff --git a/src/core/controller.js b/src/core/controller.js
index b1eccc9..467d087 100644
--- a/src/core/controller.js
+++ b/src/core/controller.js
@@ -479,7 +479,7 @@ export class Controller {
}
const headless = a.headless ?? /^(1|true)$/i.test(process.env.AXUSE_HEADLESS ?? "");
const { backend, reason } = await this.resolveBackend(a, headless);
- const browser = await this.ensureBrowser({ headless, cdpUrl: a.cdp_url, executablePath: a.executable_path, backend, profileDir: a.profile_dir, proxy: a.proxy, proxyBypass: a.proxy_bypass });
+ const browser = await this.ensureBrowser({ headless, cdpUrl: a.cdp_url, executablePath: a.executable_path, backend, profileDir: a.profile_dir, proxy: a.proxy, proxyBypass: a.proxy_bypass, timezone: a.timezone, lang: a.lang });
const { targetId, sessionId } = await browser.handle.createTab("about:blank");
let tab;
try {
@@ -488,9 +488,13 @@ export class Controller {
await this.navigateInTab(tab, url, a.settle_ms ?? 300);
} catch (e) {
// A failed open must not leak a blank tab nobody holds an id for
- // (downloads end in ERR_ABORTED, hung navigations time out).
+ // (downloads end in ERR_ABORTED, hung navigations time out). An
+ // aborted navigation can also leave a REPLACEMENT target the id
+ // never pointed at — sweep every page we do not still track.
if (tab) this.deregisterTab(tab);
try { await browser.handle.closeTabTarget(targetId); } catch {}
+ const keep = [...this.tabs.values()].map((t) => t.targetId);
+ await browser.handle.sweepStrayPages(keep).catch(() => {});
if (e instanceof AxError) {
throw new AxError(e.code, `${e.message} The tab axuse created for it was closed.`,
{ ...e, facts: { ...(e.facts ?? {}), tab_closed: true } });
@@ -719,10 +723,11 @@ export class Controller {
posture: headless ? "headless" : (vd.active ? "headed-on-virtual-display" : "headed"),
...(vd.active ? { display: vd.display } : {}),
...(rec.egress ? { egress: rec.egress } : {}),
+ ...(rec.persona ? { persona: rec.persona } : {}),
};
}
- async ensureBrowser({ headless, cdpUrl, executablePath, backend, profileDir, proxy, proxyBypass }) {
+ async ensureBrowser({ headless, cdpUrl, executablePath, backend, profileDir, proxy, proxyBypass, timezone, lang }) {
// Extension backend: the user's real Chrome through the axuse bridge
// (Codex pattern: one browser, the user's own, tabs visible to them).
if (backend === "extension") {
@@ -746,9 +751,12 @@ export class Controller {
// unbounded fan-out of per-proxy browsers OOM-kills the box instead of
// failing typed. AXUSE_MAX_BROWSERS (default 8) caps concurrent
// launched browsers; reuse of an existing key is always allowed.
+ // The key includes the FULL per-instance persona (proxy + tz + lang):
+ // one process, one coherent persona per exit — and persona changes
+ // launch a new browser, never mutate a live one.
const key = cdpUrl
? `attach:${cdpUrl}`
- : `launch:${headless ? "headless" : "headed"}:${proxy ?? process.env.AXUSE_PROXY ?? "direct"}:${profileDir ?? "ephemeral"}`;
+ : `launch:${headless ? "headless" : "headed"}:${proxy ?? process.env.AXUSE_PROXY ?? "direct"}:${timezone ?? process.env.AXUSE_TIMEZONE ?? ""}:${lang ?? process.env.AXUSE_LANG ?? ""}:${profileDir ?? "ephemeral"}`;
const maxBrowsers = Number(process.env.AXUSE_MAX_BROWSERS ?? 8);
const existingByKey = this.browserIndex.get(key);
if (!cdpUrl && !existingByKey && this.browsers.size >= maxBrowsers
@@ -768,15 +776,14 @@ export class Controller {
}
const handle = cdpUrl
? await BrowserHandle.attach(cdpUrl)
- : await BrowserHandle.launch({ headless, executablePath, userDataDir: profileDir, proxy, proxyBypass });
+ : await BrowserHandle.launch({ headless, executablePath, userDataDir: profileDir, proxy, proxyBypass, timezone, lang });
const browserId = `b${++this.browserSeq}`;
const rec = { browserId, handle, tabs: new Set(), key };
- // Egress fact for solver results (parseProxySpec strips credentials —
- // only the scheme://host:port ever surfaces).
- // Egress fact for solver results (parseProxySpec strips credentials —
- // only the scheme://host:port ever surfaces).
+ // Egress + persona facts for solver results (parseProxySpec strips
+ // credentials — only the scheme://host:port ever surfaces).
const egressSpec = parseProxySpec(proxy ?? process.env.AXUSE_PROXY ?? "");
if (egressSpec) rec.egress = egressSpec.server;
+ if (timezone || lang) rec.persona = { ...(timezone ? { timezone } : {}), ...(lang ? { lang } : {}) };
this.browsers.set(browserId, rec);
this.browserIndex.set(key, browserId);
await this.watchPopups(rec);
diff --git a/src/plugins/index.js b/src/plugins/index.js
index dedde13..74d2b4c 100644
--- a/src/plugins/index.js
+++ b/src/plugins/index.js
@@ -319,7 +319,7 @@ export function buildSolveContext(controller, tabId) {
}));
},
/** Open a URL in a new tab (profileDir: persistent A2 profile). */
- async open(url, { headless, profileDir, settleMs, executablePath, proxy, proxyBypass } = {}) {
+ async open(url, { headless, profileDir, settleMs, executablePath, proxy, proxyBypass, timezone, lang } = {}) {
const r = await controller.execute("open", {
url: String(url),
...(headless !== undefined ? { headless } : {}),
@@ -328,6 +328,8 @@ export function buildSolveContext(controller, tabId) {
...(executablePath !== undefined ? { executable_path: executablePath } : {}),
...(proxy !== undefined ? { proxy } : {}),
...(proxyBypass !== undefined ? { proxy_bypass: proxyBypass } : {}),
+ ...(timezone !== undefined ? { timezone } : {}),
+ ...(lang !== undefined ? { lang } : {}),
});
return { tabId: r.tab_id, browserId: r.browser_id, observation: r.observation, dialog: r.dialog ?? null, display: r.display ?? null };
},
diff --git a/src/workflows/posture.js b/src/workflows/posture.js
index cfb8f3f..2964f2d 100644
--- a/src/workflows/posture.js
+++ b/src/workflows/posture.js
@@ -28,6 +28,8 @@ const POSTURE_EXPRESSION = `(() => {
const ctx = new OfflineAudioContext(1, 4096, 44100);
const o = ctx.createOscillator(); o.connect(ctx.destination); o.start(0);
} catch (e) { audioOffline = false; }
+ let webrtcSupported = false;
+ try { webrtcSupported = typeof RTCPeerConnection !== "undefined"; } catch (e) {}
return {
ua: navigator.userAgent,
webdriver: navigator.webdriver,
@@ -45,9 +47,50 @@ const POSTURE_EXPRESSION = `(() => {
pdfViewer: navigator.pdfViewerEnabled === true,
notifications: (typeof Notification !== "undefined" && Notification.permission) || "unsupported",
audioOffline,
+ webrtcSupported,
};
})()`;
+/** WebRTC leak probe (proxied lanes): gather ICE candidates and classify
+ * them — mDNS host candidates (.local) are fine (real Chrome behind a VPN
+ * shows those too); any PUBLIC IP (srflx/relay of the real interface)
+ * beside a proxied HTTP persona is the classic mismatch leak. Bounded:
+ * never waits longer than ~4 s for the ICE state. Exported for tests. */
+export const WEBRTC_EXPRESSION = `(async () => {
+ if (typeof RTCPeerConnection === "undefined") return { supported: false, candidates: [] };
+ const cands = [];
+ const pc = new RTCPeerConnection({ iceServers: [{ urls: "stun:stun.l.google.com:19302" }] });
+ try {
+ pc.createDataChannel("axuse-posture");
+ const gathered = new Promise((done) => {
+ pc.onicecandidate = (e) => {
+ if (!e.candidate) { done(); return; }
+ const m = /candidate:\\S+ \\d+ \\S+ \\d+ (\\S+) \\d+ typ (\\w+)/.exec(e.candidate.candidate || "");
+ if (m) cands.push({ ip: m[1], typ: m[2] });
+ };
+ setTimeout(done, 4000);
+ });
+ await pc.setLocalDescription(await pc.createOffer());
+ await Promise.race([gathered, new Promise((r) => setTimeout(r, 4500))]);
+ } catch (e) { /* ICE unavailable — reported as empty */ }
+ try { pc.close(); } catch (e) {}
+ return { supported: true, candidates: cands };
+})()`;
+
+/** Private-IP and mDNS classification: a candidate is a PERSONA CONTRADICTION
+ * only when it carries a public, non-mDNS address next to a proxied exit. */
+export function publicIpCandidates(candidates) {
+ return (candidates ?? []).filter((c) => {
+ const ip = String(c.ip ?? "");
+ if (ip.endsWith(".local") || ip.includes(":")) return false; // mDNS / IPv6 local
+ const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(ip);
+ if (!m) return false;
+ const [a, b] = [Number(m[1]), Number(m[2])];
+ if (a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254)) return false;
+ return true;
+ });
+}
+
const EGRESS_EXPRESSION = `(async () => {
try {
const echo = await fetch(${JSON.stringify(process.env.AXUSE_EGRESS_ECHO_URL ?? "https://api.ipify.org?format=json")}, { cache: "no-store" });
@@ -59,14 +102,20 @@ const EGRESS_EXPRESSION = `(async () => {
const GEO_URL = (ip) => (process.env.AXUSE_EGRESS_GEO_URL ?? `https://ipapi.co/{ip}/json/`).replace("{ip}", encodeURIComponent(ip));
/** Measure the live posture of the controller's active tab (opens one when
- * none exists — the production lane, server mode included). */
+ * none exists — the production lane, server mode included). When the
+ * browser is PROXIED, also probes the WebRTC surface: the one place a real
+ * interface can leak next to a proxied persona. */
export async function collectPosture(controller) {
if (!controller.activeTabId) {
await controller.execute("open", { url: "about:blank", settle_ms: 150 });
}
const facts = JSON.parse((await controller.execute("evaluate", { expression: POSTURE_EXPRESSION })).value ?? "null");
const browser = [...controller.browsers.values()].at(-1);
- return { facts, posture: controller.browserPosture(), browserId: browser?.browserId ?? null };
+ let webrtc = null;
+ if (browser?.egress && facts?.webrtcSupported) {
+ webrtc = JSON.parse((await controller.execute("evaluate", { expression: WEBRTC_EXPRESSION })).value ?? "null");
+ }
+ return { facts, webrtc, posture: controller.browserPosture(), browserId: browser?.browserId ?? null };
}
/** In-browser egress check (opt-in): the IP the EXIT sees, and — when a geo
@@ -94,14 +143,17 @@ const regionOf = (v) => {
return m ? m[1].toUpperCase() : "";
};
-/** Pure: facts × env → verdicts. The rules the tests pin, in one place. */
-export function judgePosture({ facts, posture, egress }, env = process.env) {
+/** Pure: facts × env → verdicts. The rules the tests pin, in one place.
+ * Persona expectations resolve PER-INSTANCE first (open {timezone, lang} /
+ * the browser record's persona), then process env, then info. */
+export function judgePosture({ facts, posture, egress, webrtc }, env = process.env) {
const checks = [];
const add = (id, status, detail) => checks.push({ id, status, detail });
if (!facts) {
add("facts", "fail", "no in-page facts collected — the browser lane is broken");
return { checks, failures: 1, warnings: 0 };
}
+ const persona = posture?.persona ?? {};
// Critical: the headless class of signals.
add("user-agent", /headless/i.test(facts.ua) ? "fail" : "pass",
/headless/i.test(facts.ua) ? "UA contains Headless — the exact first-step detection signal" : `headed (${facts.ua.replace(/^.*?\(([^)]*\)).*$/, "$1")})`);
@@ -114,15 +166,15 @@ export function judgePosture({ facts, posture, egress }, env = process.env) {
facts.webgl ? `present (${String(facts.renderer).slice(0, 60)})` : "absent — a strong bot signal on GPU-less hosts (--enable-unsafe-swiftshader should restore it)");
add("pdf-plugins", facts.pdfViewer && facts.plugins > 0 ? "pass" : "warn",
facts.pdfViewer && facts.plugins > 0 ? `${facts.plugins} plugins, PDF viewer enabled (headed build shape)` : "no PDF plugin — headless-like plugin surface");
- // Persona coherence: clock, languages, viewport.
- const wantTz = env.AXUSE_TIMEZONE;
+ // Persona coherence: clock, languages, viewport (per-instance first).
+ const wantTz = persona.timezone ?? env.AXUSE_TIMEZONE;
if (wantTz) {
add("timezone", facts.tz === wantTz ? "pass" : "fail",
- facts.tz === wantTz ? `${facts.tz} (matches AXUSE_TIMEZONE)` : `page reports ${facts.tz}, AXUSE_TIMEZONE=${wantTz} — persona broken`);
+ facts.tz === wantTz ? `${facts.tz} (matches ${persona.timezone ? "the instance persona" : "AXUSE_TIMEZONE"})` : `page reports ${facts.tz}, expected ${wantTz} — persona broken`);
} else {
- add("timezone", "info", `${facts.tz} (host default — set AXUSE_TIMEZONE to the egress persona's zone)`);
+ add("timezone", "info", `${facts.tz} (host default — set a per-instance timezone or AXUSE_TIMEZONE to the egress persona's zone)`);
}
- const wantLang = env.AXUSE_LANG;
+ const wantLang = persona.lang ?? env.AXUSE_LANG;
if (wantLang) {
const langOk = langPrefix(facts.languages[0]) === langPrefix(wantLang) && regionOf(facts.languages[0] ?? "") === regionOf(wantLang);
// Intl can legitimately drop the region (measured: LC_ALL=de_DE.UTF-8 →
@@ -139,7 +191,22 @@ export function judgePosture({ facts, posture, egress }, env = process.env) {
add("language", "info", `navigator.languages=[${facts.languages.join(", ")}] · Intl=${facts.intl} (host defaults)`);
}
const vd = posture && typeof posture === "object" ? posture : {};
- add("browser-shape", "info", `${vd.posture ?? "unknown"}${vd.display ? ` on ${vd.display}` : ""}${vd.egress ? ` · egress ${vd.egress}` : ""}`);
+ add("browser-shape", "info", `${vd.posture ?? "unknown"}${vd.display ? ` on ${vd.display}` : ""}${vd.egress ? ` · egress ${vd.egress}` : ""}${vd.persona?.timezone || vd.persona?.lang ? ` · persona ${[vd.persona.timezone, vd.persona.lang].filter(Boolean).join("/")}` : ""}`);
+ // WebRTC (proxied lanes only — the one place a real interface can leak
+ // next to a proxied persona; unproxied lanes honestly show their IP).
+ if (vd.egress) {
+ if (!facts.webrtcSupported) {
+ add("webrtc", "info", "RTCPeerConnection unavailable on this build");
+ } else if (!webrtc) {
+ add("webrtc", "info", "not probed");
+ } else {
+ const leak = publicIpCandidates(webrtc.candidates);
+ add("webrtc", leak.length ? "warn" : "pass",
+ leak.length
+ ? `LEAK: public WebRTC candidate(s) ${leak.map((c) => `${c.ip} (${c.typ})`).join(", ")} beside the proxied exit ${vd.egress} — disable_non_proxied_udp should suppress these (build ignored the policy?)`
+ : "no public candidates beside the proxied exit (mDNS host candidates only — a real VPN shape)");
+ }
+ }
add("fingerprint-surface", "info",
`cores=${facts.cores} memory=${facts.memory ?? "n/a"} viewport=${facts.viewport.w}x${facts.viewport.h}@dpr${facts.viewport.dpr} screen=${facts.screen.w}x${facts.screen.h}x${facts.screen.depth}`);
add("audio", facts.audioOffline ? "pass" : "warn",
diff --git a/test/posture.test.js b/test/posture.test.js
index 2e5c1ab..85b5c1d 100644
--- a/test/posture.test.js
+++ b/test/posture.test.js
@@ -10,7 +10,7 @@
*/
import { test } from "node:test";
import assert from "node:assert/strict";
-import { judgePosture } from "../src/workflows/posture.js";
+import { judgePosture, publicIpCandidates } from "../src/workflows/posture.js";
import { locateBrowser } from "../src/core/cdp.js";
import { Controller } from "../src/core/controller.js";
@@ -78,6 +78,36 @@ test("posture: egress geo vs clock — the fleet misconfiguration detector", ()
assert.equal(by(offline)["egress"], "info");
});
+test("posture: webrtc classification — mDNS/private candidates never leak, public IPs do", () => {
+ assert.deepEqual(publicIpCandidates([
+ { ip: "904bc723-6ac3-47e4-9c8e-f390cc12caea.local", typ: "host" },
+ { ip: "192.168.1.5", typ: "host" },
+ { ip: "fe80::1", typ: "host" },
+ ]), [], "mDNS and private IPs are a real VPN shape, not leaks");
+ assert.deepEqual(publicIpCandidates([{ ip: "79.127.184.170", typ: "srflx" }]), [{ ip: "79.127.184.170", typ: "srflx" }]);
+ // The judge: leak → warn beside a proxied exit; clean → pass; unprobed → info.
+ const proxied = { posture: "headed", egress: "http://1.2.3.4:8080" };
+ const leak = judgePosture({ facts: { ...GOOD_FACTS, webrtcSupported: true }, posture: proxied, webrtc: { supported: true, candidates: [{ ip: "79.127.184.170", typ: "srflx" }] } }, {});
+ assert.equal(by(leak)["webrtc"], "warn");
+ assert.match(leak.checks.find((c) => c.id === "webrtc").detail, /LEAK/);
+ const clean = judgePosture({ facts: { ...GOOD_FACTS, webrtcSupported: true }, posture: proxied, webrtc: { supported: true, candidates: [{ ip: "abc.local", typ: "host" }] } }, {});
+ assert.equal(by(clean)["webrtc"], "pass");
+ const unprobed = judgePosture({ facts: { ...GOOD_FACTS, webrtcSupported: true }, posture: proxied, webrtc: null }, {});
+ assert.equal(by(unprobed)["webrtc"], "info");
+ // Unproxied lanes never get the check (their IP is honestly theirs).
+ assert.equal(by(judgePosture({ facts: GOOD_FACTS, posture: { posture: "headed" } }, {}))["webrtc"], undefined);
+});
+
+test("posture: per-instance persona drives the judge (before process env)", () => {
+ const persona = judgePosture(
+ { facts: { ...GOOD_FACTS, tz: "Asia/Tokyo", languages: ["ja-JP"], intl: "ja-JP" }, posture: { posture: "headed", persona: { timezone: "Asia/Tokyo", lang: "ja-JP" } } },
+ { AXUSE_TIMEZONE: "America/New_York", AXUSE_LANG: "en-US" },
+ );
+ assert.equal(by(persona)["timezone"], "pass", "instance persona wins over the process env");
+ assert.equal(by(persona)["language"], "pass");
+ assert.match(persona.checks.find((c) => c.id === "timezone").detail, /instance persona/);
+});
+
const hasBrowser = !!locateBrowser();
const linux = process.platform === "linux";
const xvfb = linux && (await import("node:child_process")).spawnSync("which", ["Xvfb"]).status === 0;
@@ -124,3 +154,66 @@ test("governance: the browser cap fails typed instead of OOM-killing the box", {
(e) => e.code === "COMMAND_REJECTED" && /Browser cap reached/.test(e.message),
);
});
+
+test("per-instance persona: one process, two browsers, two coherent personas", { skip: !hasBrowser ? "live-gate-browser: needs any Chromium-family browser" : false }, async (t) => {
+ const c = new Controller();
+ t.after(() => c.dispose());
+ const readPersona = async () => JSON.parse((await c.execute("evaluate", {
+ expression: "({tz: Intl.DateTimeFormat().resolvedOptions().timeZone, lang: navigator.language, intl: Intl.DateTimeFormat().resolvedOptions().locale})",
+ })).value ?? "{}");
+
+ const tokyo = await c.execute("open", { url: "about:blank", headless: true, timezone: "Asia/Tokyo", lang: "en-GB", settle_ms: 150 });
+ const p1 = await readPersona();
+ assert.equal(p1.tz, "Asia/Tokyo");
+ assert.equal(p1.lang, "en-GB");
+ assert.equal(p1.intl, "en-GB");
+ assert.deepEqual(c.browserPosture().persona, { timezone: "Asia/Tokyo", lang: "en-GB" });
+
+ const ny = await c.execute("open", { url: "about:blank", headless: true, timezone: "America/New_York", lang: "en-US", settle_ms: 150 });
+ assert.notEqual(ny.browser_id, tokyo.browser_id, "a different persona is a different browser, never a mutation");
+ const p2 = JSON.parse((await c.execute("evaluate", {
+ expression: "({tz: Intl.DateTimeFormat().resolvedOptions().timeZone, lang: navigator.language, intl: Intl.DateTimeFormat().resolvedOptions().locale})",
+ tab_id: ny.tab_id, // two tabs are controlled now — the strict lane requires it
+ })).value ?? "{}");
+ assert.equal(p2.tz, "America/New_York");
+ assert.equal(p2.lang, "en-US");
+
+ // Same persona again → same browser (the reuse key includes the persona).
+ const again = await c.execute("open", { url: "about:blank", headless: true, timezone: "Asia/Tokyo", lang: "en-GB", settle_ms: 100 });
+ assert.equal(again.browser_id, tokyo.browser_id);
+});
+
+test("webrtc: a proxied launch leaks no public ICE candidate (the profile-pref fix)", { skip: !hasBrowser ? "live-gate-browser: needs any Chromium-family browser" : false }, async (t) => {
+ // A working CONNECT tunnel — the production proxy shape. (The pref fix
+ // suppresses non-proxied paths; whether the tunnel carries STUN or not,
+ // NO public candidate may appear beside the proxied persona.)
+ const { default: http } = await import("node:http");
+ const { default: net } = await import("node:net");
+ const proxy = http.createServer((req, res) => { res.writeHead(403); res.end(); });
+ proxy.on("connect", (req, clientSocket, head) => {
+ const [host, port] = req.url.split(":");
+ const upstream = net.connect(Number(port) || 443, host, () => {
+ clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
+ upstream.write(head);
+ upstream.pipe(clientSocket);
+ clientSocket.pipe(upstream);
+ });
+ upstream.on("error", () => clientSocket.destroy());
+ clientSocket.on("error", () => upstream.destroy());
+ });
+ await new Promise((ok) => proxy.listen(0, "127.0.0.1", ok));
+ t.after(() => proxy.close());
+ const { WEBRTC_EXPRESSION } = await import("../src/workflows/posture.js");
+ const c = new Controller();
+ t.after(() => c.dispose());
+ await c.execute("open", {
+ url: "data:text/html,<h1>rtc</h1>",
+ headless: true,
+ proxy: `http://127.0.0.1:${proxy.address().port}`,
+ settle_ms: 200,
+ });
+ const webrtc = JSON.parse((await c.execute("evaluate", { expression: WEBRTC_EXPRESSION })).value ?? "null");
+ assert.ok(webrtc?.supported, "RTCPeerConnection present (the surface itself is not removed)");
+ const leak = publicIpCandidates(webrtc.candidates ?? []);
+ assert.deepEqual(leak, [], `no public candidate beside the proxied exit (got ${JSON.stringify(leak)})`);
+});