playwright-turnstile 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .pytest_cache/
7
+ .venv/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.5
2
+ Name: playwright-turnstile
3
+ Version: 0.1.0
4
+ Summary: Solve Cloudflare Turnstile in Playwright by handing the token off to the Peak API instead of clicking the widget.
5
+ Project-URL: Source, https://github.com/CircuitSavage/playwright-turnstile
6
+ Project-URL: Homepage, https://peak.fo/?utm_source=github&utm_medium=pypi&utm_campaign=packages&utm_content=playwright-turnstile
7
+ Project-URL: Documentation, https://peak.fo/docs/turnstile?utm_source=github&utm_medium=pypi&utm_campaign=packages&utm_content=playwright-turnstile
8
+ Author: Peak
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: bypass,captcha,cloudflare,playwright,solver,turnstile
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
21
+ Classifier: Topic :: Software Development :: Testing
22
+ Requires-Python: >=3.9
23
+ Provides-Extra: playwright
24
+ Requires-Dist: playwright>=1.30; extra == 'playwright'
25
+ Description-Content-Type: text/markdown
26
+
27
+ <a href="https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile">
28
+ <img src="https://raw.githubusercontent.com/CircuitSavage/playwright-turnstile/main/assets/peak-banner.png" alt="Peak — solve Cloudflare Turnstile & the 5s challenge in ~1s" width="100%">
29
+ </a>
30
+
31
+ # playwright-turnstile
32
+
33
+ **playwright-turnstile** is a Playwright helper that solves Cloudflare Turnstile for you: it reads the sitekey off the page, gets a token from Peak, and injects it so your submit or navigation goes through.
34
+
35
+ ```python
36
+ from playwright_turnstile import solve_turnstile
37
+
38
+ token = await solve_turnstile(page, api_key="pk_your_api_key")
39
+ ```
40
+
41
+ ## Why
42
+
43
+ `playwright-stealth` is a proof of concept. Even with a patched, real browser, interactive Turnstile still fails from headless and datacenter environments: the widget scores the session, sees a datacenter IP with no trusted history, and holds you at the "Verifying..." spinner or an endless challenge. Clicking the checkbox harder does not help, because the token you need is issued by Cloudflare's risk engine, not by the click.
44
+
45
+ So this package does not click. It reads the Turnstile sitekey from the DOM, hands it to Peak, and injects the returned token into `cf-turnstile-response` while firing the widget's success callback. When your setup gets blocked, drop in a Peak API key and it just works.
46
+
47
+ ## Powered by Peak
48
+
49
+ This package uses [Peak](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile) to solve Turnstile.
50
+
51
+ - Solve Cloudflare Turnstile & the 5s challenge in about a second
52
+ - Pay only for successful solves — from $1 / 1,000
53
+ - 1,000 free solves to start, no card.
54
+
55
+ → [Get your free API key](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile) · [Docs](https://peak.fo/docs/turnstile?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile) · [Pricing](https://peak.fo/pricing?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile)
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pip install playwright-turnstile playwright
61
+ playwright install chromium
62
+ ```
63
+
64
+ The core package has no runtime dependencies; `playwright` is the one you drive it with.
65
+
66
+ ## Quickstart
67
+
68
+ ```python
69
+ import asyncio
70
+ from playwright.async_api import async_playwright
71
+ from playwright_turnstile import solve_turnstile
72
+
73
+ async def main():
74
+ async with async_playwright() as p:
75
+ browser = await p.chromium.launch(headless=True)
76
+ page = await browser.new_page()
77
+ await page.goto("https://protected.example/login")
78
+
79
+ # Reads the sitekey, solves via Peak, injects the token.
80
+ await solve_turnstile(page, api_key="pk_your_api_key")
81
+
82
+ await page.click("button[type=submit]")
83
+ await page.wait_for_load_state("networkidle")
84
+ await browser.close()
85
+
86
+ asyncio.run(main())
87
+ ```
88
+
89
+ Set your key once and let it read from the environment:
90
+
91
+ ```bash
92
+ export PEAK_API_KEY=pk_your_api_key # Windows: set PEAK_API_KEY=pk_your_api_key
93
+ ```
94
+
95
+ ```python
96
+ await solve_turnstile(page) # picks up PEAK_API_KEY
97
+ ```
98
+
99
+ ## API
100
+
101
+ ### `await solve_turnstile(page, api_key=None, proxy=None, sitekey=None, timeout=180.0)`
102
+
103
+ Solve the Turnstile challenge on a Playwright **async** `Page`. Returns the token (also injected into the page).
104
+
105
+ - `page` — a Playwright async `Page` on a Turnstile-protected URL.
106
+ - `api_key` — Peak key (`pk_...`). Falls back to the `PEAK_API_KEY` env var.
107
+ - `proxy` — optional proxy passed to Peak, e.g. `http://user:pass@ip:port`. Use the same egress IP as your browser so the token matches the session.
108
+ - `sitekey` — override the sitekey instead of reading it from the DOM.
109
+ - `timeout` — seconds to wait for Peak.
110
+
111
+ ### `solve_turnstile_sync(page, ...)`
112
+
113
+ Same signature, for Playwright's **sync** API (`sync_playwright`). Blocking.
114
+
115
+ ```python
116
+ from playwright_turnstile import solve_turnstile_sync
117
+
118
+ with sync_playwright() as p:
119
+ page = p.chromium.launch().new_page()
120
+ page.goto("https://protected.example/login")
121
+ solve_turnstile_sync(page, api_key="pk_your_api_key")
122
+ ```
123
+
124
+ ## How it works
125
+
126
+ 1. Reads the sitekey from the widget (`.cf-turnstile[data-sitekey]`, any `[data-sitekey]`, or the `challenges.cloudflare.com` iframe `src`) via `query_selector` / `evaluate`.
127
+ 2. Calls Peak `POST https://api.peak.fo/solve` with `task_type: "turnstiletask"`, the `sitekey`, `url: page.url`, and your optional `proxy`.
128
+ 3. Injects the returned token into every `cf-turnstile-response` field (creating a hidden input if the widget has not yet) and invokes the widget's `data-callback`, so your form submit or navigation proceeds.
129
+
130
+ Peak also supports the Cloudflare 5s challenge (`task_type: "cloudflare5stask"`); this package focuses on Turnstile.
131
+
132
+ ## Legitimate use
133
+
134
+ Built for automation, QA, and scraping public data. Respect each target's Terms of Service and `robots.txt`, and do not use it for credential-stuffing or other abuse. You are responsible for how you use it.
135
+
136
+ ## License
137
+
138
+ MIT — see [LICENSE](./LICENSE).
@@ -0,0 +1,112 @@
1
+ <a href="https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile">
2
+ <img src="https://raw.githubusercontent.com/CircuitSavage/playwright-turnstile/main/assets/peak-banner.png" alt="Peak — solve Cloudflare Turnstile & the 5s challenge in ~1s" width="100%">
3
+ </a>
4
+
5
+ # playwright-turnstile
6
+
7
+ **playwright-turnstile** is a Playwright helper that solves Cloudflare Turnstile for you: it reads the sitekey off the page, gets a token from Peak, and injects it so your submit or navigation goes through.
8
+
9
+ ```python
10
+ from playwright_turnstile import solve_turnstile
11
+
12
+ token = await solve_turnstile(page, api_key="pk_your_api_key")
13
+ ```
14
+
15
+ ## Why
16
+
17
+ `playwright-stealth` is a proof of concept. Even with a patched, real browser, interactive Turnstile still fails from headless and datacenter environments: the widget scores the session, sees a datacenter IP with no trusted history, and holds you at the "Verifying..." spinner or an endless challenge. Clicking the checkbox harder does not help, because the token you need is issued by Cloudflare's risk engine, not by the click.
18
+
19
+ So this package does not click. It reads the Turnstile sitekey from the DOM, hands it to Peak, and injects the returned token into `cf-turnstile-response` while firing the widget's success callback. When your setup gets blocked, drop in a Peak API key and it just works.
20
+
21
+ ## Powered by Peak
22
+
23
+ This package uses [Peak](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile) to solve Turnstile.
24
+
25
+ - Solve Cloudflare Turnstile & the 5s challenge in about a second
26
+ - Pay only for successful solves — from $1 / 1,000
27
+ - 1,000 free solves to start, no card.
28
+
29
+ → [Get your free API key](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile) · [Docs](https://peak.fo/docs/turnstile?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile) · [Pricing](https://peak.fo/pricing?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=playwright-turnstile)
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install playwright-turnstile playwright
35
+ playwright install chromium
36
+ ```
37
+
38
+ The core package has no runtime dependencies; `playwright` is the one you drive it with.
39
+
40
+ ## Quickstart
41
+
42
+ ```python
43
+ import asyncio
44
+ from playwright.async_api import async_playwright
45
+ from playwright_turnstile import solve_turnstile
46
+
47
+ async def main():
48
+ async with async_playwright() as p:
49
+ browser = await p.chromium.launch(headless=True)
50
+ page = await browser.new_page()
51
+ await page.goto("https://protected.example/login")
52
+
53
+ # Reads the sitekey, solves via Peak, injects the token.
54
+ await solve_turnstile(page, api_key="pk_your_api_key")
55
+
56
+ await page.click("button[type=submit]")
57
+ await page.wait_for_load_state("networkidle")
58
+ await browser.close()
59
+
60
+ asyncio.run(main())
61
+ ```
62
+
63
+ Set your key once and let it read from the environment:
64
+
65
+ ```bash
66
+ export PEAK_API_KEY=pk_your_api_key # Windows: set PEAK_API_KEY=pk_your_api_key
67
+ ```
68
+
69
+ ```python
70
+ await solve_turnstile(page) # picks up PEAK_API_KEY
71
+ ```
72
+
73
+ ## API
74
+
75
+ ### `await solve_turnstile(page, api_key=None, proxy=None, sitekey=None, timeout=180.0)`
76
+
77
+ Solve the Turnstile challenge on a Playwright **async** `Page`. Returns the token (also injected into the page).
78
+
79
+ - `page` — a Playwright async `Page` on a Turnstile-protected URL.
80
+ - `api_key` — Peak key (`pk_...`). Falls back to the `PEAK_API_KEY` env var.
81
+ - `proxy` — optional proxy passed to Peak, e.g. `http://user:pass@ip:port`. Use the same egress IP as your browser so the token matches the session.
82
+ - `sitekey` — override the sitekey instead of reading it from the DOM.
83
+ - `timeout` — seconds to wait for Peak.
84
+
85
+ ### `solve_turnstile_sync(page, ...)`
86
+
87
+ Same signature, for Playwright's **sync** API (`sync_playwright`). Blocking.
88
+
89
+ ```python
90
+ from playwright_turnstile import solve_turnstile_sync
91
+
92
+ with sync_playwright() as p:
93
+ page = p.chromium.launch().new_page()
94
+ page.goto("https://protected.example/login")
95
+ solve_turnstile_sync(page, api_key="pk_your_api_key")
96
+ ```
97
+
98
+ ## How it works
99
+
100
+ 1. Reads the sitekey from the widget (`.cf-turnstile[data-sitekey]`, any `[data-sitekey]`, or the `challenges.cloudflare.com` iframe `src`) via `query_selector` / `evaluate`.
101
+ 2. Calls Peak `POST https://api.peak.fo/solve` with `task_type: "turnstiletask"`, the `sitekey`, `url: page.url`, and your optional `proxy`.
102
+ 3. Injects the returned token into every `cf-turnstile-response` field (creating a hidden input if the widget has not yet) and invokes the widget's `data-callback`, so your form submit or navigation proceeds.
103
+
104
+ Peak also supports the Cloudflare 5s challenge (`task_type: "cloudflare5stask"`); this package focuses on Turnstile.
105
+
106
+ ## Legitimate use
107
+
108
+ Built for automation, QA, and scraping public data. Respect each target's Terms of Service and `robots.txt`, and do not use it for credential-stuffing or other abuse. You are responsible for how you use it.
109
+
110
+ ## License
111
+
112
+ MIT — see [LICENSE](./LICENSE).
@@ -0,0 +1,41 @@
1
+ """Async example: solve Turnstile on a protected page, then submit.
2
+
3
+ Run:
4
+ pip install playwright-turnstile playwright
5
+ playwright install chromium
6
+ export PEAK_API_KEY=pk_your_api_key # Windows: set PEAK_API_KEY=pk_your_api_key
7
+ python async_example.py
8
+ """
9
+
10
+ import asyncio
11
+ import os
12
+
13
+ from playwright.async_api import async_playwright
14
+
15
+ from playwright_turnstile import solve_turnstile
16
+
17
+ TARGET_URL = "https://protected.example/login"
18
+
19
+
20
+ async def main():
21
+ api_key = os.environ.get("PEAK_API_KEY", "pk_your_api_key")
22
+
23
+ async with async_playwright() as p:
24
+ browser = await p.chromium.launch(headless=True)
25
+ page = await browser.new_page()
26
+ await page.goto(TARGET_URL)
27
+
28
+ # Solve the Turnstile challenge and inject the token.
29
+ token = await solve_turnstile(page, api_key=api_key)
30
+ print("Turnstile solved, token injected:", token[:24], "...")
31
+
32
+ # The token is now in cf-turnstile-response and the widget callback has
33
+ # fired, so a normal submit / navigation proceeds.
34
+ await page.click("button[type=submit]")
35
+ await page.wait_for_load_state("networkidle")
36
+
37
+ await browser.close()
38
+
39
+
40
+ if __name__ == "__main__":
41
+ asyncio.run(main())
@@ -0,0 +1,39 @@
1
+ """Sync example using Playwright's synchronous API.
2
+
3
+ Run:
4
+ pip install playwright-turnstile playwright
5
+ playwright install chromium
6
+ export PEAK_API_KEY=pk_your_api_key # Windows: set PEAK_API_KEY=pk_your_api_key
7
+ python sync_example.py
8
+ """
9
+
10
+ import os
11
+
12
+ from playwright.sync_api import sync_playwright
13
+
14
+ from playwright_turnstile import solve_turnstile_sync
15
+
16
+ TARGET_URL = "https://protected.example/login"
17
+
18
+
19
+ def main():
20
+ api_key = os.environ.get("PEAK_API_KEY", "pk_your_api_key")
21
+
22
+ with sync_playwright() as p:
23
+ browser = p.chromium.launch(headless=True)
24
+ page = browser.new_page()
25
+ page.goto(TARGET_URL)
26
+
27
+ # Optionally pass a proxy so Peak solves from the same egress IP:
28
+ # solve_turnstile_sync(page, api_key=api_key, proxy="http://user:pass@ip:port")
29
+ token = solve_turnstile_sync(page, api_key=api_key)
30
+ print("Turnstile solved, token injected:", token[:24], "...")
31
+
32
+ page.click("button[type=submit]")
33
+ page.wait_for_load_state("networkidle")
34
+
35
+ browser.close()
36
+
37
+
38
+ if __name__ == "__main__":
39
+ main()
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "playwright-turnstile"
7
+ version = "0.1.0"
8
+ description = "Solve Cloudflare Turnstile in Playwright by handing the token off to the Peak API instead of clicking the widget."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Peak" }]
13
+ keywords = [
14
+ "playwright",
15
+ "cloudflare",
16
+ "turnstile",
17
+ "captcha",
18
+ "solver",
19
+ "bypass",
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 4 - Beta",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: MIT License",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.9",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Topic :: Internet :: WWW/HTTP :: Browsers",
31
+ "Topic :: Software Development :: Testing",
32
+ ]
33
+ dependencies = []
34
+
35
+ [project.optional-dependencies]
36
+ playwright = ["playwright>=1.30"]
37
+
38
+ [project.urls]
39
+ Source = "https://github.com/CircuitSavage/playwright-turnstile"
40
+ Homepage = "https://peak.fo/?utm_source=github&utm_medium=pypi&utm_campaign=packages&utm_content=playwright-turnstile"
41
+ Documentation = "https://peak.fo/docs/turnstile?utm_source=github&utm_medium=pypi&utm_campaign=packages&utm_content=playwright-turnstile"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["src/playwright_turnstile"]
45
+
46
+ [tool.hatch.build.targets.sdist]
47
+ include = ["src", "README.md", "LICENSE", "examples", "tests"]
@@ -0,0 +1,24 @@
1
+ """playwright-turnstile: solve Cloudflare Turnstile in Playwright via Peak.
2
+
3
+ Real browsers still fail interactive Turnstile from headless / datacenter
4
+ environments. Instead of clicking the widget, this hands the sitekey to the
5
+ Peak API (https://peak.fo), gets a token, and injects it into the page.
6
+
7
+ from playwright_turnstile import solve_turnstile
8
+
9
+ token = await solve_turnstile(page, api_key="pk_your_api_key")
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from ._peak import PeakError, request_token
15
+ from ._turnstile import solve_turnstile, solve_turnstile_sync
16
+
17
+ __all__ = [
18
+ "solve_turnstile",
19
+ "solve_turnstile_sync",
20
+ "request_token",
21
+ "PeakError",
22
+ ]
23
+
24
+ __version__ = "0.1.0"
@@ -0,0 +1,90 @@
1
+ """Thin client for the Peak solve API (https://peak.fo).
2
+
3
+ Uses only the standard library so the package stays dependency-light. The
4
+ blocking HTTP call is wrapped in a thread by the async helper so it never
5
+ stalls the Playwright event loop.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import urllib.error
13
+ import urllib.request
14
+
15
+ PEAK_SOLVE_URL = "https://api.peak.fo/solve"
16
+ DEFAULT_TIMEOUT = 180.0
17
+
18
+
19
+ class PeakError(RuntimeError):
20
+ """Raised when Peak returns an error or the request fails."""
21
+
22
+
23
+ def _resolve_api_key(api_key: str | None) -> str:
24
+ key = api_key or os.environ.get("PEAK_API_KEY")
25
+ if not key:
26
+ raise PeakError(
27
+ "No Peak API key. Pass api_key=... or set the PEAK_API_KEY "
28
+ "environment variable. Get a free key at "
29
+ "https://peak.fo."
30
+ )
31
+ return key
32
+
33
+
34
+ def build_solve_body(sitekey: str, url: str, proxy: str | None = None) -> dict:
35
+ """Build the JSON body for a Turnstile solve task."""
36
+ body = {
37
+ "task_type": "turnstiletask",
38
+ "sitekey": sitekey,
39
+ "url": url,
40
+ }
41
+ if proxy:
42
+ body["proxy"] = proxy
43
+ return body
44
+
45
+
46
+ def request_token(
47
+ sitekey: str,
48
+ url: str,
49
+ api_key: str | None = None,
50
+ proxy: str | None = None,
51
+ timeout: float = DEFAULT_TIMEOUT,
52
+ ) -> str:
53
+ """Call Peak /solve for a Turnstile token. Blocking.
54
+
55
+ Returns the solved token string, or raises PeakError.
56
+ """
57
+ key = _resolve_api_key(api_key)
58
+ body = build_solve_body(sitekey, url, proxy)
59
+ data = json.dumps(body).encode("utf-8")
60
+ req = urllib.request.Request(
61
+ PEAK_SOLVE_URL,
62
+ data=data,
63
+ method="POST",
64
+ headers={
65
+ "X-API-Key": key,
66
+ "Content-Type": "application/json",
67
+ "Accept": "application/json",
68
+ },
69
+ )
70
+ try:
71
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
72
+ raw = resp.read()
73
+ except urllib.error.HTTPError as exc: # pragma: no cover - network path
74
+ detail = exc.read().decode("utf-8", "replace")
75
+ raise PeakError(f"Peak HTTP {exc.code}: {detail}") from exc
76
+ except urllib.error.URLError as exc: # pragma: no cover - network path
77
+ raise PeakError(f"Could not reach Peak: {exc.reason}") from exc
78
+
79
+ try:
80
+ payload = json.loads(raw)
81
+ except json.JSONDecodeError as exc:
82
+ raise PeakError(f"Peak returned invalid JSON: {raw!r}") from exc
83
+
84
+ if not payload.get("success"):
85
+ raise PeakError(f"Peak solve failed: {payload.get('error', 'unknown error')}")
86
+
87
+ token = (payload.get("data") or {}).get("token")
88
+ if not token:
89
+ raise PeakError(f"Peak response missing token: {payload!r}")
90
+ return token
@@ -0,0 +1,178 @@
1
+ """Turnstile-first Playwright helper.
2
+
3
+ Reads the Turnstile sitekey from the page, sends it to Peak for a token, then
4
+ injects the token so submit/navigation proceeds without a headless click.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+
11
+ from ._peak import PeakError, request_token
12
+
13
+ # Selectors that Cloudflare's Turnstile widget renders into the page.
14
+ _WIDGET_SELECTORS = (
15
+ ".cf-turnstile[data-sitekey]",
16
+ "[data-sitekey]",
17
+ "iframe[src*='challenges.cloudflare.com']",
18
+ )
19
+
20
+ # JS run in the page to scrape a sitekey when no element handle carries it as an
21
+ # attribute (implicit rendering, iframe-only widgets, turnstile.render config).
22
+ _FIND_SITEKEY_JS = """() => {
23
+ const el = document.querySelector('[data-sitekey]');
24
+ if (el) return el.getAttribute('data-sitekey');
25
+ const frame = document.querySelector("iframe[src*='challenges.cloudflare.com']");
26
+ if (frame) {
27
+ const m = frame.getAttribute('src').match(/[?&]sitekey=([^&]+)/);
28
+ if (m) return decodeURIComponent(m[1]);
29
+ }
30
+ return null;
31
+ }"""
32
+
33
+ # JS run in the page to inject the solved token. Sets every Turnstile / reCAPTCHA
34
+ # style response field, creating a hidden input if the widget has not made one
35
+ # yet, then fires the widget's success callback so the host page's handler runs.
36
+ _INJECT_TOKEN_JS = """(token) => {
37
+ const names = ['cf-turnstile-response', 'g-recaptcha-response'];
38
+ const setField = (name) => {
39
+ let fields = Array.from(document.querySelectorAll(
40
+ `[name="${name}"], #${name.replace(/[^a-zA-Z0-9_-]/g, '')}`
41
+ ));
42
+ if (fields.length === 0) {
43
+ const input = document.createElement('input');
44
+ input.type = 'hidden';
45
+ input.name = name;
46
+ const form = document.querySelector('form');
47
+ (form || document.body).appendChild(input);
48
+ fields = [input];
49
+ }
50
+ for (const f of fields) {
51
+ f.value = token;
52
+ f.dispatchEvent(new Event('input', { bubbles: true }));
53
+ f.dispatchEvent(new Event('change', { bubbles: true }));
54
+ }
55
+ };
56
+ names.forEach(setField);
57
+
58
+ let called = false;
59
+ const widget = document.querySelector('.cf-turnstile[data-callback], [data-callback]');
60
+ if (widget) {
61
+ const cbName = widget.getAttribute('data-callback');
62
+ if (cbName && typeof window[cbName] === 'function') {
63
+ try { window[cbName](token); called = true; } catch (e) {}
64
+ }
65
+ }
66
+ return { injected: true, callbackInvoked: called };
67
+ }"""
68
+
69
+
70
+ async def _read_sitekey(page) -> str | None:
71
+ """Read the Turnstile sitekey from the widget in the DOM."""
72
+ for selector in _WIDGET_SELECTORS:
73
+ element = await page.query_selector(selector)
74
+ if element is None:
75
+ continue
76
+ try:
77
+ sitekey = await element.get_attribute("data-sitekey")
78
+ except Exception:
79
+ sitekey = None
80
+ if sitekey:
81
+ return sitekey
82
+ # Fallback: scrape it in-page (covers iframe src / implicit render).
83
+ return await page.evaluate(_FIND_SITEKEY_JS)
84
+
85
+
86
+ async def solve_turnstile(
87
+ page,
88
+ api_key: str | None = None,
89
+ proxy: str | None = None,
90
+ sitekey: str | None = None,
91
+ timeout: float = 180.0,
92
+ ) -> str:
93
+ """Solve the Cloudflare Turnstile challenge on ``page`` via Peak.
94
+
95
+ Reads the sitekey from the page (unless one is passed), asks Peak for a
96
+ token, then injects that token and fires the widget callback so the page's
97
+ submit/navigation can proceed.
98
+
99
+ Args:
100
+ page: A Playwright async ``Page`` sitting on a Turnstile-protected page.
101
+ api_key: Peak API key. Falls back to the ``PEAK_API_KEY`` env var.
102
+ proxy: Optional proxy string passed to Peak, e.g.
103
+ ``http://user:pass@ip:port``. Use the same egress IP as the browser.
104
+ sitekey: Override the sitekey instead of reading it from the DOM.
105
+ timeout: Seconds to wait for Peak to return a token.
106
+
107
+ Returns:
108
+ The solved Turnstile token (also injected into the page).
109
+
110
+ Raises:
111
+ PeakError: if no sitekey is found, or Peak fails to solve.
112
+ """
113
+ if sitekey is None:
114
+ sitekey = await _read_sitekey(page)
115
+ if not sitekey:
116
+ raise PeakError(
117
+ "No Turnstile sitekey found on the page. Is the widget loaded? "
118
+ "You can pass sitekey=... explicitly."
119
+ )
120
+
121
+ url = page.url
122
+
123
+ token = await asyncio.to_thread(
124
+ request_token,
125
+ sitekey,
126
+ url,
127
+ api_key=api_key,
128
+ proxy=proxy,
129
+ timeout=timeout,
130
+ )
131
+
132
+ await page.evaluate(_INJECT_TOKEN_JS, token)
133
+ return token
134
+
135
+
136
+ def solve_turnstile_sync(
137
+ page,
138
+ api_key: str | None = None,
139
+ proxy: str | None = None,
140
+ sitekey: str | None = None,
141
+ timeout: float = 180.0,
142
+ ) -> str:
143
+ """Blocking convenience wrapper around Turnstile solving for the sync API.
144
+
145
+ Use this with Playwright's *sync* API (``sync_playwright``), where ``page``
146
+ methods return values directly instead of awaitables.
147
+ """
148
+ if sitekey is None:
149
+ sitekey = _read_sitekey_sync(page)
150
+ if not sitekey:
151
+ raise PeakError(
152
+ "No Turnstile sitekey found on the page. Is the widget loaded? "
153
+ "You can pass sitekey=... explicitly."
154
+ )
155
+
156
+ token = request_token(
157
+ sitekey,
158
+ page.url,
159
+ api_key=api_key,
160
+ proxy=proxy,
161
+ timeout=timeout,
162
+ )
163
+ page.evaluate(_INJECT_TOKEN_JS, token)
164
+ return token
165
+
166
+
167
+ def _read_sitekey_sync(page) -> str | None:
168
+ for selector in _WIDGET_SELECTORS:
169
+ element = page.query_selector(selector)
170
+ if element is None:
171
+ continue
172
+ try:
173
+ sitekey = element.get_attribute("data-sitekey")
174
+ except Exception:
175
+ sitekey = None
176
+ if sitekey:
177
+ return sitekey
178
+ return page.evaluate(_FIND_SITEKEY_JS)
@@ -0,0 +1,215 @@
1
+ """Tests for playwright-turnstile.
2
+
3
+ No real Playwright browser and no live Peak key are required. Peak's HTTP layer
4
+ is mocked, and a fake async ``page`` implements only the methods the helper
5
+ calls. Run: ``python -m unittest discover -s tests -v`` (or ``python -m pytest``).
6
+ """
7
+
8
+ import io
9
+ import json
10
+ import os
11
+ import sys
12
+ import unittest
13
+ from unittest import mock
14
+
15
+ # Make ``src`` importable without installing the package.
16
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
17
+
18
+ from playwright_turnstile import PeakError, solve_turnstile, solve_turnstile_sync # noqa: E402
19
+ from playwright_turnstile import _peak # noqa: E402
20
+ from playwright_turnstile._peak import build_solve_body # noqa: E402
21
+
22
+ SAMPLE_SITEKEY = "0x4AAAAAAABkMYinukE8nzYS"
23
+ SAMPLE_URL = "https://protected.example/login"
24
+ TEST_TOKEN = "XXXX.TEST"
25
+
26
+
27
+ class FakeElement:
28
+ """Stand-in for a Playwright ElementHandle."""
29
+
30
+ def __init__(self, attrs):
31
+ self._attrs = attrs
32
+
33
+ async def get_attribute(self, name):
34
+ return self._attrs.get(name)
35
+
36
+
37
+ class FakePage:
38
+ """Async fake of a Playwright Page exposing only what the helper uses."""
39
+
40
+ def __init__(self, sitekey=SAMPLE_SITEKEY, url=SAMPLE_URL):
41
+ self.url = url
42
+ self._sitekey = sitekey
43
+ self.query_selector_calls = []
44
+ self.evaluate_calls = [] # list of (js, arg)
45
+
46
+ async def query_selector(self, selector):
47
+ self.query_selector_calls.append(selector)
48
+ if self._sitekey and "data-sitekey" in selector:
49
+ return FakeElement({"data-sitekey": self._sitekey})
50
+ return None
51
+
52
+ async def evaluate(self, js, *args):
53
+ self.evaluate_calls.append((js, args[0] if args else None))
54
+ # Emulate the in-page injection return value.
55
+ if "cf-turnstile-response" in js:
56
+ return {"injected": True, "callbackInvoked": True}
57
+ # Emulate the sitekey-scrape fallback.
58
+ return self._sitekey
59
+
60
+
61
+ def make_urlopen(captured, response=None):
62
+ """Build a fake urlopen that records the request and returns a canned body."""
63
+ if response is None:
64
+ response = {"success": True, "data": {"token": TEST_TOKEN}, "cost": 0.001}
65
+ payload = json.dumps(response).encode("utf-8")
66
+
67
+ def fake_urlopen(req, timeout=None):
68
+ captured["url"] = req.full_url
69
+ captured["method"] = req.get_method()
70
+ captured["headers"] = {k.lower(): v for k, v in req.header_items()}
71
+ captured["body"] = json.loads(req.data.decode("utf-8"))
72
+ captured["timeout"] = timeout
73
+ return io.BytesIO(payload)
74
+
75
+ return fake_urlopen
76
+
77
+
78
+ class SolveBodyTests(unittest.TestCase):
79
+ def test_body_omits_proxy_when_absent(self):
80
+ body = build_solve_body(SAMPLE_SITEKEY, SAMPLE_URL)
81
+ self.assertEqual(
82
+ body,
83
+ {"task_type": "turnstiletask", "sitekey": SAMPLE_SITEKEY, "url": SAMPLE_URL},
84
+ )
85
+ self.assertNotIn("proxy", body)
86
+
87
+ def test_body_includes_proxy_when_given(self):
88
+ body = build_solve_body(SAMPLE_SITEKEY, SAMPLE_URL, proxy="http://u:p@1.2.3.4:8000")
89
+ self.assertEqual(body["proxy"], "http://u:p@1.2.3.4:8000")
90
+
91
+
92
+ class SolveTurnstileTests(unittest.IsolatedAsyncioTestCase):
93
+ async def test_reads_sitekey_calls_peak_and_injects_token(self):
94
+ page = FakePage()
95
+ captured = {}
96
+
97
+ with mock.patch.object(_peak.urllib.request, "urlopen", make_urlopen(captured)):
98
+ token = await solve_turnstile(page, api_key="pk_test_key")
99
+
100
+ # Token returned.
101
+ self.assertEqual(token, TEST_TOKEN)
102
+
103
+ # Sitekey was read from the DOM widget.
104
+ self.assertTrue(
105
+ any("data-sitekey" in sel for sel in page.query_selector_calls),
106
+ "helper never queried a [data-sitekey] widget",
107
+ )
108
+
109
+ # Peak was called with the correct endpoint, method, header and body.
110
+ self.assertEqual(captured["url"], "https://api.peak.fo/solve")
111
+ self.assertEqual(captured["method"], "POST")
112
+ self.assertEqual(captured["headers"].get("x-api-key"), "pk_test_key")
113
+ self.assertEqual(
114
+ captured["body"],
115
+ {
116
+ "task_type": "turnstiletask",
117
+ "sitekey": SAMPLE_SITEKEY,
118
+ "url": SAMPLE_URL,
119
+ },
120
+ )
121
+
122
+ # Token was injected via a page.evaluate call carrying the token + JS.
123
+ inject_calls = [
124
+ (js, arg) for (js, arg) in page.evaluate_calls if "cf-turnstile-response" in js
125
+ ]
126
+ self.assertEqual(len(inject_calls), 1, "expected exactly one injection evaluate call")
127
+ inject_js, inject_arg = inject_calls[0]
128
+ self.assertEqual(inject_arg, TEST_TOKEN)
129
+ self.assertIn("data-callback", inject_js) # fires the widget success callback
130
+
131
+ async def test_proxy_is_forwarded_to_peak(self):
132
+ page = FakePage()
133
+ captured = {}
134
+ with mock.patch.object(_peak.urllib.request, "urlopen", make_urlopen(captured)):
135
+ await solve_turnstile(page, api_key="pk_test_key", proxy="http://u:p@1.2.3.4:8000")
136
+ self.assertEqual(captured["body"]["proxy"], "http://u:p@1.2.3.4:8000")
137
+
138
+ async def test_explicit_sitekey_skips_dom_read(self):
139
+ page = FakePage(sitekey=None) # DOM has no widget
140
+ captured = {}
141
+ with mock.patch.object(_peak.urllib.request, "urlopen", make_urlopen(captured)):
142
+ token = await solve_turnstile(page, api_key="pk_test_key", sitekey="0xEXPLICIT")
143
+ self.assertEqual(token, TEST_TOKEN)
144
+ self.assertEqual(captured["body"]["sitekey"], "0xEXPLICIT")
145
+
146
+ async def test_missing_sitekey_raises(self):
147
+ page = FakePage(sitekey=None)
148
+ with self.assertRaises(PeakError):
149
+ await solve_turnstile(page, api_key="pk_test_key")
150
+
151
+ async def test_peak_failure_raises(self):
152
+ page = FakePage()
153
+ captured = {}
154
+ fail = {"success": False, "error": "insufficient balance"}
155
+ with mock.patch.object(_peak.urllib.request, "urlopen", make_urlopen(captured, fail)):
156
+ with self.assertRaises(PeakError) as ctx:
157
+ await solve_turnstile(page, api_key="pk_test_key")
158
+ self.assertIn("insufficient balance", str(ctx.exception))
159
+
160
+ async def test_api_key_from_env(self):
161
+ page = FakePage()
162
+ captured = {}
163
+ with mock.patch.dict(os.environ, {"PEAK_API_KEY": "pk_env_key"}):
164
+ with mock.patch.object(_peak.urllib.request, "urlopen", make_urlopen(captured)):
165
+ await solve_turnstile(page)
166
+ self.assertEqual(captured["headers"].get("x-api-key"), "pk_env_key")
167
+
168
+ async def test_missing_api_key_raises(self):
169
+ page = FakePage()
170
+ with mock.patch.dict(os.environ, {}, clear=True):
171
+ with self.assertRaises(PeakError):
172
+ await solve_turnstile(page)
173
+
174
+
175
+ class FakeSyncElement:
176
+ def __init__(self, attrs):
177
+ self._attrs = attrs
178
+
179
+ def get_attribute(self, name):
180
+ return self._attrs.get(name)
181
+
182
+
183
+ class FakeSyncPage:
184
+ def __init__(self, sitekey=SAMPLE_SITEKEY, url=SAMPLE_URL):
185
+ self.url = url
186
+ self._sitekey = sitekey
187
+ self.evaluate_calls = []
188
+
189
+ def query_selector(self, selector):
190
+ if self._sitekey and "data-sitekey" in selector:
191
+ return FakeSyncElement({"data-sitekey": self._sitekey})
192
+ return None
193
+
194
+ def evaluate(self, js, *args):
195
+ self.evaluate_calls.append((js, args[0] if args else None))
196
+ if "cf-turnstile-response" in js:
197
+ return {"injected": True, "callbackInvoked": True}
198
+ return self._sitekey
199
+
200
+
201
+ class SolveTurnstileSyncTests(unittest.TestCase):
202
+ def test_sync_wrapper_solves_and_injects(self):
203
+ page = FakeSyncPage()
204
+ captured = {}
205
+ with mock.patch.object(_peak.urllib.request, "urlopen", make_urlopen(captured)):
206
+ token = solve_turnstile_sync(page, api_key="pk_test_key")
207
+ self.assertEqual(token, TEST_TOKEN)
208
+ self.assertEqual(captured["body"]["sitekey"], SAMPLE_SITEKEY)
209
+ inject_calls = [c for c in page.evaluate_calls if "cf-turnstile-response" in c[0]]
210
+ self.assertEqual(len(inject_calls), 1)
211
+ self.assertEqual(inject_calls[0][1], TEST_TOKEN)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ unittest.main(verbosity=2)