Stealth browser automation for AI agents over MCP and the Chrome DevTools Protocol: navigation, network hooks, DOM extraction, and pixel-accurate UI cloning.
Python ai-agent-toolsai-toolsanthropicanti-bot-bypassautomation-toolsbrowser-automationchrome-devtoolsclaude-mcpcloudflare-bypassdeveloper-toolsfastmcpmcp-servermodel-context-protocolnetwork-interceptionnodriverpythonstealth-browserundetectable-browserweb-automationweb-scraping
Keep the Chrome sandbox and harden browser startup
Vibhek Sonibc7fd083616a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 014d1d2..585b85d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,10 +13,13 @@ The format is based on Keep a Changelog and adheres to Semantic Versioning where- **`STEALTH_BROWSER_EXECUTABLE`** - Environment variable that selects the browser executable instead of auto-detection.- **Page bindings** - `create_page_binding`, `get_page_binding_calls`, `resolve_page_binding_call`, and `remove_page_binding` let page JavaScript call `window.<name>(...args)` and get a Promise that the agent answers. Calls are queued as JSON (64 KB per call, 500 queued per instance), `auto_resolve` answers immediately with a fixed value, and bindings follow every tab and navigation. Nothing runs on the server host. This replaces `create_python_binding`.- **`BROWSER_TAB_RECYCLE_NAVIGATIONS`** - Opt-in main tab recycling. It was always on at 25 navigations before.+- **Launch flags benchmark target** - Fails when the real Chrome command line has automation, sandbox-disabling, or unsupported flags.- **Input fidelity benchmark target** - Checks that `click_element` and `type_text` produce trusted events in a real order without touching the page DOM.- **Tests** - `tests/test_js_values.py`, `tests/test_element_cloners.py`, and `tests/test_hooks_and_proxy.py` cover result conversion, template escaping, cloner data paths, hook matching, proxy parsing, and debug log export. CI now runs the unit test suite.### Fixed+- **Sandbox flags** - Chrome keeps its sandbox on Windows and macOS, including under an administrator account. Only Linux as root or in a container gets `--no-sandbox`. `--disable-setuid-sandbox`, `--single-process`, and `--disable-gpu` are no longer added anywhere, so headed windows no longer show the "unsupported command-line flag" bar, tabs no longer share one crash-prone process in containers, and WebGL stays available.+- **Browser startup** - Chrome gets up to 30 seconds to start instead of under 3, which cold CI runners and slow disks missed. A failed start no longer leaves a Chrome process and temp profile behind, and Chrome's output goes to the null device instead of an unread pipe that could fill up and block it.- **Trusted clicks** - `click_element` scrolls the element into view, moves the mouse along a short path, and presses and releases the button with CDP input events, so pages see trusted `pointerdown`, `mousedown`, `mouseup`, and `click` events. It used to call `el.click()` from JavaScript, which produces an untrusted click with no mouse events, and nodriver's click flashed a highlight element into the page DOM. Covered or hidden elements still fall back to a JavaScript click.- **Trusted typing** - `type_text` sends keydown, keypress, input, and keyup for every character, holds Shift for capitals and symbols, and inserts other characters like an input method. It used to send bare `char` events. Clearing a field now selects the content and presses Backspace, so React and other frameworks see the change. `parse_newlines` and `shift_enter` press real Enter and Shift+Enter keys.- **Speed** - `navigate` returns in about 30 ms on a simple page instead of about 550 ms, `close_instance` takes about 0.2 s instead of hitting a 5 s timeout every time, `click_element` dropped its fixed 0.5 s wait, `list_tabs` and `new_tab` no longer wait 0.5 s per tab, and `wait_for_element` polls every 100 ms without fetching the whole DOM tree. Element lookups for click, type, paste, and key presses fetch only the document root.diff --git a/STEALTH_TESTS.md b/STEALTH_TESTS.mdindex 75136b2..990119d 100644--- a/STEALTH_TESTS.md+++ b/STEALTH_TESTS.md@@ -17,6 +17,7 @@ Local runs write to `.stealth-results/` and print one line per target. Use `--ou| Target | What it measures ||--------|------------------|+| Launch flags | The real Chrome command line has no automation, sandbox-disabling, or unsupported flags || Local fingerprint probe | Automation tells read by a bundled page on 127.0.0.1, no network needed || Init script injection | `add_script_to_evaluate_on_new_document` runs before page scripts and survives navigation || Input fidelity | `click_element` and `type_text` produce trusted pointer, mouse, and key events in a real order, with nothing injected into the page |diff --git a/benchmarks/stealth/runner.py b/benchmarks/stealth/runner.pyindex 6d3c9fc..81fcdb4 100644--- a/benchmarks/stealth/runner.py+++ b/benchmarks/stealth/runner.py@@ -13,6 +13,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))import nodriver as uc+import psutilfrom browser_manager import BrowserManagerfrom dom_handler import DOMHandler@@ -98,6 +99,16 @@ class BrowserSession:"""return await self.manager.add_init_script(self.instance_id, source)+ async def launch_arguments(self) -> List[str]:+ """+ Read the browser process command line.++ Returns:+ List[str]: Arguments after the executable+ """+ browser = await self.manager.get_browser(self.instance_id)+ return psutil.Process(browser._process.pid).cmdline()[1:]+async def click(self, selector: str) -> None:"""Click through DOMHandler.click_element.diff --git a/benchmarks/stealth/targets/__init__.py b/benchmarks/stealth/targets/__init__.pyindex 5366b7f..ba7a4c5 100644--- a/benchmarks/stealth/targets/__init__.py+++ b/benchmarks/stealth/targets/__init__.py@@ -6,11 +6,13 @@ from .base import Targetfrom .cloudflare import CloudflareTargetfrom .creepjs import CreepJSTargetfrom .input_fidelity import InputFidelityTarget+from .launch_flags import LaunchFlagsTargetfrom .local_probe import InitScriptTarget, LocalProbeTargetfrom .result_tables import IntoliTarget, SannysoftTargetfrom .tls_fingerprint import TLSFingerprintTargetALL_TARGETS: List[Target] = [+ LaunchFlagsTarget(),LocalProbeTarget(),InitScriptTarget(),InputFidelityTarget(),diff --git a/benchmarks/stealth/targets/base.py b/benchmarks/stealth/targets/base.pyindex 705849a..7920e5c 100644--- a/benchmarks/stealth/targets/base.py+++ b/benchmarks/stealth/targets/base.py@@ -46,6 +46,14 @@ class Session(Protocol):str: Script identifier"""+ async def launch_arguments(self) -> List[str]:+ """+ Command line arguments of the running browser process.++ Returns:+ List[str]: Arguments after the executable+ """+async def click(self, selector: str) -> None:"""Click an element the way the click_element tool does.diff --git a/benchmarks/stealth/targets/launch_flags.py b/benchmarks/stealth/targets/launch_flags.pynew file mode 100644index 0000000..8b52d0d--- /dev/null+++ b/benchmarks/stealth/targets/launch_flags.py@@ -0,0 +1,88 @@+"""Target that checks the browser command line for automation and warning flags."""++from typing import Any, Dict, List, Tuple++from ..results import Check+from .base import Session, Target++AUTOMATION_FLAGS = (+ "--enable-automation",+ "--remote-debugging-pipe",+ "--remote-debugging-port=0",+ "--headless=old",+)+WARNING_FLAGS = (+ "--no-sandbox",+ "--disable-setuid-sandbox",+ "--single-process",+ "--disable-web-security",+ "--disable-site-isolation-trials",+ "--ignore-certificate-errors",+)+DEGRADING_FLAGS = ("--disable-gpu",)+++def matching_flags(arguments: List[str], flags: Tuple[str, ...]) -> List[str]:+ """+ Find launch arguments that start with any of the given flags.++ Args:+ arguments (List[str]): Browser command line arguments.+ flags (Tuple[str, ...]): Flag prefixes to look for.++ Returns:+ List[str]: Matching arguments in command line order.+ """+ return [argument for argument in arguments if argument.startswith(flags)]+++class LaunchFlagsTarget(Target):+ """+ Reads the real browser command line.++ Automation flags turn on navigator.webdriver or similar tells. Warning+ flags make headed Chrome show an "unsupported command-line flag" bar and+ weaken the browser. --disable-gpu removes WebGL, which is itself a signal.+ """++ name = "launch_flags"+ title = "Launch flags"+ category = "Browser configuration"+ url = ""+ timeout = 15.0++ async def collect(self, session: Session) -> Dict[str, Any]:+ """+ Read the browser process arguments.++ Args:+ session (Session): Active browser session++ Returns:+ Dict[str, Any]: {"arguments": [...]} without the profile path+ """+ arguments = await session.launch_arguments()+ return {"arguments": [argument for argument in arguments if not argument.startswith("--user-data-dir")]}++ def evaluate(self, payload: Dict[str, Any]) -> Tuple[List[Check], Dict[str, Any], str]:+ """+ Turn the command line into checks.++ Args:+ payload (Dict[str, Any]): Data returned by collect()++ Returns:+ Tuple[List[Check], Dict[str, Any], str]: Checks, details, and summary+ """+ arguments = payload.get("arguments") or []+ automation = matching_flags(arguments, AUTOMATION_FLAGS)+ warnings = matching_flags(arguments, WARNING_FLAGS)+ degrading = matching_flags(arguments, DEGRADING_FLAGS)+ checks = [+ Check("no automation flags", not automation, True, automation),+ Check("no unsupported or sandbox-disabling flags", not warnings, True, warnings),+ Check("GPU not disabled", not degrading, False, degrading),+ ]+ found = automation + warnings + degrading+ summary = f"found {', '.join(found)}" if found else f"{len(arguments)} arguments, none flagged"+ return checks, {"arguments": arguments}, summarydiff --git a/src/browser_launcher.py b/src/browser_launcher.pynew file mode 100644index 0000000..fec9000--- /dev/null+++ b/src/browser_launcher.py@@ -0,0 +1,141 @@+"""Chrome process launch with a patient DevTools handshake and no leaked processes."""++import asyncio+import shutil+import sys+import time+from pathlib import Path+from typing import Optional++import nodriver as uc+import psutil+from nodriver import Browser+from nodriver.core import util as nodriver_util++DEVTOOLS_READY_TIMEOUT = 30.0+DEVTOOLS_POLL_INTERVAL = 0.05+PROCESS_EXIT_TIMEOUT = 3.0+ACTIVE_PORT_FILE = "DevToolsActivePort"+++def _is_listening(pid: int, port: int) -> bool:+ """+ Check whether a process or its children listen on a TCP port.++ Inspecting the process avoids probing a closed port, which takes about a+ second to be refused on Windows.++ Args:+ pid (int): Browser process id.+ port (int): DevTools port.++ Returns:+ bool: True once the port is in LISTEN state.+ """+ try:+ root = psutil.Process(pid)+ for process in [root, *root.children(recursive=True)]:+ for connection in process.net_connections(kind="tcp"):+ if connection.status == psutil.CONN_LISTEN and connection.laddr and connection.laddr.port == port:+ return True+ except (psutil.Error, OSError):+ return False+ return False+++def _read_active_port(profile_dir: Path) -> Optional[int]:+ """+ Read the DevTools port Chrome writes once its debugging server listens.++ Args:+ profile_dir (Path): Browser user data directory.++ Returns:+ Optional[int]: Port number, or None when the file is not written yet.+ """+ try:+ first_line = (profile_dir / ACTIVE_PORT_FILE).read_text(encoding="utf-8").splitlines()[0]+ return int(first_line.strip())+ except (OSError, ValueError, IndexError):+ return None+++async def _stop_process(process: asyncio.subprocess.Process) -> None:+ """+ Terminate a process, killing it if it does not exit in time.++ Args:+ process (asyncio.subprocess.Process): Process to stop.+ """+ if process.returncode is not None:+ return+ for signal_process in (process.terminate, process.kill):+ try:+ signal_process()+ await asyncio.wait_for(process.wait(), PROCESS_EXIT_TIMEOUT)+ return+ except ProcessLookupError:+ return+ except Exception:+ continue+++async def launch_browser(config: uc.Config, timeout: float = DEVTOOLS_READY_TIMEOUT) -> Browser:+ """+ Start Chrome for a nodriver config and connect to it.++ nodriver launches Chrome itself but gives the DevTools endpoint under+ three seconds to come up, which cold starts on CI machines and slow+ disks miss, and it leaves the process running when that happens. It+ also pipes Chrome's output without reading it, so a chatty browser can+ block on a full pipe. Here readiness is detected by watching the+ process listen on its debugging port, its output goes to the null device, startup gets up to `timeout`+ seconds, and a failed start kills the process and removes its temporary+ profile. Port 0 is avoided on purpose, because Chrome treats+ --remote-debugging-port=0 as automation and sets navigator.webdriver.++ Args:+ config (uc.Config): nodriver config describing the launch.+ timeout (float): Seconds to wait for the DevTools endpoint.++ Returns:+ Browser: Connected nodriver browser whose `_process` is the launched Chrome.++ Raises:+ Exception: When Chrome exits early or the endpoint does not come up in time.+ """+ profile_dir = Path(config.user_data_dir)+ profile_dir.mkdir(parents=True, exist_ok=True)+ (profile_dir / ACTIVE_PORT_FILE).unlink(missing_ok=True)+ config.host = "127.0.0.1"+ config.port = nodriver_util.free_port()+ process = await asyncio.create_subprocess_exec(+ config.browser_executable_path,+ *config(),+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.DEVNULL,+ stderr=asyncio.subprocess.DEVNULL,+ close_fds=sys.platform != "win32",+ )+ try:+ deadline = time.monotonic() + timeout+ while not (+ _read_active_port(profile_dir) == config.port+ or await asyncio.to_thread(_is_listening, process.pid, config.port)+ ):+ if process.returncode is not None:+ raise Exception(f"Browser exited during startup with code {process.returncode}")+ if time.monotonic() >= deadline:+ raise Exception(f"Browser DevTools endpoint did not start within {timeout:.0f}s")+ await asyncio.sleep(DEVTOOLS_POLL_INTERVAL)++ browser = Browser(config)+ await browser.start()+ browser._process = process+ browser._process_pid = process.pid+ return browser+ except BaseException:+ await _stop_process(process)+ if not config.uses_custom_data_dir:+ shutil.rmtree(config.user_data_dir, ignore_errors=True)+ raisediff --git a/src/browser_manager.py b/src/browser_manager.pyindex 52ef31d..defc4c8 100644--- a/src/browser_manager.py+++ b/src/browser_manager.py@@ -12,6 +12,7 @@ import nodriver as ucfrom nodriver import Browser, Tabimport cdp_raw+from browser_launcher import launch_browserfrom debug_logger import debug_loggerfrom models import BrowserInstance, BrowserState, BrowserOptions, PageStatefrom persistent_storage import persistent_storage@@ -28,7 +29,7 @@ from proxy_utils import ()HEADLESS_UA_TOKEN = "HeadlessChrome/"-HEADLESS_UA_PROBE_TIMEOUT = 20.0+HEADLESS_UA_PROBE_TIMEOUT = 40.0CLOSE_STEP_TIMEOUT = 2.0TARGET_UPDATE_EVENTS = (uc.cdp.target.TargetInfoChanged,@@ -169,7 +170,7 @@ class BrowserManager:user_agent: Optional[str] = Nonetry:probe = await asyncio.wait_for(- uc.start(config=uc.Config(+ launch_browser(uc.Config(headless=True,sandbox=sandbox,browser_executable_path=browser_executable,@@ -470,7 +471,7 @@ class BrowserManager:browser_args=launch_args)- browser = await uc.start(config=config)+ browser = await launch_browser(config)tab = browser.main_tabconfig_obj = getattr(browser, "config", None)actual_user_data_dir = getattr(config_obj, "user_data_dir", options.user_data_dir)diff --git a/src/platform_utils.py b/src/platform_utils.pyindex 2016b0b..f1409a5 100644--- a/src/platform_utils.py+++ b/src/platform_utils.py@@ -65,38 +65,36 @@ def is_running_in_container() -> bool:return any(container_indicators)+def sandbox_must_be_disabled() -> bool:+ """+ Check whether Chrome can only start without its sandbox here.++ Only Linux needs this, when running as root or inside a container.+ Chrome on Windows runs sandboxed under an administrator account, and+ every extra sandbox flag shows an "unsupported command-line flag" bar+ in headed windows, so other platforms keep the sandbox.++ Returns:+ bool: True on Linux as root or in a container+ """+ if platform.system().lower() != 'linux':+ return False+ return is_running_as_root() or is_running_in_container()++def get_required_sandbox_args() -> List[str]:"""- Get the required browser arguments for sandbox handling based on current environment.-+ Get the browser arguments the current environment requires.++ Only --no-sandbox is added, and only where Chrome cannot start otherwise.+ Flags such as --disable-setuid-sandbox, --single-process, and+ --disable-gpu are left out: they show warning bars, crash tabs, or remove+ WebGL, which makes the browser easier to fingerprint.+Returns:List[str]: List of browser arguments needed for current environment"""- args = []-- if is_running_as_root():- args.extend([- '--no-sandbox',- '--disable-setuid-sandbox'- ])-- if is_running_in_container():- args.extend([- '--no-sandbox',- '--disable-setuid-sandbox',- '--disable-dev-shm-usage',- '--disable-gpu',- '--single-process',- ])-- seen = set()- unique_args = []- for arg in args:- if arg not in seen:- seen.add(arg)- unique_args.append(arg)-- return unique_args+ return ['--no-sandbox'] if sandbox_must_be_disabled() else []def merge_browser_args(user_args: Optional[List[str]] = None) -> List[str]:diff --git a/src/server.py b/src/server.pyindex dab1edf..35e1df8 100644--- a/src/server.py+++ b/src/server.py@@ -249,10 +249,10 @@ async def spawn_browser(Dict[str, Any]: Instance information including instance_id."""try:- from platform_utils import is_running_as_root, is_running_in_container-+ from platform_utils import sandbox_must_be_disabled+if sandbox is None:- sandbox = not (is_running_as_root() or is_running_in_container())+ sandbox = not sandbox_must_be_disabled()elif isinstance(sandbox, str):sandbox = sandbox.lower() in ('true', '1', 'yes', 'on', 'enabled')elif isinstance(sandbox, int):diff --git a/tests/test_headless_user_agent.py b/tests/test_headless_user_agent.pyindex b7dd6f0..0b6a7a0 100644--- a/tests/test_headless_user_agent.py+++ b/tests/test_headless_user_agent.py@@ -51,7 +51,7 @@ class HeadlessUserAgentTests(unittest.TestCase):manager = BrowserManager()cleanup = mock.Mock()- with mock.patch.object(browser_manager_module.uc, "start", side_effect=fake_start), mock.patch.object(+ with mock.patch.object(browser_manager_module, "launch_browser", side_effect=fake_start), mock.patch.object(browser_manager_module, "process_cleanup", cleanup):first = asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, ["--lang=en-US"]))@@ -74,7 +74,7 @@ class HeadlessUserAgentTests(unittest.TestCase):raise RuntimeError("no browser")manager = BrowserManager()- with mock.patch.object(browser_manager_module.uc, "start", side_effect=failing_start):+ with mock.patch.object(browser_manager_module, "launch_browser", side_effect=failing_start):self.assertIsNone(asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, [])))self.assertIsNone(asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, [])))self.assertEqual(len(calls), 2)@@ -84,7 +84,7 @@ class HeadlessUserAgentTests(unittest.TestCase):return FakeBrowser(CLEAN_UA)manager = BrowserManager()- with mock.patch.object(browser_manager_module.uc, "start", side_effect=fake_start) as start, mock.patch.object(+ with mock.patch.object(browser_manager_module, "launch_browser", side_effect=fake_start) as start, mock.patch.object(browser_manager_module, "process_cleanup", mock.Mock()):self.assertIsNone(asyncio.run(manager._resolve_headless_user_agent("/missing/chrome", True, [])))diff --git a/tests/test_platform_sandbox.py b/tests/test_platform_sandbox.pynew file mode 100644index 0000000..0d9fa38--- /dev/null+++ b/tests/test_platform_sandbox.py@@ -0,0 +1,49 @@+import sys+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "src"))++import platform_utils+++def environment(system, root, container):+ return (+ mock.patch.object(platform_utils.platform, "system", return_value=system),+ mock.patch.object(platform_utils, "is_running_as_root", return_value=root),+ mock.patch.object(platform_utils, "is_running_in_container", return_value=container),+ )+++class SandboxRuleTests(unittest.TestCase):+ def check(self, system, root, container):+ patches = environment(system, root, container)+ with patches[0], patches[1], patches[2]:+ return platform_utils.sandbox_must_be_disabled(), platform_utils.get_required_sandbox_args()++ def test_windows_admin_keeps_sandbox(self):+ self.assertEqual(self.check("Windows", True, False), (False, []))++ def test_macos_keeps_sandbox(self):+ self.assertEqual(self.check("Darwin", True, False), (False, []))++ def test_linux_root_or_container_disables_sandbox_only(self):+ self.assertEqual(self.check("Linux", True, False), (True, ["--no-sandbox"]))+ self.assertEqual(self.check("Linux", False, True), (True, ["--no-sandbox"]))++ def test_linux_user_keeps_sandbox(self):+ self.assertEqual(self.check("Linux", False, False), (False, []))++ def test_merge_never_adds_warning_flags(self):+ patches = environment("Linux", True, True)+ with patches[0], patches[1], patches[2]:+ merged = platform_utils.merge_browser_args(["--lang=en-US"])+ self.assertEqual(merged, ["--lang=en-US", "--no-sandbox"])+ for flag in ("--disable-setuid-sandbox", "--single-process", "--disable-gpu"):+ self.assertNotIn(flag, merged)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_stealth_benchmark.py b/tests/test_stealth_benchmark.pyindex 05e6f5f..df48aae 100644--- a/tests/test_stealth_benchmark.py+++ b/tests/test_stealth_benchmark.py@@ -39,6 +39,7 @@ from benchmarks.stealth.targets.local_probe import (platform_matches,)from benchmarks.stealth.targets.input_fidelity import TYPED_TEXT, InputFidelityTarget+from benchmarks.stealth.targets.launch_flags import LaunchFlagsTargetfrom benchmarks.stealth.targets.result_tables import SannysoftTargetfrom benchmarks.stealth.targets.tls_fingerprint import (CHROME_AKAMAI_FINGERPRINT,@@ -203,6 +204,15 @@ class TargetEvaluationTests(unittest.TestCase):inconsistent = probe_payload(notificationPermission="denied", permissionQuery="prompt")self.assertEqual(status_from_checks(target.evaluate(inconsistent)[0]), Status.FAIL)+ def test_launch_flags(self):+ target = LaunchFlagsTarget()+ clean = ["--no-first-run", "--remote-debugging-port=51234", "--headless=new"]+ self.assertEqual(status_from_checks(target.evaluate({"arguments": clean})[0]), Status.PASS)+ for flag in ("--no-sandbox", "--disable-setuid-sandbox", "--remote-debugging-port=0", "--enable-automation"):+ checks = target.evaluate({"arguments": clean + [flag]})[0]+ self.assertEqual(status_from_checks(checks), Status.FAIL, flag)+ self.assertEqual(status_from_checks(target.evaluate({"arguments": clean + ["--disable-gpu"]})[0]), Status.DEGRADED)+def test_input_fidelity(self):def events(trusted=True):recorded = [@@ -250,7 +260,7 @@ class TargetEvaluationTests(unittest.TestCase):def test_select_targets(self):self.assertEqual([t.name for t in select_targets(["tls", "local_probe"])], ["local_probe", "tls"])- self.assertEqual(len(select_targets()), 8)+ self.assertEqual(len(select_targets()), 9)with self.assertRaises(ValueError):select_targets(["missing"])