Skip to content

Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.

feat(cloakserve): exit after a period with no CDP connections (#616)

bercee51f07780355
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8facbc8..4f2f1a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,10 @@ Changes are tagged: **[wrapper]** for Python/JS wrapper, **[binary]** for Chromi
---
+## [Unreleased]
+
+- **[wrapper]** `cloakserve --exit-after-idle=SECONDS` (or `CLOAKSERVE_EXIT_AFTER_IDLE`) shuts the server down with exit status 0 once no CDP connection has been open for that long, so a per-job container stops when its work is done (#572)
+
## [0.6.4] — 2026-10-23
- **[wrapper]** .NET: the package is now built against Microsoft.Playwright 1.64.1 (was 1.49.0). The humanize wrappers are generated from the Playwright interfaces at build time, so with a newer Playwright loaded, `Humanize.PageAsync` and the humanized launches failed with `TypeLoadException: Method '...' does not have an implementation`. Your project needs Microsoft.Playwright 1.64.1 or newer. .NET only.
diff --git a/README.md b/README.md
index 3f02316..6b0b8e2 100644
--- a/README.md
+++ b/README.md
@@ -1011,6 +1011,8 @@ Supported query params: `fingerprint`, `timezone`, `locale`, `platform`, `platfo
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).
+For a server that runs one job and goes away (e.g. a per-job container), set `--exit-after-idle=SECONDS` or `CLOAKSERVE_EXIT_AFTER_IDLE=SECONDS`: `cloakserve` shuts down with exit status 0 once no CDP WebSocket has been connected for that long, counted from startup if nobody connects. It is off by default and takes the same disable values as `--idle-timeout`.
+
**Persistent profiles** — mount a volume to keep cookies and sessions across container restarts:
```bash
diff --git a/bin/cloakserve b/bin/cloakserve
index e5c1f99..0b3a80e 100755
--- a/bin/cloakserve
+++ b/bin/cloakserve
@@ -200,6 +200,7 @@ class ChromePool:
self._next_port = BASE_CDP_PORT
# Connection refcounting for status reporting
self._connections: dict[str, int] = {}
+ self._last_activity = time.monotonic()
self._idle_tasks: dict[str, asyncio.Task] = {}
def _get_lock(self, seed: str) -> asyncio.Lock:
@@ -235,10 +236,12 @@ class ChromePool:
def connect(self, seed_key: str) -> None:
"""Increment connection refcount for a seed."""
self._cancel_idle_cleanup(seed_key)
+ self._last_activity = time.monotonic()
self._connections[seed_key] = self._connections.get(seed_key, 0) + 1
def disconnect(self, seed_key: str) -> None:
"""Decrement connection refcount for a seed."""
+ self._last_activity = time.monotonic()
count = self._connections.get(seed_key, 0) - 1
if count <= 0:
self._connections.pop(seed_key, None)
@@ -798,21 +801,32 @@ def _default_data_dir() -> str:
return str(Path.home() / ".cloakbrowser" / "cloakserve")
-def _parse_idle_timeout(value: str) -> float:
+def _parse_idle_timeout(value: str, flag: str = "--idle-timeout") -> float:
value = value.strip()
if value.lower() in {"0", "false", "off", "none", "disabled"}:
return 0.0
timeout = float(value)
if timeout < 0:
- raise ValueError("--idle-timeout must be greater than or equal to 0")
+ raise ValueError(f"{flag} must be greater than or equal to 0")
return timeout
-def _default_idle_timeout() -> float:
- value = os.environ.get("CLOAKSERVE_IDLE_TIMEOUT")
+def _default_idle_timeout(env: str = "CLOAKSERVE_IDLE_TIMEOUT", flag: str = "--idle-timeout") -> float:
+ value = os.environ.get(env)
if value is None:
return 0.0
- return _parse_idle_timeout(value)
+ return _parse_idle_timeout(value, flag)
+
+
+async def _exit_after_idle(pool: ChromePool, timeout: float) -> None:
+ """Stop the server once no CDP connection has been open for `timeout` seconds."""
+ while True:
+ if not pool._connections and time.monotonic() - pool._last_activity >= timeout:
+ logger.info("No CDP connections for %gs, exiting", timeout)
+ # run_app treats SIGINT as its normal shutdown (Chrome cleanup, exit status 0), Windows included
+ signal.raise_signal(signal.SIGINT)
+ return
+ await asyncio.sleep(min(timeout, 1.0))
def parse_cli_args(argv: list[str]) -> tuple[dict, list[str]]:
@@ -832,6 +846,7 @@ def parse_cli_args(argv: list[str]) -> tuple[dict, list[str]]:
"default_timezone": None,
"idle_timeout": _default_idle_timeout(),
"keep_profiles": False,
+ "exit_after_idle": _default_idle_timeout("CLOAKSERVE_EXIT_AFTER_IDLE", "--exit-after-idle"),
}
passthrough = []
# Flags consumed by cloakserve (not passed to Chrome)
@@ -839,6 +854,7 @@ def parse_cli_args(argv: list[str]) -> tuple[dict, list[str]]:
"--port=",
"--data-dir=",
"--idle-timeout=",
+ "--exit-after-idle=",
"--remote-debugging-port=",
"--remote-debugging-address=",
)
@@ -852,6 +868,8 @@ def parse_cli_args(argv: list[str]) -> tuple[dict, list[str]]:
config["idle_timeout"] = _parse_idle_timeout(arg.split("=", 1)[1])
elif arg == "--keep-profiles":
config["keep_profiles"] = True
+ elif arg.startswith("--exit-after-idle="):
+ config["exit_after_idle"] = _parse_idle_timeout(arg.split("=", 1)[1], "--exit-after-idle")
elif arg == "--headless=false" or arg == "--headless=False":
config["headless"] = False
passthrough.append(arg)
@@ -921,6 +939,12 @@ def main() -> None:
app.on_shutdown.append(on_shutdown)
+ if config["exit_after_idle"] > 0:
+ async def start_exit_watch(app: web.Application) -> None:
+ app["exit_watch"] = asyncio.create_task(_exit_after_idle(pool, config["exit_after_idle"]))
+
+ app.on_startup.append(start_exit_watch)
+
port = config["port"]
logger.info("CloakBrowser CDP multiplexer starting on port %d", port)
logger.info(
diff --git a/tests/test_cloakserve.py b/tests/test_cloakserve.py
index 8d68c54..a25f5b4 100644
--- a/tests/test_cloakserve.py
+++ b/tests/test_cloakserve.py
@@ -163,6 +163,17 @@ class TestParseCliArgs:
with pytest.raises(ValueError):
parse_cli_args(["--idle-timeout=-1"])
+ def test_exit_after_idle(self, monkeypatch):
+ monkeypatch.delenv("CLOAKSERVE_EXIT_AFTER_IDLE", raising=False)
+ assert parse_cli_args([])[0]["exit_after_idle"] == 0.0
+ config, passthrough = parse_cli_args(["--exit-after-idle=30", "--no-sandbox"])
+ assert config["exit_after_idle"] == 30.0
+ assert passthrough == ["--no-sandbox"]
+ monkeypatch.setenv("CLOAKSERVE_EXIT_AFTER_IDLE", "off")
+ assert parse_cli_args([])[0]["exit_after_idle"] == 0.0
+ with pytest.raises(ValueError, match="--exit-after-idle"):
+ parse_cli_args(["--exit-after-idle=-1"])
+
@patch("os.path.exists", return_value=True)
def test_default_data_dir_docker(self, _mock):
assert _default_data_dir() == "/tmp/cloakserve"
@@ -536,6 +547,21 @@ class TestConnectionTracking:
assert pool._connections["a"] == 1
assert pool._connections["b"] == 1
+ def test_exit_after_idle_waits_for_last_connection(self):
+ async def run():
+ pool = self._make_pool()
+ pool.connect("seed1")
+ with patch.object(_mod.signal, "raise_signal") as raise_signal:
+ watch = asyncio.create_task(_mod._exit_after_idle(pool, 0.02))
+ await asyncio.sleep(0.06)
+ raise_signal.assert_not_called()
+
+ pool.disconnect("seed1")
+ await asyncio.wait_for(watch, 1)
+ raise_signal.assert_called_once_with(_mod.signal.SIGINT)
+
+ asyncio.run(run())
+
def test_idle_cleanup_disabled_by_default(self):
async def run():
pool = self._make_pool()