Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.
Python ai-agentsanti-detectantidetect-browserbot-detectionbrowser-automationcaptcha-bypasschromiumcloudflarecloudflare-bypassfingerprintheadless-browserplaywrightpuppeteerpythonrecaptchaseleniumstealth-browserundetectedweb-scrapingwebscraping
feat(cloakserve): add --keep-profiles and stop Chrome with SIGINT on cleanup
CloakHQebe06e449655
diff --git a/README.md b/README.mdindex 71f9bb5..3f02316 100644--- a/README.md+++ b/README.md@@ -959,6 +959,10 @@ docker run -d --name cloak -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \# Reap disconnected per-seed browser processes after 5 minutesdocker run -d --name cloak -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \cloakserve --idle-timeout=300++# Keep per-seed profiles (cookies, logins) across idle cleanup and container restarts+docker run -d --name cloak -p 127.0.0.1:9222:9222 -v ./cloak-profiles:/profiles cloakhq/cloakbrowser \+ cloakserve --idle-timeout=300 --data-dir=/profiles --keep-profiles```Stop the server:@@ -1005,7 +1009,7 @@ b3 = pw.chromium.connect_over_cdp(Supported query params: `fingerprint`, `timezone`, `locale`, `platform`, `platform-version`, `gpu-vendor`, `hardware-concurrency`, `device-memory`, `screen-width`, `screen-height`, `proxy`, `geoip`. Same seed reuses the same process (first connection's params win). No seed = shared default process (backward compatible).-By default, per-seed processes stay alive until `cloakserve` exits; idle cleanup is disabled (`0`). If clients create many unique seeds, set `--idle-timeout=SECONDS` or `CLOAKSERVE_IDLE_TIMEOUT=SECONDS` to automatically terminate a seed's Chrome process after its last CDP WebSocket disconnects. `0`, `off`, `false`, `none`, or `disabled` disable idle cleanup. When cleanup runs, the seed's temporary profile directory under `--data-dir` is removed too. Check active processes at `GET /` (returns JSON with PIDs, ports, connection counts, idle timeout, and pending cleanup status).+By default, per-seed processes stay alive until `cloakserve` exits; idle cleanup is disabled (`0`). If clients create many unique seeds, set `--idle-timeout=SECONDS` or `CLOAKSERVE_IDLE_TIMEOUT=SECONDS` to automatically terminate a seed's Chrome process after its last CDP WebSocket disconnects. `0`, `off`, `false`, `none`, or `disabled` disable idle cleanup. When cleanup runs, the seed's temporary profile directory under `--data-dir` is removed too, unless you pass `--keep-profiles` (the profile then survives, and reopening the seed restores its cookies and logins). Check active processes at `GET /` (returns JSON with PIDs, ports, connection counts, idle timeout, and pending cleanup status).**Persistent profiles** — mount a volume to keep cookies and sessions across container restarts:diff --git a/bin/cloakserve b/bin/cloakserveindex 27ea917..f516981 100755--- a/bin/cloakserve+++ b/bin/cloakserve@@ -25,6 +25,7 @@ import osimport randomimport reimport shutil+import signalimport socketimport subprocessimport sys@@ -182,7 +183,9 @@ class ChromePool:default_locale: str | None = None,default_timezone: str | None = None,idle_timeout: float = 0.0,+ keep_profiles: bool = False,):+ self._keep_profiles = keep_profilesself._binary = binaryself._global_args = global_argsself._headless = headless@@ -205,6 +208,10 @@ class ChromePool:return self._locks[seed]def _safe_rmtree(self, path: str) -> None:+ # --keep-profiles: a seed's profile (cookies, logins) outlives its Chrome+ # process, so reopening the seed after close/idle restores the identity.+ if self._keep_profiles:+ returnresolved = Path(path).resolve()data_resolved = Path(self._data_dir).resolve()if resolved == data_resolved or not resolved.is_relative_to(data_resolved):@@ -418,9 +425,16 @@ class ChromePool:if not proc:returnif proc.process.poll() is None:- proc.process.terminate()+ # Linux Chrome treats SIGTERM as session end and exits without writing+ # its cookie store; SIGINT takes the normal exit path, which does.+ if sys.platform == "win32":+ proc.process.terminate()+ else:+ proc.process.send_signal(signal.SIGINT)try:- await asyncio.to_thread(proc.process.wait, timeout=5)+ # The binary's /session/end on exit is bounded at 9s; killing+ # sooner can leave the seat held until its TTL.+ await asyncio.to_thread(proc.process.wait, timeout=10)except subprocess.TimeoutExpired:proc.process.kill()await asyncio.to_thread(self._safe_rmtree, proc.user_data_dir)@@ -811,6 +825,7 @@ def parse_cli_args(argv: list[str]) -> tuple[dict, list[str]]:"default_locale": None,"default_timezone": None,"idle_timeout": _default_idle_timeout(),+ "keep_profiles": False,}passthrough = []# Flags consumed by cloakserve (not passed to Chrome)@@ -829,6 +844,8 @@ def parse_cli_args(argv: list[str]) -> tuple[dict, list[str]]:config["data_dir"] = arg.split("=", 1)[1]elif arg.startswith("--idle-timeout="):config["idle_timeout"] = _parse_idle_timeout(arg.split("=", 1)[1])+ elif arg == "--keep-profiles":+ config["keep_profiles"] = Trueelif arg == "--headless=false" or arg == "--headless=False":config["headless"] = Falsepassthrough.append(arg)@@ -874,6 +891,7 @@ def main() -> None:default_locale=config["default_locale"],default_timezone=config["default_timezone"],idle_timeout=config["idle_timeout"],+ keep_profiles=config["keep_profiles"],)app = web.Application()diff --git a/tests/test_cloakserve.py b/tests/test_cloakserve.pyindex 7be64cb..66b91c5 100644--- a/tests/test_cloakserve.py+++ b/tests/test_cloakserve.py@@ -132,6 +132,12 @@ class TestParseCliArgs:_, passthrough = parse_cli_args(["--data-dir=/tmp/test"])assert not any(a.startswith("--data-dir=") for a in passthrough)+ def test_keep_profiles_flag(self):+ config, passthrough = parse_cli_args(["--keep-profiles", "--no-sandbox"])+ assert config["keep_profiles"] is True+ assert "--keep-profiles" not in passthrough+ assert parse_cli_args([])[0]["keep_profiles"] is False+def test_idle_timeout_not_in_passthrough(self):config, passthrough = parse_cli_args(["--idle-timeout=30", "--no-sandbox"])assert config["idle_timeout"] == 30.0@@ -474,6 +480,28 @@ class TestConnectionTracking:process=SimpleNamespace(poll=lambda: None),)+ @pytest.mark.parametrize("platform", ["linux", "darwin", "win32"])+ def test_cleanup_stops_chrome_without_session_ending(self, platform):+ # Linux Chrome treats SIGTERM as session end and skips the cookie-store+ # write, so cleanup must use SIGINT off Windows.+ pool = self._make_pool()+ proc = MagicMock()+ proc.poll.return_value = None+ pool._processes["seed1"] = SimpleNamespace(process=proc, user_data_dir="/tmp/x")+ pool._safe_rmtree = lambda path: None++ with patch.object(_mod.sys, "platform", platform):+ asyncio.run(pool._cleanup_process("seed1"))++ if platform == "win32":+ proc.terminate.assert_called_once_with()+ proc.send_signal.assert_not_called()+ else:+ proc.send_signal.assert_called_once_with(_mod.signal.SIGINT)+ proc.terminate.assert_not_called()+ # Room for the binary's bounded /session/end (up to 9s) before kill()+ proc.wait.assert_called_once_with(timeout=10)+def test_connect_increments(self):pool = self._make_pool()pool.connect("seed1")@@ -684,6 +712,21 @@ class TestSafeRmtree:assert not subdir.exists(), "Valid subdirectory should be deleted"+ def test_keep_profiles_keeps_subdirectory(self, tmp_path):+ data_dir = tmp_path / "profiles"+ data_dir.mkdir()+ subdir = data_dir / "seed-12345"+ subdir.mkdir()+ (subdir / "Cookies").touch()++ pool = ChromePool(+ binary="/fake/chrome", global_args=[], headless=True,+ data_dir=str(data_dir), keep_profiles=True,+ )+ pool._safe_rmtree(str(subdir))++ assert (subdir / "Cookies").exists(), "--keep-profiles must keep the profile"+def test_refuses_traversal_path(self, tmp_path):data_dir = tmp_path / "profiles"data_dir.mkdir()