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
fix: keep sync Playwright responsive during time.sleep() on Windows
CloakHQ4b2422fd3ee6
diff --git a/cloakbrowser/browser.py b/cloakbrowser/browser.pyindex 51cd9b8..494e5a9 100644--- a/cloakbrowser/browser.py+++ b/cloakbrowser/browser.py@@ -19,6 +19,8 @@ import inspectimport loggingimport osimport sys+import threading+import timefrom typing import Any, Literal, TypedDictfrom urllib.parse import quote, unquote, urlparse, urlunparse@@ -43,6 +45,44 @@ from .widevine import seed_widevine_hintlogger = logging.getLogger("cloakbrowser")+# The sync Playwright client only processes the browser's messages while one of+# its calls is running. A long time.sleep() leaves it idle, and on Windows that+# stalls pages: a Cloudflare challenge stays on "Verifying" until the script's+# next Playwright call. So while a sync browser is open, time.sleep() on its+# thread waits inside Playwright's own event loop, the same wait the async API+# does. Shorter sleeps (humanize's keystroke and mouse pacing) keep the real one.+_real_sleep = time.sleep+_SLEEP_PUMP_MIN_S = 0.1+_sleep_owners: dict[int, list[Any]] = {} # thread id -> open sync browsers/contexts+++def _pumping_sleep(seconds: float) -> None:+ owners = _sleep_owners.get(threading.get_ident())+ if owners and isinstance(seconds, (int, float)) and seconds >= _SLEEP_PUMP_MIN_S:+ owner = owners[-1]+ try:+ owner._sync(asyncio.sleep(seconds))+ return+ except Exception as exc:+ logger.warning("time.sleep could not wait in the Playwright loop, using a plain sleep: %s", exc)+ _untrack_sleep_owner(owner)+ _real_sleep(seconds)+++def _track_sleep_owner(owner: Any) -> None:+ _sleep_owners.setdefault(threading.get_ident(), []).append(owner)+ if time.sleep is _real_sleep:+ time.sleep = _pumping_sleep+++def _untrack_sleep_owner(owner: Any) -> None:+ for tid, owners in list(_sleep_owners.items()):+ owners[:] = [o for o in owners if o is not owner]+ if not owners:+ del _sleep_owners[tid]+ if not _sleep_owners and time.sleep is _pumping_sleep:+ time.sleep = _real_sleep+def license_error_from(exc: BaseException, launch_options: dict[str, Any] | None = None@@ -560,9 +600,11 @@ def launch(else:_original_close(reason=reason)finally:+ _untrack_sleep_owner(browser)pw.stop()browser.close = _close_with_cleanup+ _track_sleep_owner(browser)# Convert a post-handshake license denial into a clear error on the user's# first call. Installed before the wraps below so it sits closest to the@@ -822,9 +864,11 @@ def launch_persistent_context(else:_original_close(reason=reason)finally:+ _untrack_sleep_owner(context)pw.stop()context.close = _close_with_cleanup+ _track_sleep_owner(context)# Warn on first use of Playwright's request client (see launch(), #579).if proxy is not None and "proxy" not in launch_options:diff --git a/tests/conftest.py b/tests/conftest.pyindex 09542e1..46e0132 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,7 +1,22 @@"""Shared pytest fixtures."""+import time+import pytest+_ORIGINAL_SLEEP = time.sleep++[email protected](autouse=True)+def restore_time_sleep():+ """Mocked launches are rarely closed, which would leave time.sleep patched+ for every later test. Drop all tracked sync browsers after each test."""+ yield+ from cloakbrowser import browser++ browser._sleep_owners.clear()+ time.sleep = _ORIGINAL_SLEEP+@pytest.fixture(autouse=True)def isolated_cache_dir(request, tmp_path_factory, monkeypatch):diff --git a/tests/test_sleep_pump.py b/tests/test_sleep_pump.pynew file mode 100644index 0000000..b2df925--- /dev/null+++ b/tests/test_sleep_pump.py@@ -0,0 +1,84 @@+"""time.sleep() while a sync browser is open waits inside Playwright's event loop."""++import asyncio+import threading+import time+from unittest.mock import MagicMock, patch++import cloakbrowser.browser as b+from cloakbrowser import launch+++class FakeOwner:+ """Stands in for a sync Browser/BrowserContext: _sync runs the coroutine."""++ def __init__(self):+ self.calls = 0++ def _sync(self, coro):+ self.calls += 1+ return asyncio.run(coro)+++def test_long_sleep_runs_in_playwright_loop():+ owner = FakeOwner()+ b._track_sleep_owner(owner)+ with patch.object(b, "_real_sleep") as real:+ time.sleep(0.1)+ assert owner.calls == 1+ real.assert_not_called()+++def test_short_sleep_keeps_real_sleep():+ owner = FakeOwner()+ b._track_sleep_owner(owner)+ with patch.object(b, "_real_sleep") as real:+ time.sleep(0.05)+ assert owner.calls == 0+ real.assert_called_once_with(0.05)+++def test_other_thread_keeps_real_sleep():+ owner = FakeOwner()+ b._track_sleep_owner(owner)+ with patch.object(b, "_real_sleep") as real:+ t = threading.Thread(target=time.sleep, args=(0.2,))+ t.start()+ t.join()+ assert owner.calls == 0+ real.assert_called_once_with(0.2)+++def test_untrack_restores_time_sleep():+ owner = FakeOwner()+ b._track_sleep_owner(owner)+ assert time.sleep is b._pumping_sleep+ b._untrack_sleep_owner(owner)+ assert time.sleep is b._real_sleep+++def test_dead_loop_falls_back_to_real_sleep(caplog):+ owner = MagicMock()+ owner._sync.side_effect = _closed_loop+ b._track_sleep_owner(owner)+ with patch.object(b, "_real_sleep") as real:+ time.sleep(0.3)+ real.assert_called_once_with(0.3)+ assert "Event loop is closed" in caplog.text+ assert b._sleep_owners == {} # the dead owner was dropped+++def _closed_loop(coro):+ coro.close()+ raise RuntimeError("Event loop is closed")+++@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")+@patch("playwright.sync_api.sync_playwright")+def test_launch_tracks_until_close(mock_sync_playwright, _):+ mock_pw = MagicMock()+ mock_sync_playwright.return_value.start.return_value = mock_pw+ browser = launch()+ assert time.sleep is b._pumping_sleep+ browser.close()+ assert time.sleep is b._real_sleep