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: license helpers for your own Playwright, persistent launch reuses build_launch_options
CloakHQ74905e1a1e82
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a050e14..15386ef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,12 @@ Changes are tagged: **[wrapper]** for Python/JS wrapper, **[binary]** for Chromi---+## [Unreleased]++- **[wrapper]** Launch with your own Playwright instance: `build_launch_options()` (JS `buildLaunchOptions()`, .NET `CloakLauncher.BuildLaunchOptionsAsync()`) returns the options `launch()` uses, so `pw.chromium.launch(**build_launch_options())` needs no copy of `launch()`. `humanize_browser()` / `humanize_browser_async()` apply the humanize layer to that browser. Python and .NET (JS had `buildLaunchOptions()` since 0.3.29) (#153, #255)+- **[wrapper]** Clear license errors for browsers you launch yourself: `guard_browser()` (JS `guardBrowser()`, .NET `CloakLauncher.GuardBrowser()`) turns a license denial after launch, like a full session limit, into `CloakBrowserLicenseError` instead of a bare "Target closed" error, and `license_error_from(e, opts)` (JS `licenseErrorFrom()`, .NET `CloakLauncher.LicenseErrorFrom()`) does the same for a denial during launch. Python, JavaScript, and .NET+- **[wrapper]** `license_denial(browser_or_context)` (JS `licenseDenial()`, .NET `LicenseDenial()` on the launch handles) reports whether the license refused a browser, without making a browser call. Works on everything the launch functions return, including Puppeteer browsers in JS. Python, JavaScript, and .NET+## [0.7.0] — 2026-11-01**Breaking: every launch now needs a license key.** A free key takes one email and gets the latest build (1 concurrent session). The old keyless v146 build is no longer downloaded. To keep running it without a key, stay on the 0.6 wrapper: `pip install "cloakbrowser<0.7"`, `npm install [email protected]`, `dotnet add package CloakBrowser --version 0.6.5`, or the Docker image `cloakhq/cloakbrowser:0.6.5`.diff --git a/README.md b/README.mdindex 00eb9a8..dfeadb3 100644--- a/README.md+++ b/README.md@@ -1392,6 +1392,7 @@ Issues and PRs welcome. If something isn't working, [open an issue](https://gith- [@pujitha24](https://github.com/pujitha24) — cloakserve WebSocket heartbeat for vanished clients- [@w21180239](https://github.com/w21180239) — Playwright-compatible `context.close(reason=...)`- [@alkaz-nodemaven](https://github.com/alkaz-nodemaven) — GeoIP private proxy address fix+- [@mvanhorn](https://github.com/mvanhorn) — Python `build_launch_options()` for your own Playwright instance## Star Historydiff --git a/cloakbrowser/__init__.py b/cloakbrowser/__init__.pyindex 0c63bcb..8beca06 100644--- a/cloakbrowser/__init__.py+++ b/cloakbrowser/__init__.py@@ -11,7 +11,7 @@ Usage:browser.close()"""-from .browser import launch, launch_async, launch_context, launch_context_async, launch_persistent_context, launch_persistent_context_async, ProxySettings, build_args, build_launch_options, humanize_browser, humanize_browser_async, maybe_resolve_geoip+from .browser import launch, launch_async, launch_context, launch_context_async, launch_persistent_context, launch_persistent_context_async, ProxySettings, build_args, build_launch_options, guard_browser, guard_browser_async, humanize_browser, humanize_browser_async, license_denial, license_error_from, maybe_resolve_geoipfrom .config import get_default_stealth_argsfrom .download import binary_info, clear_cache, ensure_binaryfrom .license import CloakBrowserLicenseError, LicenseInfo, validate_license@@ -42,8 +42,12 @@ __all__ = ["get_default_stealth_args","build_args","build_launch_options",+ "guard_browser",+ "guard_browser_async","humanize_browser","humanize_browser_async",+ "license_denial",+ "license_error_from","maybe_resolve_geoip","ProxySettings","validate_license",diff --git a/cloakbrowser/browser.py b/cloakbrowser/browser.pyindex 16b3849..51cd9b8 100644--- a/cloakbrowser/browser.py+++ b/cloakbrowser/browser.py@@ -29,6 +29,7 @@ from .config import ()from .download import ensure_binaryfrom .license import (+ LICENSE_STATUS_FILE_ENV,CloakBrowserLicenseError,build_launch_env,license_error_for_code,@@ -43,15 +44,25 @@ from .widevine import seed_widevine_hintlogger = logging.getLogger("cloakbrowser")-def _license_error(exc: BaseException) -> CloakBrowserLicenseError | None:+def license_error_from(+ exc: BaseException, launch_options: dict[str, Any] | None = None+) -> CloakBrowserLicenseError | None:"""Return a CloakBrowserLicenseError if a launch failure was a license deny.+ For callers launching with build_launch_options(): a denial during launch+ fails pw.chromium.launch() itself, before guard_browser() can run.+The Pro binary exits with a distinct code (76-79) on a license problem;- Playwright embeds that code in the launch-failure text. Returns None for any- other failure so a genuine crash propagates unchanged.+ Playwright embeds that code in the launch-failure text. When the text has no+ code, falls back to the denial file named in *launch_options* (the binary+ writes the same code there), like the JS and .NET wrappers. Returns None for+ any other failure so a genuine crash propagates unchanged."""msg = license_error_message(str(exc))- return CloakBrowserLicenseError(msg) if msg is not None else None+ if msg is not None:+ return CloakBrowserLicenseError(msg)+ denial_path = _denial_path_from(launch_options) if launch_options else None+ return _denial_license_error(denial_path) if denial_path else None# Factory methods whose return value is itself a handle the user drives (a page@@ -274,6 +285,24 @@ def _drop_conflicting_viewport(context_kwargs: dict[str, Any], kwargs: dict[str,context_kwargs.pop("viewport", None)+def _context_kwargs(+ user_agent: str | None, viewport: Any, color_scheme: str | None, kwargs: dict[str, Any]+) -> dict[str, Any]:+ """Context kwargs for launch_context() / launch_persistent_context(). locale and+ timezone are NOT here: they go to the binary as flags (--lang,+ --fingerprint-timezone), since Playwright's context options use detectable CDP+ emulation."""+ context_kwargs: dict[str, Any] = {}+ if user_agent:+ context_kwargs["user_agent"] = user_agent+ context_kwargs.update(_resolve_context_viewport(viewport))+ if color_scheme:+ context_kwargs["color_scheme"] = color_scheme+ context_kwargs.update(kwargs)+ _drop_conflicting_viewport(context_kwargs, kwargs)+ return context_kwargs++def _resolve_timezone(timezone: str | None, kwargs: dict[str, Any]) -> str | None:"""Accept both timezone and timezone_id — either works, no warning."""if "timezone_id" in kwargs:@@ -318,14 +347,22 @@ def build_launch_options(browser_version: str | None = None,release_channel: str | None = None,_suppress_maximize: bool = False,- _status_file: str | None = None,**kwargs: Any,) -> dict[str, Any]:"""Build the kwargs dict that ``launch()`` passes to ``chromium.launch()``.Use this when you already manage a Playwright instance and want to composeCloakBrowser's binary, proxy, environment, and stealth arguments yourself:- ``pw.chromium.launch(**build_launch_options(...))``.+ ``pw.chromium.launch(**build_launch_options(...))``. A license denial (e.g.+ over the session cap) can land during launch or after it; to get+ ``CloakBrowserLicenseError`` instead of a bare "Target closed" error::++ opts = build_launch_options(...)+ try:+ browser = pw.chromium.launch(**opts)+ except Exception as e:+ raise license_error_from(e, opts) or e+ guard_browser(browser, opts)"""_check_removed_kwargs(kwargs)@@ -348,9 +385,9 @@ def build_launch_options()_maybe_warn_windows_fonts(chrome_args)- denial_path = _status_file- if denial_path is None and resolve_license_key(license_key):- denial_path = mint_denial_file()+ # The binary writes its license exit code here on a denial; guard_browser()+ # reads the path back from the env.+ denial_path = mint_denial_file() if resolve_license_key(license_key) else Nonelaunch_env = build_launch_env(license_key, user_env=kwargs.pop("env", None), status_file=denial_path)@@ -367,6 +404,41 @@ def build_launch_options(}+def _denial_path_from(launch_options: dict[str, Any]) -> str | None:+ return (launch_options.get("env") or {}).get(LICENSE_STATUS_FILE_ENV)+++def guard_browser(browser: Any, launch_options: dict[str, Any]) -> None:+ """Make a license denial on a sync Browser you launched yourself raise+ CloakBrowserLicenseError (e.g. "session limit reached") instead of a bare+ TargetClosedError. Pass the dict build_launch_options() returned. Call it+ before humanize_browser(). No-op when no license key was in play.+ """+ denial_path = _denial_path_from(launch_options)+ if denial_path:+ browser._cloak_denial_path = denial_path+ _install_license_guard(browser, denial_path)+++def guard_browser_async(browser: Any, launch_options: dict[str, Any]) -> None:+ """Async-API variant of :func:`guard_browser`."""+ denial_path = _denial_path_from(launch_options)+ if denial_path:+ browser._cloak_denial_path = denial_path+ _install_license_guard_async(browser, denial_path)+++def license_denial(obj: Any) -> CloakBrowserLicenseError | None:+ """Return why the license refused this browser/context (e.g. "session limit+ reached"), or None. Checks now, without making a browser call: useful while+ waiting on something else, like a CDP endpoint. Works on anything launch(),+ launch_context(), launch_persistent_context() or guard_browser() handed back+ (sync or async). Safe to call repeatedly.+ """+ denial_path = getattr(obj, "_cloak_denial_path", None)+ return _denial_license_error(denial_path) if denial_path else None++def humanize_browser(browser: Any,human_preset: HumanPreset = "default",@@ -445,11 +517,8 @@ def launch(>>> print(page.title())>>> browser.close()"""- _check_removed_kwargs(kwargs)-from playwright.sync_api import sync_playwright- denial_path = mint_denial_file() if resolve_license_key(license_key) else Nonelaunch_options = build_launch_options(headless=headless,proxy=proxy,@@ -463,21 +532,16 @@ def launch(browser_version=browser_version,release_channel=release_channel,_suppress_maximize=_suppress_maximize,- _status_file=denial_path,**kwargs,)- # build_launch_options() folded proxy_extra_args into the args; recompute them- # for the request-client warning below (#579).- _, proxy_extra_args = _resolve_proxy_config(proxy)-logger.debug("Launching stealth Chromium (headless=%s, args=%d)", headless, len(launch_options["args"]))pw = sync_playwright().start()try:browser = pw.chromium.launch(**launch_options)except Exception as exc:- lic = _license_error(exc)+ lic = license_error_from(exc, launch_options)try:pw.stop()except Exception as stop_exc:@@ -502,15 +566,14 @@ def launch(# 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- # real call. Stash the path so launch_context() can guard its context too.- if denial_path:- browser._cloak_denial_path = denial_path- _install_license_guard(browser, denial_path)+ # real call. Stashes the path so launch_context() can guard its context too.+ guard_browser(browser, launch_options)- # Proxy went to Chrome as --proxy-server, so Playwright's request client has no+ # Proxy went to Chrome as --proxy-server (any proxy not in Playwright's proxy+ # option, see _resolve_proxy_config), so Playwright's request client has no# proxy (#579). The impl "context" event fires for every new context,# including the one new_page() and launch_context() create internally.- if proxy_extra_args:+ if proxy is not None and "proxy" not in launch_options:browser._impl_obj.on("context", _warn_on_request_client_use)# Default new_page()/new_context() to no_viewport: headed, the page tracks the@@ -575,11 +638,8 @@ async def launch_async( # noqa: C901>>>>>> asyncio.run(main())"""- _check_removed_kwargs(kwargs)-from playwright.async_api import async_playwright- denial_path = mint_denial_file() if resolve_license_key(license_key) else None# Blocking network calls (license/download, exit-IP lookups) run in a thread so# they don't freeze the caller's event loop.launch_options = await asyncio.to_thread(@@ -596,21 +656,16 @@ async def launch_async( # noqa: C901browser_version=browser_version,release_channel=release_channel,_suppress_maximize=_suppress_maximize,- _status_file=denial_path,**kwargs,)- # build_launch_options() folded proxy_extra_args into the args; recompute them- # for the request-client warning below (#579).- _, proxy_extra_args = _resolve_proxy_config(proxy)-logger.debug("Launching stealth Chromium async (headless=%s, args=%d)", headless, len(launch_options["args"]))pw = await async_playwright().start()try:browser = await pw.chromium.launch(**launch_options)except Exception as exc:- lic = _license_error(exc)+ lic = license_error_from(exc, launch_options)try:await pw.stop()except Exception as stop_exc:@@ -634,13 +689,11 @@ async def launch_async( # noqa: C901browser.close = _close_with_cleanup# Convert a post-handshake license denial into a clear error on first use- # (see launch()). Stash the path for launch_context_async().- if denial_path:- browser._cloak_denial_path = denial_path- _install_license_guard_async(browser, denial_path)+ # (see launch()). Stashes the path for launch_context_async().+ guard_browser_async(browser, launch_options)# Warn on first use of Playwright's request client (see launch(), #579).- if proxy_extra_args:+ if proxy is not None and "proxy" not in launch_options:browser._impl_obj.on("context", _warn_on_request_client_use)# Default new_page()/new_context() to no_viewport (see launch()).@@ -719,15 +772,22 @@ def launch_persistent_context(from playwright.sync_api import sync_playwrighttimezone = _resolve_timezone(timezone, kwargs)-- binary_path = ensure_binary(license_key=license_key, browser_version=browser_version, release_channel=release_channel)- timezone, locale, exit_ip = maybe_resolve_geoip(geoip, proxy, timezone, locale, args)- proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy)- args = _resolve_webrtc_args(args, proxy)- args = _append_webrtc_exit_ip(args, exit_ip)- args = persistent_seed_args(user_data_dir, stealth_args, args)- chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=viewport is _VIEWPORT_UNSET and "viewport" not in kwargs and "no_viewport" not in kwargs)- _maybe_warn_windows_fonts(chrome_args)+ launch_options = build_launch_options(+ headless=headless,+ proxy=proxy,+ args=persistent_seed_args(user_data_dir, stealth_args, args),+ stealth_args=stealth_args,+ timezone=timezone,+ locale=locale,+ geoip=geoip,+ extension_paths=extension_paths,+ license_key=license_key,+ browser_version=browser_version,+ release_channel=release_channel,+ # Caller chose a viewport geometry -> don't also auto-maximize the window.+ _suppress_maximize=(viewport is not _VIEWPORT_UNSET or "no_viewport" in kwargs),+ **_context_kwargs(user_agent, viewport, color_scheme, kwargs),+ )logger.debug("Launching persistent stealth Chromium (headless=%s, user_data_dir=%s)",@@ -735,41 +795,15 @@ def launch_persistent_context(user_data_dir,)- # locale and timezone are set via binary flags (--lang, --fingerprint-timezone)- # — NOT via Playwright context kwargs which use detectable CDP emulation.- context_kwargs: dict[str, Any] = {}- if user_agent:- context_kwargs["user_agent"] = user_agent- context_kwargs.update(- _resolve_context_viewport(viewport)- )- if color_scheme:- context_kwargs["color_scheme"] = color_scheme- context_kwargs.update(kwargs)- _drop_conflicting_viewport(context_kwargs, kwargs)-- # Resolve env for the browser process (license key injection, if needed)- user_env = context_kwargs.pop("env", None)- denial_path = mint_denial_file() if resolve_license_key(license_key) else None- launch_env = build_launch_env(license_key, user_env=user_env, status_file=denial_path)- if launch_env is not None:- context_kwargs["env"] = launch_env-- seed_widevine_hint(user_data_dir, binary_path)+ seed_widevine_hint(user_data_dir, launch_options["executable_path"])pw = sync_playwright().start()try:context = pw.chromium.launch_persistent_context(- user_data_dir=os.fspath(user_data_dir),- executable_path=binary_path,- headless=headless,- args=chrome_args,- ignore_default_args=IGNORE_DEFAULT_ARGS,- **proxy_kwargs,- **context_kwargs,+ user_data_dir=os.fspath(user_data_dir), **launch_options)except Exception as exc:- lic = _license_error(exc)+ lic = license_error_from(exc, launch_options)try:pw.stop()except Exception as stop_exc:@@ -793,7 +827,7 @@ def launch_persistent_context(context.close = _close_with_cleanup# Warn on first use of Playwright's request client (see launch(), #579).- if proxy_extra_args:+ if proxy is not None and "proxy" not in launch_options:_warn_on_request_client_use(context._impl_obj)# Human-like behavioral patching. Applied BEFORE the license guard: the guard@@ -812,7 +846,9 @@ def launch_persistent_context(# the user navigates pages[0] directly and never calls new_page — guard those# existing pages too, or a post-handshake denial surfaces as a bare# TargetClosedError on that first navigation.+ denial_path = _denial_path_from(launch_options)if denial_path:+ context._cloak_denial_path = denial_path # for license_denial()_install_license_guard(context, denial_path)for _pg in context.pages:_install_license_guard(_pg, denial_path)@@ -890,14 +926,23 @@ async def launch_persistent_context_async(timezone = _resolve_timezone(timezone, kwargs)# Blocking network calls run in a thread (see launch_async).- binary_path = await asyncio.to_thread(ensure_binary, license_key=license_key, browser_version=browser_version, release_channel=release_channel)- timezone, locale, exit_ip = await asyncio.to_thread(maybe_resolve_geoip, geoip, proxy, timezone, locale, args)- proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy)- args = await asyncio.to_thread(_resolve_webrtc_args, args, proxy)- args = _append_webrtc_exit_ip(args, exit_ip)- args = persistent_seed_args(user_data_dir, stealth_args, args)- chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=viewport is _VIEWPORT_UNSET and "viewport" not in kwargs and "no_viewport" not in kwargs)- _maybe_warn_windows_fonts(chrome_args)+ launch_options = await asyncio.to_thread(+ build_launch_options,+ headless=headless,+ proxy=proxy,+ args=persistent_seed_args(user_data_dir, stealth_args, args),+ stealth_args=stealth_args,+ timezone=timezone,+ locale=locale,+ geoip=geoip,+ extension_paths=extension_paths,+ license_key=license_key,+ browser_version=browser_version,+ release_channel=release_channel,+ # Caller chose a viewport geometry -> don't also auto-maximize the window.+ _suppress_maximize=(viewport is not _VIEWPORT_UNSET or "no_viewport" in kwargs),+ **_context_kwargs(user_agent, viewport, color_scheme, kwargs),+ )logger.debug("Launching persistent stealth Chromium async (headless=%s, user_data_dir=%s)",@@ -905,41 +950,15 @@ async def launch_persistent_context_async(user_data_dir,)- # locale and timezone are set via binary flags (--lang, --fingerprint-timezone)- # — NOT via Playwright context kwargs which use detectable CDP emulation.- context_kwargs: dict[str, Any] = {}- if user_agent:- context_kwargs["user_agent"] = user_agent- context_kwargs.update(- _resolve_context_viewport(viewport)- )- if color_scheme:- context_kwargs["color_scheme"] = color_scheme- context_kwargs.update(kwargs)- _drop_conflicting_viewport(context_kwargs, kwargs)-- # Resolve env for the browser process (license key injection, if needed)- user_env = context_kwargs.pop("env", None)- denial_path = mint_denial_file() if resolve_license_key(license_key) else None- launch_env = build_launch_env(license_key, user_env=user_env, status_file=denial_path)- if launch_env is not None:- context_kwargs["env"] = launch_env-- seed_widevine_hint(user_data_dir, binary_path)+ seed_widevine_hint(user_data_dir, launch_options["executable_path"])pw = await async_playwright().start()try:context = await pw.chromium.launch_persistent_context(- user_data_dir=os.fspath(user_data_dir),- executable_path=binary_path,- headless=headless,- args=chrome_args,- ignore_default_args=IGNORE_DEFAULT_ARGS,- **proxy_kwargs,- **context_kwargs,+ user_data_dir=os.fspath(user_data_dir), **launch_options)except Exception as exc:- lic = _license_error(exc)+ lic = license_error_from(exc, launch_options)try:await pw.stop()except Exception as stop_exc:@@ -963,7 +982,7 @@ async def launch_persistent_context_async(context.close = _close_with_cleanup# Warn on first use of Playwright's request client (see launch(), #579).- if proxy_extra_args:+ if proxy is not None and "proxy" not in launch_options:_warn_on_request_client_use(context._impl_obj)# Human-like behavioral patching (async variant). Applied BEFORE the license@@ -979,8 +998,9 @@ async def launch_persistent_context_async(# launch()). A persistent context also arrives with a page already open (see# the sync variant): guard those existing pages so a post-handshake denial on# pages[0] surfaces cleanly instead of as a bare TargetClosedError.+ denial_path = _denial_path_from(launch_options)if denial_path:- context._cloak_denial_path = denial_path+ context._cloak_denial_path = denial_path # for license_denial(); Manager reads it too_install_license_guard_async(context, denial_path)for _pg in context.pages:_install_license_guard_async(_pg, denial_path)@@ -1055,19 +1075,8 @@ def launch_context(# the window (mirrors the persistent-context path + JS)._suppress_maximize=(viewport is not _VIEWPORT_UNSET or "no_viewport" in kwargs))- context_kwargs: dict[str, Any] = {}- if user_agent:- context_kwargs["user_agent"] = user_agent- context_kwargs.update(- _resolve_context_viewport(viewport)- )- if color_scheme:- context_kwargs["color_scheme"] = color_scheme- context_kwargs.update(kwargs)- _drop_conflicting_viewport(context_kwargs, kwargs)-try:- context = browser.new_context(**context_kwargs)+ context = browser.new_context(**_context_kwargs(user_agent, viewport, color_scheme, kwargs))except Exception:browser.close()raise@@ -1086,11 +1095,11 @@ def launch_context(context.close = _close_context_with_cleanup- # browser.new_context above is already guarded by launch(); also guard the- # context's new_page for a denial that lands after the context is created.+ # launch() guards browser.new_context deeply, so this context is already+ # guarded; only store the path for license_denial().denial_path = getattr(browser, "_cloak_denial_path", None)if denial_path:- _install_license_guard(context, denial_path)+ context._cloak_denial_path = denial_path# Human-like behavioral patchingif humanize:@@ -1188,22 +1197,11 @@ async def launch_context_async(# the window (mirrors the persistent-context path + JS)._suppress_maximize=(viewport is not _VIEWPORT_UNSET or "no_viewport" in kwargs))- context_kwargs: dict[str, Any] = {}- if user_agent:- context_kwargs["user_agent"] = user_agent- context_kwargs.update(- _resolve_context_viewport(viewport)- )- if color_scheme:- context_kwargs["color_scheme"] = color_scheme- context_kwargs.update(kwargs)- _drop_conflicting_viewport(context_kwargs, kwargs)-# Catch BaseException (not just Exception) so that asyncio.CancelledError# triggers browser cleanup — otherwise the underlying Chromium process# leaks when the awaiting task is cancelled.try:- context = await browser.new_context(**context_kwargs)+ context = await browser.new_context(**_context_kwargs(user_agent, viewport, color_scheme, kwargs))except BaseException:try:await browser.close()@@ -1225,11 +1223,11 @@ async def launch_context_async(context.close = _close_context_with_cleanup- # browser.new_context above is already guarded by launch_async(); also guard- # the context's new_page for a denial that lands after context creation.+ # launch_async() guards browser.new_context deeply, so this context is already+ # guarded; only store the path for license_denial().denial_path = getattr(browser, "_cloak_denial_path", None)if denial_path:- _install_license_guard_async(context, denial_path)+ context._cloak_denial_path = denial_path# Human-like behavioral patching (async variant)if humanize:diff --git a/dotnet/src/CloakBrowser/CloakLauncher.cs b/dotnet/src/CloakBrowser/CloakLauncher.csindex 8718c3f..4afc676 100644--- a/dotnet/src/CloakBrowser/CloakLauncher.cs+++ b/dotnet/src/CloakBrowser/CloakLauncher.cs@@ -23,44 +23,16 @@ public static class CloakLauncher{options ??= new LaunchOptions();- string binaryPath = await Download.EnsureBinaryAsync(- options.LicenseKey, options.BrowserVersion,- releaseChannel: options.ReleaseChannel).ConfigureAwait(false);- var (timezone, locale, exitIp) = await MaybeResolveGeoIpAsync(- options.GeoIp, options.Proxy, options.Timezone, options.Locale, options.Args).ConfigureAwait(false);- var proxyResolution = ProxyResolver.Resolve(options.Proxy);- var args = await ResolveWebRtcArgsAsync(options.Args, options.Proxy).ConfigureAwait(false);- args = MaybeAppendWebRtcExitIp(args, exitIp);-- var combined = new List<string>(args ?? new List<string>());- combined.AddRange(proxyResolution.ExtraArgs);- var chromeArgs = BuildArgs(options.StealthArgs, combined, timezone, locale, options.Headless, options.ExtensionPaths,- startMaximized: !options.SuppressMaximize);- MaybeWarnWindowsFonts(chromeArgs);-- CloakLog.Debug($"Launching stealth Chromium (headless={options.Headless}, args={chromeArgs.Count})");-- // Per-launch denial file: the binary records a post-handshake license- // denial here so NewPage/NewContext can surface it (see LicenseGuard).- // Only when a key is in play (none only with a CLOAKBROWSER_BINARY_PATH override).- var denialPath = License.ResolveLicenseKey(options.LicenseKey) != null- ? License.MintDenialFile()- : null;+ var launchOptions = await BuildLaunchOptionsAsync(options).ConfigureAwait(false);+ var denialPath = DenialPathFrom(launchOptions);+ CloakLog.Debug($"Launching stealth Chromium (headless={options.Headless}, args={launchOptions.Args!.Count()})");var playwright = await Playwright.CreateAsync().ConfigureAwait(false);// Only the launch is wrapped for license-error mapping (mirrors Python/JS).IBrowser browser;try{- browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions- {- ExecutablePath = binaryPath,- Headless = options.Headless,- Args = chromeArgs,- IgnoreDefaultArgs = Config.IgnoreDefaultArgs,- Proxy = proxyResolution.PlaywrightProxy,- Env = License.BuildLaunchEnv(options.LicenseKey, statusFile: denialPath),- }).ConfigureAwait(false);+ browser = await playwright.Chromium.LaunchAsync(launchOptions).ConfigureAwait(false);}catch (Exception ex){@@ -91,6 +63,83 @@ public static class CloakLauncher}}+ /// <summary>+ /// Build the Playwright launch options <see cref="LaunchAsync"/> uses, without starting+ /// Chromium. Use it with your own Playwright instance:+ /// <c>var opts = await CloakLauncher.BuildLaunchOptionsAsync(o);+ /// var browser = CloakLauncher.GuardBrowser(await pw.Chromium.LaunchAsync(opts), opts);</c>.+ /// Wrap the launch call with <see cref="LicenseErrorFrom"/> so a license denial during+ /// launch also surfaces as <see cref="CloakBrowserLicenseError"/>.+ /// Humanize options on <paramref name="options"/> are ignored here; wrap with+ /// <see cref="Wrappers.Humanize.Browser"/> before <see cref="GuardBrowser"/>.+ /// </summary>+ public static async Task<BrowserTypeLaunchOptions> BuildLaunchOptionsAsync(LaunchOptions? options = null)+ {+ options ??= new LaunchOptions();++ string binaryPath = await Download.EnsureBinaryAsync(+ options.LicenseKey, options.BrowserVersion,+ releaseChannel: options.ReleaseChannel).ConfigureAwait(false);+ var (timezone, locale, exitIp) = await MaybeResolveGeoIpAsync(+ options.GeoIp, options.Proxy, options.Timezone, options.Locale, options.Args).ConfigureAwait(false);+ var proxyResolution = ProxyResolver.Resolve(options.Proxy);+ var args = await ResolveWebRtcArgsAsync(options.Args, options.Proxy).ConfigureAwait(false);+ args = MaybeAppendWebRtcExitIp(args, exitIp);++ var combined = new List<string>(args ?? new List<string>());+ combined.AddRange(proxyResolution.ExtraArgs);+ var chromeArgs = BuildArgs(options.StealthArgs, combined, timezone, locale, options.Headless, options.ExtensionPaths,+ startMaximized: !options.SuppressMaximize);+ MaybeWarnWindowsFonts(chromeArgs);++ // Per-launch denial file: the binary records a post-handshake license+ // denial here so GuardBrowser / the handle can surface it (see LicenseGuard).+ // Only when a key is in play (none only with a CLOAKBROWSER_BINARY_PATH override).+ var denialPath = License.ResolveLicenseKey(options.LicenseKey) != null+ ? License.MintDenialFile()+ : null;++ return new BrowserTypeLaunchOptions+ {+ ExecutablePath = binaryPath,+ Headless = options.Headless,+ Args = chromeArgs,+ IgnoreDefaultArgs = Config.IgnoreDefaultArgs,+ Proxy = proxyResolution.PlaywrightProxy,+ Env = License.BuildLaunchEnv(options.LicenseKey, statusFile: denialPath),+ };+ }++ /// <summary>+ /// Make a license denial (e.g. over the session cap) on a browser you launched yourself+ /// throw <see cref="CloakBrowserLicenseError"/> instead of a bare "Target closed" error.+ /// Pass the options <see cref="BuildLaunchOptionsAsync"/> returned and use the returned+ /// browser. Returns <paramref name="browser"/> unchanged when no license key was in play.+ /// </summary>+ public static IBrowser GuardBrowser(IBrowser browser, BrowserTypeLaunchOptions launchOptions) =>+ (IBrowser)LicenseGuard.Wrap(browser, DenialPathFrom(launchOptions));++ /// <summary>+ /// Map a failed <c>Chromium.LaunchAsync(opts)</c> to <see cref="CloakBrowserLicenseError"/> when+ /// the binary refused the license during launch (before <see cref="GuardBrowser"/> can run),+ /// or null for any other error:+ /// <c>catch (Exception ex) { throw CloakLauncher.LicenseErrorFrom(ex, opts) ?? ex; }</c>.+ /// .NET Playwright omits the exit code from its error, so this reads the launch's denial file.+ /// </summary>+ public static CloakBrowserLicenseError? LicenseErrorFrom(Exception ex, BrowserTypeLaunchOptions launchOptions) =>+ License.LicenseErrorFrom(ex, DenialPathFrom(launchOptions));++ /// <summary>+ /// Why the license refused the browser launched with <paramref name="launchOptions"/>+ /// (from <see cref="BuildLaunchOptionsAsync"/>), or null. Checks now, without a browser+ /// call. Handles from <see cref="LaunchAsync"/> etc. have <c>LicenseDenial()</c> instead.+ /// </summary>+ public static CloakBrowserLicenseError? LicenseDenial(BrowserTypeLaunchOptions launchOptions) =>+ DenialPathFrom(launchOptions) is { } path ? LicenseGuard.DenialError(path) : null;++ private static string? DenialPathFrom(BrowserTypeLaunchOptions launchOptions) =>+ launchOptions.Env?.FirstOrDefault(kv => kv.Key == License.LicenseStatusFileEnv).Value;+// -----------------------------------------------------------------------// launch_context - returns a Context handle (browser owned)// -----------------------------------------------------------------------@@ -160,30 +209,28 @@ public static class CloakLauncher{options ??= new LaunchContextOptions();- string binaryPath = await Download.EnsureBinaryAsync(- options.LicenseKey, options.BrowserVersion,- releaseChannel: options.ReleaseChannel).ConfigureAwait(false);- var (timezone, locale, exitIp) = await MaybeResolveGeoIpAsync(- options.GeoIp, options.Proxy, options.Timezone, options.Locale, options.Args).ConfigureAwait(false);- var proxyResolution = ProxyResolver.Resolve(options.Proxy);- var args = await ResolveWebRtcArgsAsync(options.Args, options.Proxy).ConfigureAwait(false);- args = MaybeAppendWebRtcExitIp(args, exitIp);- args = Config.PersistentSeedArgs(userDataDir, options.StealthArgs, args);-- var combined = new List<string>(args ?? new List<string>());- combined.AddRange(proxyResolution.ExtraArgs);- var chromeArgs = BuildArgs(options.StealthArgs, combined, timezone, locale, options.Headless, options.ExtensionPaths,- startMaximized: !options.NoViewport && options.Viewport == null);- MaybeWarnWindowsFonts(chromeArgs);+ var launchOptions = await BuildLaunchOptionsAsync(new LaunchOptions+ {+ Headless = options.Headless,+ Proxy = options.Proxy,+ Args = Config.PersistentSeedArgs(userDataDir, options.StealthArgs, options.Args),+ StealthArgs = options.StealthArgs,+ Timezone = options.Timezone,+ Locale = options.Locale,+ GeoIp = options.GeoIp,+ ExtensionPaths = options.ExtensionPaths,+ LicenseKey = options.LicenseKey,+ BrowserVersion = options.BrowserVersion,+ ReleaseChannel = options.ReleaseChannel,+ // Caller chose a viewport geometry → don't also auto-maximize the window.+ SuppressMaximize = options.NoViewport || options.Viewport != null,+ }).ConfigureAwait(false);+ var denialPath = DenialPathFrom(launchOptions);CloakLog.Debug($"Launching persistent stealth Chromium (headless={options.Headless}, user_data_dir={userDataDir})");// Seed the Widevine CDM hint (Linux-only; no-op elsewhere).- Widevine.SeedWidevineHint(userDataDir, binaryPath);-- var denialPath = License.ResolveLicenseKey(options.LicenseKey) != null- ? License.MintDenialFile()- : null;+ Widevine.SeedWidevineHint(userDataDir, launchOptions.ExecutablePath!);var playwright = await Playwright.CreateAsync().ConfigureAwait(false);// Only the launch is wrapped for license-error mapping (mirrors Python/JS).@@ -192,12 +239,12 @@ public static class CloakLauncher{var ctxLaunchOptions = new BrowserTypeLaunchPersistentContextOptions{- ExecutablePath = binaryPath,- Headless = options.Headless,- Args = chromeArgs,- IgnoreDefaultArgs = Config.IgnoreDefaultArgs,- Proxy = proxyResolution.PlaywrightProxy,- Env = License.BuildLaunchEnv(options.LicenseKey, statusFile: denialPath),+ ExecutablePath = launchOptions.ExecutablePath,+ Headless = launchOptions.Headless,+ Args = launchOptions.Args,+ IgnoreDefaultArgs = launchOptions.IgnoreDefaultArgs,+ Proxy = launchOptions.Proxy,+ Env = launchOptions.Env,};ApplyContextEmulation(ctxLaunchOptions, options);diff --git a/dotnet/src/CloakBrowser/Handles.cs b/dotnet/src/CloakBrowser/Handles.csindex 5c03a3d..59fa992 100644--- a/dotnet/src/CloakBrowser/Handles.cs+++ b/dotnet/src/CloakBrowser/Handles.cs@@ -100,6 +100,14 @@ public sealed class CloakBrowserHandle : IAsyncDisposable/// <summary>Whether the humanize layer is enabled for this browser.</summary>public bool HumanizeEnabled => _humanize;+ /// <summary>+ /// Why the license refused this browser (e.g. "session limit reached"), or null. Checks+ /// now, without a browser call: useful while waiting on something else, like a CDP+ /// endpoint. Safe to call repeatedly.+ /// </summary>+ public CloakBrowserLicenseError? LicenseDenial() =>+ _denialPath == null ? null : LicenseGuard.DenialError(_denialPath);+/// <summary>Close the browser and stop the underlying Playwright instance.</summary>public Task CloseAsync() => CloseAsync(null);@@ -412,6 +420,13 @@ public sealed class CloakContextHandle : IAsyncDisposable/// <summary>Whether the humanize layer is enabled for this context.</summary>public bool HumanizeEnabled => _humanize;+ /// <summary>+ /// Why the license refused this context's browser (e.g. "session limit reached"), or+ /// null. Checks now, without a browser call. Safe to call repeatedly.+ /// </summary>+ public CloakBrowserLicenseError? LicenseDenial() =>+ _denialPath == null ? null : LicenseGuard.DenialError(_denialPath);+/// <summary>Close the context (and browser, if owned) and stop Playwright.</summary>public Task CloseAsync() => CloseAsync(null);diff --git a/dotnet/tests/CloakBrowser.Tests/LicenseTests.cs b/dotnet/tests/CloakBrowser.Tests/LicenseTests.csindex 36733d4..dc99cc2 100644--- a/dotnet/tests/CloakBrowser.Tests/LicenseTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/LicenseTests.cs@@ -1281,4 +1281,64 @@ public class LicenseTests : IDisposable() => Task.FromResult<object>("ok"), Path.Combine(_tmp, "absent.json"));Assert.Equal("ok", result);}++ // GuardBrowser: the public hook for callers who launch with BuildLaunchOptionsAsync.+ [Fact]+ public async Task GuardBrowser_UsesDenialPathFromLaunchOptionsEnv()+ {+ var f = Path.Combine(_tmp, "d.json");+ File.WriteAllText(f, "77");+ var (raw, rec) = CloakBrowser.Tests.Wrappers.Fake.Of<Microsoft.Playwright.IBrowser>();+ rec.On("NewPageAsync", _ => Task.FromException<Microsoft.Playwright.IPage>(+ new Exception("Target page, context or browser has been closed")));+ var opts = new Microsoft.Playwright.BrowserTypeLaunchOptions+ {+ Env = new Dictionary<string, string> { [License.LicenseStatusFileEnv] = f },+ };++ var guarded = CloakLauncher.GuardBrowser(raw, opts);++ Assert.NotSame(raw, guarded);+ await Assert.ThrowsAsync<CloakBrowserLicenseError>(() => guarded.NewPageAsync());+ }++ [Fact]+ public void LicenseErrorFrom_ReadsDenialFileFromLaunchOptions()+ {+ var f = Path.Combine(_tmp, "d.json");+ File.WriteAllText(f, "76");+ var opts = new Microsoft.Playwright.BrowserTypeLaunchOptions+ {+ Env = new Dictionary<string, string> { [License.LicenseStatusFileEnv] = f },+ };+ var closed = new Exception("Target page, context or browser has been closed");+ Assert.NotNull(CloakLauncher.LicenseErrorFrom(closed, opts));+ Assert.Null(CloakLauncher.LicenseErrorFrom(closed, new Microsoft.Playwright.BrowserTypeLaunchOptions()));+ }++ [Fact]+ public void LicenseDenial_ChecksDenialFileWithoutBrowserCall()+ {+ var f = Path.Combine(_tmp, "d.json");+ var opts = new Microsoft.Playwright.BrowserTypeLaunchOptions+ {+ Env = new Dictionary<string, string> { [License.LicenseStatusFileEnv] = f },+ };+ Assert.Null(CloakLauncher.LicenseDenial(new Microsoft.Playwright.BrowserTypeLaunchOptions()));+ Assert.Null(CloakLauncher.LicenseDenial(opts)); // no file yet+ File.WriteAllText(f, "76");+ Assert.NotNull(CloakLauncher.LicenseDenial(opts));+ Assert.NotNull(CloakLauncher.LicenseDenial(opts)); // cached after read+ }++ [Fact]+ public void GuardBrowser_NoLicenseReturnsSameBrowser()+ {+ var (raw, _) = CloakBrowser.Tests.Wrappers.Fake.Of<Microsoft.Playwright.IBrowser>();+ Assert.Same(raw, CloakLauncher.GuardBrowser(raw, new Microsoft.Playwright.BrowserTypeLaunchOptions()));+ Assert.Same(raw, CloakLauncher.GuardBrowser(raw, new Microsoft.Playwright.BrowserTypeLaunchOptions+ {+ Env = new Dictionary<string, string> { ["FOO"] = "1" },+ }));+ }}diff --git a/js/src/index.ts b/js/src/index.tsindex b192781..be48570 100644--- a/js/src/index.ts+++ b/js/src/index.ts@@ -16,7 +16,7 @@*/// Launch functions (Playwright API)-export { launch, launchContext, launchPersistentContext, buildLaunchOptions, buildContextOptions, humanizeBrowser } from "./playwright.js";+export { launch, launchContext, launchPersistentContext, buildLaunchOptions, buildContextOptions, guardBrowser, humanizeBrowser } from "./playwright.js";// Binary managementexport { ensureBinary, clearCache, binaryInfo } from "./download.js";@@ -25,7 +25,7 @@ export { ensureBinary, clearCache, binaryInfo } from "./download.js";export { getDefaultStealthArgs } from "./config.js";// License-export { validateLicense, CloakBrowserLicenseError } from "./license.js";+export { validateLicense, CloakBrowserLicenseError, licenseDenial, licenseErrorFrom } from "./license.js";// Typesexport type { LaunchOptions, LaunchContextOptions, LaunchPersistentContextOptions, BinaryInfo } from "./types.js";diff --git a/js/src/license.ts b/js/src/license.tsindex c557b67..98ab65a 100644--- a/js/src/license.ts+++ b/js/src/license.ts@@ -247,6 +247,17 @@ function denialLicenseError(denialPath: string): CloakBrowserLicenseError | nullreturn code !== null ? licenseErrorForCode(code) : null;}+/**+ * Why the license refused this browser/context (e.g. "session limit reached"),+ * or null. Checks now, without a browser call: useful while waiting on something+ * else, like a CDP endpoint. Works on anything launch(), launchContext(),+ * launchPersistentContext() or guardBrowser() handed back. Safe to call repeatedly.+ */+export function licenseDenial(target: unknown): CloakBrowserLicenseError | null {+ const denialPath = (target as any)?.__cloakDenialPath as string | undefined;+ return denialPath ? denialLicenseError(denialPath) : null;+}+/*** Public, non-getter method names on `target` and its prototype chain — the* methods that can throw a TargetClosedError once the browser dies. Getters arediff --git a/js/src/playwright.ts b/js/src/playwright.tsindex 84755a4..bd8a3ba 100644--- a/js/src/playwright.ts+++ b/js/src/playwright.ts@@ -12,6 +12,7 @@ import { ensureBinary } from "./download.js";import { resolveProxyConfig, warnOnRequestClientUse } from "./proxy.js";import { maybeResolveGeoip, resolveWebrtcArgs, appendWebrtcExitIp } from "./geoip.js";import {+ LICENSE_STATUS_FILE_ENV,buildLaunchEnv,installLicenseGuard,licenseErrorFrom,@@ -83,6 +84,9 @@ export function buildContextOptions(** Useful when integrating CloakBrowser with a custom Playwright build or another* wrapper that needs to call `chromium.launch()` itself.+ *+ * @param statusFile No longer needed: the denial file is created automatically.+ * Kept for compatibility.*/export async function buildLaunchOptions(options: LaunchOptions = {},@@ -104,6 +108,12 @@ export async function buildLaunchOptions(// Resolve env for the browser process (license key injection, if needed).const { env: userEnv, ...restLaunchOptions } = options.launchOptions ?? {};+ // Standalone callers get a denial file too, so guardBrowser() can turn a+ // license denial into a clear error. Minted after ensureBinary: with no key,+ // its claim menu is what creates one.+ if (statusFile === undefined && resolveLicenseKey(options.licenseKey)) {+ statusFile = mintDenialFile();+ }const launchEnv = buildLaunchEnv(options.licenseKey,userEnv as Record<string, string | undefined> | undefined,@@ -122,6 +132,28 @@ export async function buildLaunchOptions(} as PlaywrightLaunchOptions;}+/**+ * Make a license denial (e.g. over the session cap) on a browser you launched+ * yourself throw CloakBrowserLicenseError instead of a bare "Target closed"+ * error. Pass the options buildLaunchOptions() returned; call it before+ * humanizeBrowser(). No-op when no license key was in play.+ *+ * A denial can also land during launch, before this runs. Map that one too:+ * ```ts+ * const opts = await buildLaunchOptions();+ * const browser = await chromium.launch(opts).catch((e) => {+ * throw licenseErrorFrom(e) ?? e;+ * });+ * guardBrowser(browser, opts);+ * ```+ */+export function guardBrowser(browser: Browser, launchOptions: PlaywrightLaunchOptions): void {+ const denialPath = launchOptions.env?.[LICENSE_STATUS_FILE_ENV];+ if (!denialPath) return;+ (browser as any).__cloakDenialPath = denialPath;+ installLicenseGuard(browser, denialPath);+}+/*** Apply CloakBrowser's human-like behavioral layer to an existing Playwright browser.*/@@ -155,28 +187,19 @@ export async function humanizeBrowser(*/export async function launch(options: LaunchOptions = {}): Promise<Browser> {const { chromium } = await import("playwright-core");- // Only a path (nothing is written). Decided AFTER buildLaunchOptions: with no- // key, its ensureBinary runs the claim menu that creates one, and the guard must- // cover that first launch too (Python mints after ensure_binary for the same reason).- let denialPath = mintDenialFile();+ // Mints the denial file (after ensureBinary, so a key the claim menu just+ // created is covered too).+ const launchOptions = await buildLaunchOptions(options);let browser: Browser;- let launchOptions: PlaywrightLaunchOptions;try {- launchOptions = await buildLaunchOptions(options, denialPath);- if (!resolveLicenseKey(options.licenseKey)) denialPath = undefined;browser = await chromium.launch(launchOptions);} catch (err) {- const lic = licenseErrorFrom(err, denialPath);- if (lic) throw lic;- throw err;+ throw licenseErrorFrom(err, launchOptions.env?.[LICENSE_STATUS_FILE_ENV]) ?? err;}// Convert a post-handshake license denial into a clear error on first use.- // Installed before the wraps below so it sits closest to the real call. Stash+ // Installed before the wraps below so it sits closest to the real call. Stashes// the path so launchContext() can guard its context too. Mirrors Python launch().- if (denialPath) {- (browser as any).__cloakDenialPath = denialPath;- installLicenseGuard(browser, denialPath);- }+ guardBrowser(browser, launchOptions);// Proxy went to Chrome as --proxy-server, so Playwright's request client has no// proxy (#579). browser.newPage() and launchContext() both go through newContext.if (options.proxy && !launchOptions.proxy) {@@ -262,12 +285,10 @@ export async function launchContext(}};- // browser.newContext above is already guarded by launch(); also guard the- // context's newPage for a denial that lands after the context is created.+ // launch() guards browser.newContext deeply, so this context is already+ // guarded; only store the path for licenseDenial().const denialPath = (browser as any).__cloakDenialPath as string | undefined;- if (denialPath) {- installLicenseGuard(context, denialPath);- }+ if (denialPath) (context as any).__cloakDenialPath = denialPath;// Human-like behavioral patchingif (options.humanize) {@@ -310,54 +331,26 @@ export async function launchPersistentContext(options = resolveTimezone(options);const { chromium } = await import("playwright-core");- const binaryPath =- process.env.CLOAKBROWSER_BINARY_PATH ||- (await ensureBinary(- options.licenseKey,- options.browserVersion,- options.releaseChannel,- ));- const { exitIp, ...resolved } = await maybeResolveGeoip(options);- const { proxyOption, proxyArgs } = resolveProxyConfig(options.proxy);- let resolvedArgs = await resolveWebrtcArgs(options);- resolvedArgs = appendWebrtcExitIp(resolvedArgs, exitIp);- resolvedArgs = persistentSeedArgs(options.userDataDir, options.stealthArgs, resolvedArgs);- const args = buildArgs({ ...options, ...resolved, args: [...(resolvedArgs ?? []), ...proxyArgs] });- maybeWarnWindowsFonts(args);-- seedWidevineHint(options.userDataDir, binaryPath);-- // Resolve env for the browser process (license key injection, if needed).- const denialPath = resolveLicenseKey(options.licenseKey) ? mintDenialFile() : undefined;- const { env: userEnv, ...restLaunchOptions } = options.launchOptions ?? {};- const launchEnv = buildLaunchEnv(- options.licenseKey,- userEnv as Record<string, string | undefined> | undefined,- denialPath,- );- const envResult = launchEnv !== undefined ? { env: launchEnv } : {};+ const launchOptions = await buildLaunchOptions({+ ...options,+ args: persistentSeedArgs(options.userDataDir, options.stealthArgs, options.args),+ });+ seedWidevineHint(options.userDataDir, launchOptions.executablePath!);+ const denialPath = launchOptions.env?.[LICENSE_STATUS_FILE_ENV];// locale and timezone are set via binary flags (--lang, --fingerprint-timezone)// — NOT via Playwright context kwargs which use detectable CDP emulation.let context: BrowserContext;try {context = await chromium.launchPersistentContext(options.userDataDir, {- executablePath: binaryPath,- headless: options.headless ?? true,- args,- ignoreDefaultArgs: IGNORE_DEFAULT_ARGS,- ...(proxyOption ? { proxy: proxyOption } : {}),...buildContextOptions(options),- ...restLaunchOptions,- ...envResult,+ ...launchOptions,});} catch (err) {- const lic = licenseErrorFrom(err, denialPath);- if (lic) throw lic;- throw err;+ throw licenseErrorFrom(err, denialPath) ?? err;}- if (proxyArgs.length) warnOnRequestClientUse(context);+ if (options.proxy && !launchOptions.proxy) warnOnRequestClientUse(context);// Human-like behavioral patching. Applied BEFORE the license guard: the guard// stores its wrapper on the page/context object (it carries this launch's denial@@ -375,6 +368,7 @@ export async function launchPersistentContext(// The persistent path hands back a context, so guard its newPage (see launch()).if (denialPath) {+ (context as any).__cloakDenialPath = denialPath; // for licenseDenial()installLicenseGuard(context, denialPath);// A persistent context arrives with a page already open, so the user// navigates pages()[0] directly and never calls newPage. Guard the existingdiff --git a/js/src/puppeteer.ts b/js/src/puppeteer.tsindex 0fe3024..ce0dde8 100644--- a/js/src/puppeteer.ts+++ b/js/src/puppeteer.ts@@ -151,6 +151,7 @@ export async function launch(options: LaunchOptions = {}): Promise<Browser> {// Guarding the browser deeply covers newPage AND the context factories// (createBrowserContext) and every page/context they hand back — so a user// who creates their own context is covered too.+ (browser as any).__cloakDenialPath = denialPath; // for licenseDenial()installLicenseGuard(browser, denialPath);}await applyPostLaunch(browser, options);@@ -214,6 +215,7 @@ export async function launchPersistentContext(// Guard the browser deeply for a post-handshake denial (see launch()).if (denialPath) {+ (browser as any).__cloakDenialPath = denialPath; // for licenseDenial()installLicenseGuard(browser, denialPath);// A persistent browser arrives with a page already open, so the user drives// pages()[0] directly and never calls newPage. Guard those existing pagesdiff --git a/js/tests/launch.test.ts b/js/tests/launch.test.tsindex 73b4664..3026728 100644--- a/js/tests/launch.test.ts+++ b/js/tests/launch.test.ts@@ -122,6 +122,9 @@ describe("composable Playwright launch helpers", () => {expect(entry.buildLaunchOptions).toBeTypeOf("function");expect(entry.buildContextOptions).toBeTypeOf("function");expect(entry.humanizeBrowser).toBeTypeOf("function");+ expect(entry.guardBrowser).toBeTypeOf("function");+ expect(entry.licenseErrorFrom).toBeTypeOf("function");+ expect(entry.licenseDenial).toBeTypeOf("function");});it("buildContextOptions returns Playwright context options without launching a browser", async () => {@@ -200,10 +203,55 @@ describe("composable Playwright launch helpers", () => {expect(options.env).toBeDefined();expect(options.env!.CLOAKBROWSER_LICENSE_KEY).toBe("cb_test_key");+ // Standalone call still gets a denial file for guardBrowser()+ expect(options.env!.CLOAKBROWSER_LICENSE_STATUS_FILE).toMatch(/denials/);// launchOptions timeout still forwardedexpect(options.timeout).toBe(1234);});+ it("guardBrowser turns a denial into CloakBrowserLicenseError", async () => {+ const { guardBrowser, CloakBrowserLicenseError } = await import("../src/index.js");+ const fs = await import("node:fs");+ const os = await import("node:os");+ const path = await import("node:path");++ const denial = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "cb-")), "d.json");+ fs.writeFileSync(denial, "77");+ const browser: any = {+ newPage: async () => {+ throw new Error("Target page, context or browser has been closed");+ },+ };+ guardBrowser(browser, { env: { CLOAKBROWSER_LICENSE_STATUS_FILE: denial } });++ expect(browser.__cloakDenialPath).toBe(denial);+ await expect(browser.newPage()).rejects.toBeInstanceOf(CloakBrowserLicenseError);+ });++ it("licenseDenial checks the stashed denial file without a browser call", async () => {+ const { licenseDenial, CloakBrowserLicenseError } = await import("../src/index.js");+ const fs = await import("node:fs");+ const os = await import("node:os");+ const path = await import("node:path");++ const denial = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "cb-")), "d.json");+ const ctx: any = {};+ expect(licenseDenial(ctx)).toBeNull(); // nothing stashed+ ctx.__cloakDenialPath = denial;+ expect(licenseDenial(ctx)).toBeNull(); // no file yet+ fs.writeFileSync(denial, "76");+ expect(licenseDenial(ctx)).toBeInstanceOf(CloakBrowserLicenseError);+ expect(licenseDenial(ctx)).toBeInstanceOf(CloakBrowserLicenseError); // cached after read+ });++ it("guardBrowser is a no-op without a license", async () => {+ const { guardBrowser } = await import("../src/index.js");+ const newPage = async () => "page";+ const browser: any = { newPage };+ guardBrowser(browser, { executablePath: "/fake/chrome" });+ expect(browser.newPage).toBe(newPage);+ });+it("buildLaunchOptions preserves custom env via launchOptions", async () => {const { buildLaunchOptions } = await import("../src/index.js");diff --git a/tests/test_build_launch_options.py b/tests/test_build_launch_options.pyindex 22c3a0a..16fc4c9 100644--- a/tests/test_build_launch_options.py+++ b/tests/test_build_launch_options.py@@ -83,6 +83,104 @@ def test_build_launch_options_threads_suppress_maximize():assert "--start-maximized" not in opts["args"]+def test_guard_browser_installs_guard_from_options_env():+ """guard_browser reads the denial path build_launch_options put in env."""+ from cloakbrowser.browser import guard_browser+ from cloakbrowser.license import LICENSE_STATUS_FILE_ENV++ browser = MagicMock()+ with patch("cloakbrowser.browser._install_license_guard") as mock_guard:+ guard_browser(browser, {"env": {LICENSE_STATUS_FILE_ENV: "/tmp/d.json"}})++ mock_guard.assert_called_once_with(browser, "/tmp/d.json")+ assert browser._cloak_denial_path == "/tmp/d.json"+++def test_guard_browser_async_uses_async_guard():+ from cloakbrowser.browser import guard_browser_async+ from cloakbrowser.license import LICENSE_STATUS_FILE_ENV++ browser = MagicMock()+ with patch("cloakbrowser.browser._install_license_guard_async") as mock_guard:+ guard_browser_async(browser, {"env": {LICENSE_STATUS_FILE_ENV: "/tmp/d.json"}})++ mock_guard.assert_called_once_with(browser, "/tmp/d.json")+++def test_license_error_maps_launch_failure():+ """A denial during launch (binary exit 76 in Playwright's launch log) maps to+ CloakBrowserLicenseError; any other error maps to None."""+ from cloakbrowser import license_error_from+ from cloakbrowser.license import CloakBrowserLicenseError++ denied = Exception(+ "BrowserType.launch: Target page, context or browser has been closed\n"+ " - [pid=1] <process did exit: exitCode=76, signal=null>"+ )+ assert isinstance(license_error_from(denied), CloakBrowserLicenseError)+ assert license_error_from(Exception("net::ERR_PROXY_CONNECTION_FAILED")) is None+++def test_license_error_from_falls_back_to_denial_file(tmp_path):+ """No exit code in the text -> read the launch's denial file (JS/.NET parity)."""+ from cloakbrowser import license_error_from+ from cloakbrowser.license import LICENSE_STATUS_FILE_ENV, CloakBrowserLicenseError++ closed = Exception("BrowserType.launch: Target page, context or browser has been closed")+ opts = {"env": {LICENSE_STATUS_FILE_ENV: str(tmp_path / "d.json")}}+ assert license_error_from(closed, opts) is None # no file -> genuine error+ (tmp_path / "d.json").write_text("76")+ assert license_error_from(closed) is None # no options -> text only+ assert isinstance(license_error_from(closed, opts), CloakBrowserLicenseError)+++def test_license_denial_reads_stashed_path(tmp_path):+ """license_denial checks without a browser call; repeat calls keep the answer."""+ from cloakbrowser import license_denial+ from cloakbrowser.license import CloakBrowserLicenseError++ class Obj:+ pass++ ctx = Obj()+ assert license_denial(ctx) is None # nothing stashed -> no license in play+ ctx._cloak_denial_path = str(tmp_path / "d.json")+ assert license_denial(ctx) is None # no file -> not denied+ (tmp_path / "d.json").write_text("76")+ assert isinstance(license_denial(ctx), CloakBrowserLicenseError)+ assert isinstance(license_denial(ctx), CloakBrowserLicenseError) # file consumed, cached+++def test_guard_browser_noop_without_license():+ """No key -> no env/denial path -> nothing installed."""+ from cloakbrowser.browser import guard_browser++ with patch("cloakbrowser.browser._install_license_guard") as mock_guard:+ guard_browser(MagicMock(), {"executable_path": "/fake/chrome"})+ guard_browser(MagicMock(), {"env": {"FOO": "1"}})++ mock_guard.assert_not_called()+++def test_guard_browser_raises_license_error_on_denial(tmp_path):+ """End to end on a fake browser: a denial file turns the next call's+ failure into CloakBrowserLicenseError."""+ from cloakbrowser.browser import guard_browser+ from cloakbrowser.license import LICENSE_STATUS_FILE_ENV, CloakBrowserLicenseError++ class FakeBrowser:+ def new_page(self):+ raise RuntimeError("Target page, context or browser has been closed")++ denial = tmp_path / "d.json"+ denial.write_text("77")+ browser = FakeBrowser()+ guard_browser(browser, {"env": {LICENSE_STATUS_FILE_ENV: str(denial)}})++ with pytest.raises(CloakBrowserLicenseError):+ browser.new_page()++def test_build_launch_options_removed_backend_raises():"""Removed kwargs still fail before any launch side effects."""from cloakbrowser.browser import build_launch_options@@ -185,11 +283,12 @@ def test_launch_delegates_to_build_launch_options_and_humanize_browser():browser_version="148.0.7778.215.4",release_channel=None,_suppress_maximize=True,- _status_file=ANY,timeout=1234,)pw.chromium.launch.assert_called_once_with(**launch_opts)mock_humanize.assert_called_once_with(browser, "careful", overrides)+ # Proxy given but no Playwright "proxy" option -> it went as --proxy-server (#579).+ browser._impl_obj.on.assert_called_once_with("context", ANY)assert result is browser@@ -203,9 +302,11 @@ async def test_launch_async_delegates_to_build_launch_options():"headless": True,"args": ["--custom-flag"],"ignore_default_args": IGNORE_DEFAULT_ARGS,+ "proxy": {"server": "http://proxy:8080"},"timeout": 1234,}browser = AsyncMock()+ browser._impl_obj = MagicMock()pw = MagicMock()pw.chromium.launch = AsyncMock(return_value=browser)pw.stop = AsyncMock()@@ -247,8 +348,9 @@ async def test_launch_async_delegates_to_build_launch_options():browser_version="148.0.7778.215.4",release_channel=None,_suppress_maximize=False,- _status_file=ANY,timeout=1234,)pw.chromium.launch.assert_awaited_once_with(**launch_opts)+ # Proxy went through Playwright's own option -> no #579 warning hook.+ browser._impl_obj.on.assert_not_called()assert result is browser