Skip to content

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

feat(proxy): warn when Playwright's request client skips the proxy (#579)

CloakHQ89d2c27badc0
diff --git a/README.md b/README.md
index 160e0dc..e13b6f6 100644
--- a/README.md
+++ b/README.md
@@ -1420,6 +1420,7 @@ A: Possibly. Bot detection is an arms race. Source-level patches are harder to d
**Q: Can I use my own proxy?**
A: Yes. Pass `proxy="http://user:pass@host:port"` or `proxy="socks5://user:pass@host:port"` to `launch()`. Both HTTP and SOCKS5 proxies are supported natively.
+SOCKS5 and credentialed HTTP proxies are set on the browser, so Playwright's own request client (`context.request`, `page.request`, `route.fetch()`) does not use them and sends from your real IP. Make those calls from the page instead, e.g. `page.evaluate("url => fetch(url).then(r => r.text())", url)`, which goes through the proxy like any browser request.
## Links
diff --git a/cloakbrowser/browser.py b/cloakbrowser/browser.py
index 0e3ff03..62a4cfa 100644
--- a/cloakbrowser/browser.py
+++ b/cloakbrowser/browser.py
@@ -430,6 +430,12 @@ def launch(
browser._cloak_denial_path = denial_path
_install_license_guard(browser, denial_path)
+ # Proxy went to Chrome as --proxy-server, 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:
+ browser._impl_obj.on("context", _warn_on_request_client_use)
+
# Default new_page()/new_context() to no_viewport for headed (page tracks the
# real window) and for headless on binaries that report coherent dimensions
# natively; older headless binaries keep Playwright's default viewport. Apply
@@ -556,6 +562,10 @@ async def launch_async( # noqa: C901
browser._cloak_denial_path = denial_path
_install_license_guard_async(browser, denial_path)
+ # Warn on first use of Playwright's request client (see launch(), #579).
+ if proxy_extra_args:
+ browser._impl_obj.on("context", _warn_on_request_client_use)
+
# Default new_page()/new_context() to no_viewport for headed and qualifying
# headless binaries (see launch()).
if not headless or binary_supports_headless_no_viewport(license_key, browser_version, release_channel):
@@ -712,6 +722,10 @@ 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:
+ _warn_on_request_client_use(context._impl_obj)
+
# The persistent path hands back a context, so guard it (new_page deep — see
# launch()). A persistent context also arrives with a page already open, so
# the user navigates pages[0] directly and never calls new_page — guard those
@@ -875,6 +889,10 @@ 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:
+ _warn_on_request_client_use(context._impl_obj)
+
# The persistent path hands back a context, so guard it (new_page deep — see
# 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
@@ -1740,6 +1758,45 @@ def _is_socks_proxy(proxy: str | ProxySettings | None) -> bool:
return url.lower().startswith(("socks5://", "socks5h://"))
+_request_proxy_warned = False
+
+
+def _warn_on_request_client_use(impl_context: Any) -> None:
+ """Warn once, on first use, that Playwright's request client does not use a
+ proxy we passed as --proxy-server (#579).
+
+ Playwright only proxies ``context.request`` when it owns the proxy. Its
+ get/post/fetch, ``page.request`` and ``route.fetch()`` all funnel through the
+ impl ``APIRequestContext._inner_fetch`` (shared by the sync and async APIs),
+ so one instance wrap catches every path.
+ """
+ # A per-context proxy does reach the request client, so nothing leaks there.
+ if (getattr(impl_context, "_options", None) or {}).get("proxy"):
+ return
+ request = getattr(impl_context, "_request", None)
+ original = getattr(request, "_inner_fetch", None)
+ # Private Playwright API: if it is ever renamed, skip rather than break.
+ if original is None:
+ return
+
+ async def _inner_fetch(*args: Any, **kwargs: Any) -> Any:
+ global _request_proxy_warned
+ # Self-remove so only the first call runs through us. pop() because two
+ # concurrent first calls can both land here.
+ vars(request).pop("_inner_fetch", None)
+ if not _request_proxy_warned:
+ _request_proxy_warned = True
+ # Straight to stderr so an app's logging config can't silence it.
+ sys.stderr.write(
+ "[cloakbrowser] context.request / page.request / route.fetch() do not use "
+ "this proxy (it is set on the browser, not Playwright) and will send from "
+ "your real IP. Use page.evaluate('fetch(...)') for proxied requests.\n"
+ )
+ return await original(*args, **kwargs)
+
+ request._inner_fetch = _inner_fetch
+
+
def _resolve_proxy_config(
proxy: str | ProxySettings | None,
browser_version: str | None = None,
diff --git a/dotnet/README.md b/dotnet/README.md
index 7b83f74..207e22f 100644
--- a/dotnet/README.md
+++ b/dotnet/README.md
@@ -588,7 +588,10 @@ await using var browser = await CloakLauncher.LaunchAsync(new LaunchOptions
- **SOCKS5** and **credentialed HTTP** proxies are routed through Chrome's
`--proxy-server` with inline, URL-encoded credentials (matching the Python
logic, including the `linux-x64` / `windows-x64` + binary-version gate for HTTP
- inline auth).
+ inline auth). Because these are set on the browser, Playwright's own request
+ client (`context.APIRequest`, `page.APIRequest`, `route.FetchAsync()`) does not
+ use them and sends from your real IP. Make those calls from the page instead
+ (`page.EvaluateAsync("url => fetch(url).then(r => r.text())", url)`).
- **GeoIP** looks up the proxy exit IP against MaxMind GeoLite2 and applies the
resolved timezone/locale via binary flags.
- **WebRTC** spoofing reuses that exit IP so `RTCPeerConnection` cannot leak the
diff --git a/js/README.md b/js/README.md
index 02ff18a..87d112a 100644
--- a/js/README.md
+++ b/js/README.md
@@ -83,6 +83,10 @@ const browser = await launch({
const browser = await launch({
proxy: 'socks5://user:pass@proxy:1080',
});
+// Note: SOCKS5 and credentialed HTTP proxies are set on the browser, so
+// context.request / page.request / route.fetch() do NOT use them (real IP).
+// Make those calls from the page instead, which goes through the proxy:
+const data = await page.evaluate(async (url) => (await fetch(url)).json(), 'https://example.com/api');
// With proxy object (bypass, separate auth fields)
const browser = await launch({
diff --git a/js/src/playwright.ts b/js/src/playwright.ts
index 91e59da..d9a68ab 100644
--- a/js/src/playwright.ts
+++ b/js/src/playwright.ts
@@ -13,7 +13,7 @@ import {
import { buildArgs } from "./args.js";
import { maybeWarnWindowsFonts } from "./fonts.js";
import { ensureBinary } from "./download.js";
-import { resolveProxyConfig } from "./proxy.js";
+import { resolveProxyConfig, warnOnRequestClientUse } from "./proxy.js";
import { maybeResolveGeoip, resolveWebrtcArgs, appendWebrtcExitIp } from "./geoip.js";
import {
buildLaunchEnv,
@@ -196,8 +196,10 @@ export async function launch(options: LaunchOptions = {}): Promise<Browser> {
const { chromium } = await import("playwright-core");
const denialPath = resolveLicenseKey(options.licenseKey) ? mintDenialFile() : undefined;
let browser: Browser;
+ let launchOptions: PlaywrightLaunchOptions;
try {
- browser = await chromium.launch(await buildLaunchOptions(options, denialPath));
+ launchOptions = await buildLaunchOptions(options, denialPath);
+ browser = await chromium.launch(launchOptions);
} catch (err) {
const lic = licenseErrorFrom(err);
if (lic) throw lic;
@@ -210,6 +212,16 @@ export async function launch(options: LaunchOptions = {}): Promise<Browser> {
(browser as any).__cloakDenialPath = denialPath;
installLicenseGuard(browser, denialPath);
}
+ // 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) {
+ const origNewContext = browser.newContext.bind(browser);
+ (browser as any).newContext = async (opts?: Parameters<typeof origNewContext>[0]) => {
+ const context = await origNewContext(opts);
+ warnOnRequestClientUse(context);
+ return context;
+ };
+ }
// Headed: a bare browser.newPage() would inherit Playwright's emulated 1280x720
// viewport -> outerWidth < innerWidth (impossible window = bot tell). Default
// newPage()/newContext() to viewport:null so the page tracks the real window.
@@ -392,6 +404,8 @@ export async function launchPersistentContext(
throw err;
}
+ if (proxyArgs.length) warnOnRequestClientUse(context);
+
// The persistent path hands back a context, so guard its newPage (see launch()).
if (denialPath) {
installLicenseGuard(context, denialPath);
diff --git a/js/src/proxy.ts b/js/src/proxy.ts
index 32153c8..54d973b 100644
--- a/js/src/proxy.ts
+++ b/js/src/proxy.ts
@@ -313,3 +313,39 @@ export function parseProxyUrl(proxy: string): ParsedProxy {
return result;
}
+
+let requestProxyWarned = false;
+
+/** @internal Exported for testing only. */
+export function resetRequestProxyWarned(): void {
+ requestProxyWarned = false;
+}
+
+/**
+ * Warn once, on first use, that Playwright's request client does not use a proxy
+ * we passed as --proxy-server (#579). Playwright only proxies context.request when
+ * it owns the proxy. get/post/fetch, page.request and route.fetch() all funnel
+ * through context.request._innerFetch, so one instance wrap catches every path.
+ */
+export function warnOnRequestClientUse(context: unknown): void {
+ const ctx = context as any;
+ // A per-context proxy does reach the request client, so nothing leaks there.
+ if (ctx?._options?.proxy) return;
+ const req = ctx?.request;
+ // Private Playwright API: if it is ever renamed, skip rather than break.
+ if (typeof req?._innerFetch !== "function") return;
+ req._innerFetch = function (...args: unknown[]) {
+ // Self-remove so only the first call runs through us (keeps Playwright's
+ // API-call naming in traces intact for every later call).
+ delete req._innerFetch;
+ if (!requestProxyWarned) {
+ requestProxyWarned = true;
+ console.warn(
+ "[cloakbrowser] context.request / page.request / route.fetch() do not use this proxy " +
+ "(it is set on the browser, not Playwright) and will send from your real IP. " +
+ "Use page.evaluate(() => fetch(...)) for proxied requests.",
+ );
+ }
+ return req._innerFetch(...args);
+ };
+}
diff --git a/js/tests/launch.test.ts b/js/tests/launch.test.ts
index ff63337..84b014b 100644
--- a/js/tests/launch.test.ts
+++ b/js/tests/launch.test.ts
@@ -446,8 +446,56 @@ describe("launchContext (unit)", () => {
// Warning was logged for both stripped keys
expect(warnSpy).toHaveBeenCalledTimes(2);
});
+
+ it("warns once when the request client is used with a --proxy-server proxy (#579)", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { req, inner } = mockRequestClient();
+ mockContext.request = req;
+ const { launchContext } = await import("../src/playwright.js");
+ const ctx: any = await launchContext({ proxy: "socks5://u:p@h:1080" });
+
+ expect(requestProxyWarnings(warnSpy)).toBe(0); // nothing until first use
+ await ctx.request._innerFetch({});
+ await ctx.request._innerFetch({});
+ expect(inner).toHaveBeenCalledTimes(2);
+ expect(requestProxyWarnings(warnSpy)).toBe(1);
+ });
+
+ it("no request client warning when Playwright owns the proxy (#579)", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { req, inner } = mockRequestClient();
+ mockContext.request = req;
+ const { launchContext } = await import("../src/playwright.js");
+ const ctx: any = await launchContext({ proxy: "http://h:8080" });
+
+ await ctx.request._innerFetch({});
+ expect(inner).toHaveBeenCalledOnce();
+ expect(requestProxyWarnings(warnSpy)).toBe(0);
+ });
+
+ it("no request client warning when the context has its own proxy (#579)", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { req } = mockRequestClient();
+ mockContext.request = req;
+ mockContext._options = { proxy: { server: "http://ctx-proxy:8080" } };
+ const { launchContext } = await import("../src/playwright.js");
+ const ctx: any = await launchContext({ proxy: "socks5://u:p@h:1080" });
+
+ await ctx.request._innerFetch({});
+ expect(requestProxyWarnings(warnSpy)).toBe(0);
+ });
});
+/** Request client whose _innerFetch lives on the prototype, like playwright-core's. */
+function mockRequestClient() {
+ const proto = { _innerFetch: vi.fn().mockResolvedValue("ok") };
+ return { req: Object.create(proto), inner: proto._innerFetch };
+}
+
+function requestProxyWarnings(warnSpy: { mock: { calls: unknown[][] } }): number {
+ return warnSpy.mock.calls.filter((c) => String(c[0]).includes("context.request")).length;
+}
+
describe("launchPersistentContext (unit)", () => {
let mockContext: any;
let mockChromium: any;
@@ -475,6 +523,30 @@ describe("launchPersistentContext (unit)", () => {
}
});
+ it("warns once when the request client is used with a --proxy-server proxy (#579)", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { req, inner } = mockRequestClient();
+ mockContext.request = req;
+ const { launchPersistentContext } = await import("../src/playwright.js");
+ const ctx: any = await launchPersistentContext({ userDataDir: "/tmp/profile", proxy: "socks5://u:p@h:1080" });
+
+ await ctx.request._innerFetch({});
+ await ctx.request._innerFetch({});
+ expect(inner).toHaveBeenCalledTimes(2);
+ expect(requestProxyWarnings(warnSpy)).toBe(1);
+ });
+
+ it("no request client warning when Playwright owns the proxy (#579)", async () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { req } = mockRequestClient();
+ mockContext.request = req;
+ const { launchPersistentContext } = await import("../src/playwright.js");
+ const ctx: any = await launchPersistentContext({ userDataDir: "/tmp/profile", proxy: "http://h:8080" });
+
+ await ctx.request._innerFetch({});
+ expect(requestProxyWarnings(warnSpy)).toBe(0);
+ });
+
it("applies DEFAULT_VIEWPORT", async () => {
const { launchPersistentContext } = await import("../src/playwright.js");
await launchPersistentContext({ userDataDir: "/tmp/profile" });
diff --git a/tests/test_proxy.py b/tests/test_proxy.py
index 2eda870..2fb6f76 100644
--- a/tests/test_proxy.py
+++ b/tests/test_proxy.py
@@ -1,11 +1,15 @@
"""Tests for proxy URL parsing and credential extraction."""
-from unittest.mock import patch
+import asyncio
+from unittest.mock import MagicMock, patch
+
+import pytest
from cloakbrowser.browser import (
_is_socks_proxy,
_parse_proxy_url,
_resolve_proxy_config,
+ _warn_on_request_client_use,
maybe_resolve_geoip,
)
@@ -517,3 +521,75 @@ class TestResolveProxyConfig:
kwargs, args = _resolve_proxy_config(proxy)
assert kwargs == {"proxy": proxy}
assert args == []
+
+
+class _FakeRequest:
+ """Stands in for playwright's impl APIRequestContext (method on the class)."""
+
+ def __init__(self):
+ self.calls = 0
+
+ async def _inner_fetch(self, *args, **kwargs):
+ self.calls += 1
+ return "ok"
+
+
+class _FakeContext:
+ def __init__(self, options=None):
+ self._options = options or {}
+ self._request = _FakeRequest()
+
+
+class TestRequestClientProxyWarning:
+ """#579: Playwright's request client skips a proxy passed as --proxy-server."""
+
+ @pytest.fixture(autouse=True)
+ def _reset_flag(self):
+ import cloakbrowser.browser as browser_mod
+ browser_mod._request_proxy_warned = False
+ yield
+ browser_mod._request_proxy_warned = False
+
+ def test_warns_once_on_first_use(self, capsys):
+ ctx = _FakeContext()
+ _warn_on_request_client_use(ctx)
+ assert "context.request" not in capsys.readouterr().err # nothing until used
+
+ asyncio.run(ctx._request._inner_fetch(None, "https://x"))
+ asyncio.run(ctx._request._inner_fetch(None, "https://x"))
+ assert ctx._request.calls == 2
+ assert capsys.readouterr().err.count("context.request") == 1
+
+ def test_per_context_proxy_does_not_warn(self, capsys):
+ ctx = _FakeContext({"proxy": {"server": "http://ctx-proxy:8080"}})
+ _warn_on_request_client_use(ctx)
+ asyncio.run(ctx._request._inner_fetch(None, "https://x"))
+ assert "context.request" not in capsys.readouterr().err
+
+ @pytest.mark.parametrize("proxy,hooked", [("socks5://u:p@h:1080", True), ("http://proxy:8080", False)])
+ @patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")
+ @patch("cloakbrowser.browser.maybe_resolve_geoip", return_value=(None, None, None))
+ def test_launch_hooks_only_flag_path(self, _geoip, _bin, proxy, hooked):
+ pw_cm = MagicMock()
+ browser = pw_cm.start.return_value.chromium.launch.return_value
+ with patch("playwright.sync_api.sync_playwright", return_value=pw_cm):
+ from cloakbrowser.browser import launch
+ launch(proxy=proxy)
+ calls = [c for c in browser._impl_obj.on.call_args_list if c.args == ("context", _warn_on_request_client_use)]
+ assert bool(calls) is hooked
+
+ @pytest.mark.parametrize("proxy,hooked", [("socks5://u:p@h:1080", True), ("http://proxy:8080", False)])
+ @patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")
+ @patch("cloakbrowser.browser.maybe_resolve_geoip", return_value=(None, None, None))
+ @patch("cloakbrowser.browser.persistent_seed_args", side_effect=lambda _d, _s, a: a)
+ def test_persistent_hooks_only_flag_path(self, _seed, _geoip, _bin, proxy, hooked):
+ pw_cm = MagicMock()
+ context = pw_cm.start.return_value.chromium.launch_persistent_context.return_value
+ with patch("playwright.sync_api.sync_playwright", return_value=pw_cm), \
+ patch("cloakbrowser.browser._warn_on_request_client_use") as hook:
+ from cloakbrowser.browser import launch_persistent_context
+ launch_persistent_context("/tmp/profile", proxy=proxy)
+ if hooked:
+ hook.assert_called_once_with(context._impl_obj)
+ else:
+ hook.assert_not_called()