cloudflare-skip 2.0.0__tar.gz → 2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cloudflare-skip
3
- Version: 2.0.0
3
+ Version: 2.1.0
4
4
  Summary: Skip Cloudflare challenges: solve once in a real browser, then reuse the clearance with fast HTTP requests.
5
5
  Project-URL: Homepage, https://github.com/tn3w/cloudflare-skip
6
6
  Project-URL: Source, https://github.com/tn3w/cloudflare-skip
@@ -55,15 +55,17 @@ with fast HTTP requests. No display needed.**
55
55
  pip install cloudflare-skip
56
56
  cloudflare-skip https://cl-skip.tn3w.dev # non-interactive challenge
57
57
  cloudflare-skip https://cl-skip.tn3w.dev/interactive # interactive (checkbox) challenge
58
+ cloudflare-skip --turnstile https://cl-skip.tn3w.dev/turnstile # print a widget token
58
59
  ```
59
60
 
60
61
  ```python
61
- from cloudflare_skip import get, solve
62
+ from cloudflare_skip import get, solve, solve_turnstile
62
63
 
63
64
  response = get("https://cl-skip.tn3w.dev", params={"q": "x"}, timeout=10)
64
65
  print(response.status_code, response.text)
65
66
 
66
67
  clearance = solve("https://cl-skip.tn3w.dev") # {"cookies": {...}, "user_agent": "..."}
68
+ token = solve_turnstile("https://cl-skip.tn3w.dev/turnstile") # cf-turnstile-response
67
69
  ```
68
70
 
69
71
  `get(url, **kwargs)` returns a `curl_cffi` response; keyword arguments (`params`,
@@ -71,6 +73,36 @@ clearance = solve("https://cl-skip.tn3w.dev") # {"cookies": {...}, "user_agent"
71
73
  Cloudflare still challenges after a solve and `TimeoutError` if the browser cannot solve
72
74
  within 30s. The CLI prints the body, writes the status to stderr and exits 1 on 4xx/5xx.
73
75
 
76
+ ### Turnstile widgets in your own flows
77
+
78
+ Sites that embed Turnstile themselves answer `200` without `cf-mitigated`, so `get`
79
+ can't see it. Get a token with `solve_turnstile` and send it where the site's own
80
+ JavaScript would (form field, JSON body or header; check the browser's network tab):
81
+
82
+ ```python
83
+ from cloudflare_skip import session, solve_turnstile
84
+
85
+ token = solve_turnstile("https://cl-skip.tn3w.dev/turnstile")
86
+ response = session.post(
87
+ "https://cl-skip.tn3w.dev/turnstile/verify", data={"cf-turnstile-response": token}
88
+ )
89
+ ```
90
+
91
+ If the widget only appears after a click (`turnstile.render(...)` in the site's
92
+ script), pass its sitekey and the widget is rendered on that page directly, no click
93
+ needed. Extra keyword arguments (`action`, `cData`, ...) go to `turnstile.render`; copy
94
+ them from the site's call, since the server may check `action`:
95
+
96
+ ```python
97
+ token = solve_turnstile("https://example.com/watch", sitekey="0x4AAAA...", action="play")
98
+ ```
99
+
100
+ ```bash
101
+ cloudflare-skip --sitekey 0x4AAAA... --action play https://example.com/watch
102
+ ```
103
+
104
+ Tokens are single-use and expire after 300s, so get one right before each request.
105
+
74
106
  Needs Chrome or Chromium (found on `PATH`, or set `CHROME_PATH`). Runs headless, so it
75
107
  works on servers without a display; `solve(url, headless=False)` shows the window.
76
108
  As root (e.g. in Docker) the sandbox is disabled automatically.
@@ -84,11 +116,15 @@ As root (e.g. in Docker) the sandbox is disabled automatically.
84
116
  closed shadow roots included), it is focused and ticked with `Space`.
85
117
  4. As soon as `cf_clearance` is set, cookies + user agent are cached per host in
86
118
  `~/.cache/cloudflare_skip.json` and replayed over HTTP.
119
+ 5. Turnstile widgets on normal pages: `solve_turnstile` ticks the same way and returns
120
+ the `cf-turnstile-response` token as soon as it is filled. With a sitekey it renders
121
+ its own widget on the page (loading Turnstile's script if missing) instead.
87
122
 
88
123
  | Run | Time |
89
124
  |-----|------|
90
125
  | First, browser solve (non-interactive, `/`) | ~2.7-3.1s |
91
126
  | First, browser solve (interactive, `/interactive`) | ~3.2-3.9s |
127
+ | Turnstile widget token (`/turnstile`) | ~2.3-2.8s |
92
128
  | Cached, in-process | ~0.02-0.1s |
93
129
 
94
130
  Almost all of the solve time is Cloudflare itself: Chrome is ready after 0.2s, the
@@ -120,7 +156,9 @@ uv run scripts/record.py <non-interactive|interactive> [light|dark] # header G
120
156
 
121
157
  `site/` is the test page behind https://cl-skip.tn3w.dev, put behind Cloudflare
122
158
  challenge rules: `/` gets a non-interactive challenge, `/interactive` an interactive
123
- one. `pages.yml` builds it on every push to `site/`.
159
+ one. `/turnstile` is a standalone managed Turnstile widget (no challenge rule), its
160
+ token verified server side at `/turnstile/verify`. `pages.yml` builds it on every
161
+ push to `site/`.
124
162
 
125
163
  `scripts/record.py` screencasts headless Chrome solving the challenge and encodes the
126
164
  frames with `gifski` (needs `gifski`, no display).
@@ -28,15 +28,17 @@ with fast HTTP requests. No display needed.**
28
28
  pip install cloudflare-skip
29
29
  cloudflare-skip https://cl-skip.tn3w.dev # non-interactive challenge
30
30
  cloudflare-skip https://cl-skip.tn3w.dev/interactive # interactive (checkbox) challenge
31
+ cloudflare-skip --turnstile https://cl-skip.tn3w.dev/turnstile # print a widget token
31
32
  ```
32
33
 
33
34
  ```python
34
- from cloudflare_skip import get, solve
35
+ from cloudflare_skip import get, solve, solve_turnstile
35
36
 
36
37
  response = get("https://cl-skip.tn3w.dev", params={"q": "x"}, timeout=10)
37
38
  print(response.status_code, response.text)
38
39
 
39
40
  clearance = solve("https://cl-skip.tn3w.dev") # {"cookies": {...}, "user_agent": "..."}
41
+ token = solve_turnstile("https://cl-skip.tn3w.dev/turnstile") # cf-turnstile-response
40
42
  ```
41
43
 
42
44
  `get(url, **kwargs)` returns a `curl_cffi` response; keyword arguments (`params`,
@@ -44,6 +46,36 @@ clearance = solve("https://cl-skip.tn3w.dev") # {"cookies": {...}, "user_agent"
44
46
  Cloudflare still challenges after a solve and `TimeoutError` if the browser cannot solve
45
47
  within 30s. The CLI prints the body, writes the status to stderr and exits 1 on 4xx/5xx.
46
48
 
49
+ ### Turnstile widgets in your own flows
50
+
51
+ Sites that embed Turnstile themselves answer `200` without `cf-mitigated`, so `get`
52
+ can't see it. Get a token with `solve_turnstile` and send it where the site's own
53
+ JavaScript would (form field, JSON body or header; check the browser's network tab):
54
+
55
+ ```python
56
+ from cloudflare_skip import session, solve_turnstile
57
+
58
+ token = solve_turnstile("https://cl-skip.tn3w.dev/turnstile")
59
+ response = session.post(
60
+ "https://cl-skip.tn3w.dev/turnstile/verify", data={"cf-turnstile-response": token}
61
+ )
62
+ ```
63
+
64
+ If the widget only appears after a click (`turnstile.render(...)` in the site's
65
+ script), pass its sitekey and the widget is rendered on that page directly, no click
66
+ needed. Extra keyword arguments (`action`, `cData`, ...) go to `turnstile.render`; copy
67
+ them from the site's call, since the server may check `action`:
68
+
69
+ ```python
70
+ token = solve_turnstile("https://example.com/watch", sitekey="0x4AAAA...", action="play")
71
+ ```
72
+
73
+ ```bash
74
+ cloudflare-skip --sitekey 0x4AAAA... --action play https://example.com/watch
75
+ ```
76
+
77
+ Tokens are single-use and expire after 300s, so get one right before each request.
78
+
47
79
  Needs Chrome or Chromium (found on `PATH`, or set `CHROME_PATH`). Runs headless, so it
48
80
  works on servers without a display; `solve(url, headless=False)` shows the window.
49
81
  As root (e.g. in Docker) the sandbox is disabled automatically.
@@ -57,11 +89,15 @@ As root (e.g. in Docker) the sandbox is disabled automatically.
57
89
  closed shadow roots included), it is focused and ticked with `Space`.
58
90
  4. As soon as `cf_clearance` is set, cookies + user agent are cached per host in
59
91
  `~/.cache/cloudflare_skip.json` and replayed over HTTP.
92
+ 5. Turnstile widgets on normal pages: `solve_turnstile` ticks the same way and returns
93
+ the `cf-turnstile-response` token as soon as it is filled. With a sitekey it renders
94
+ its own widget on the page (loading Turnstile's script if missing) instead.
60
95
 
61
96
  | Run | Time |
62
97
  |-----|------|
63
98
  | First, browser solve (non-interactive, `/`) | ~2.7-3.1s |
64
99
  | First, browser solve (interactive, `/interactive`) | ~3.2-3.9s |
100
+ | Turnstile widget token (`/turnstile`) | ~2.3-2.8s |
65
101
  | Cached, in-process | ~0.02-0.1s |
66
102
 
67
103
  Almost all of the solve time is Cloudflare itself: Chrome is ready after 0.2s, the
@@ -93,7 +129,9 @@ uv run scripts/record.py <non-interactive|interactive> [light|dark] # header G
93
129
 
94
130
  `site/` is the test page behind https://cl-skip.tn3w.dev, put behind Cloudflare
95
131
  challenge rules: `/` gets a non-interactive challenge, `/interactive` an interactive
96
- one. `pages.yml` builds it on every push to `site/`.
132
+ one. `/turnstile` is a standalone managed Turnstile widget (no challenge rule), its
133
+ token verified server side at `/turnstile/verify`. `pages.yml` builds it on every
134
+ push to `site/`.
97
135
 
98
136
  `scripts/record.py` screencasts headless Chrome solving the challenge and encodes the
99
137
  frames with `gifski` (needs `gifski`, no display).
@@ -22,6 +22,19 @@ POLL_SECONDS = 0.02
22
22
  KEY_SECONDS = 0.02
23
23
  RETICK_SECONDS = 2
24
24
  TURNSTILE_HOST = "challenges.cloudflare.com"
25
+ TOKEN_SCRIPT = "document.querySelector('[name=cf-turnstile-response]')?.value"
26
+ RENDER_SCRIPT = """(() => {
27
+ if (window.skipToken || window.skipRendering || !document.body) return window.skipToken;
28
+ window.skipRendering = true;
29
+ const options = {...%s, callback: token => window.skipToken = token};
30
+ const render = () => turnstile.render(
31
+ document.body.appendChild(document.createElement("div")), options);
32
+ if (window.turnstile) return render() && null;
33
+ const script = document.createElement("script");
34
+ script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
35
+ script.onload = render;
36
+ document.head.append(script);
37
+ })()"""
25
38
  BROWSERS = (
26
39
  "chromium",
27
40
  "chromium-browser",
@@ -36,7 +49,7 @@ PLATFORMS = {
36
49
  "darwin": "Macintosh; Intel Mac OS X 10_15_7",
37
50
  }
38
51
 
39
- __all__ = ["ChallengeError", "get", "solve"]
52
+ __all__ = ["ChallengeError", "get", "solve", "solve_turnstile"]
40
53
 
41
54
 
42
55
  class ChallengeError(RuntimeError):
@@ -178,19 +191,29 @@ def tick_checkbox(browser: DevTools, page: str, turnstile: str) -> bool:
178
191
  return True
179
192
 
180
193
 
181
- def read_cookies(browser: DevTools, page: str, url: str) -> dict:
194
+ def read_cookies(browser: DevTools, page: str, url: str) -> dict | None:
182
195
  cookies = browser.send("Network.getCookies", page, urls=[url])["cookies"]
183
- return {cookie["name"]: cookie["value"] for cookie in cookies}
196
+ cookies = {cookie["name"]: cookie["value"] for cookie in cookies}
197
+ return cookies if "cf_clearance" in cookies else None
184
198
 
185
199
 
186
- def wait_for_cookies(browser: DevTools, page: str, url: str) -> dict:
200
+ def token_reader(options: dict):
201
+ script = RENDER_SCRIPT % json.dumps(options) if options else TOKEN_SCRIPT
202
+
203
+ def read_token(browser: DevTools, page: str, url: str) -> str | None:
204
+ reply = browser.send("Runtime.evaluate", page, expression=script)
205
+ return reply.get("result", {}).get("value")
206
+
207
+ return read_token
208
+
209
+
210
+ def wait_for(browser: DevTools, page: str, url: str, read):
187
211
  turnstile = None
188
212
  ticked_at = -RETICK_SECONDS
189
213
  deadline = time.monotonic() + TIMEOUT_SECONDS
190
214
  while time.monotonic() < deadline:
191
- cookies = read_cookies(browser, page, url)
192
- if "cf_clearance" in cookies:
193
- return cookies
215
+ if value := read(browser, page, url):
216
+ return value
194
217
  turnstile = turnstile or find_turnstile(browser)
195
218
  due = turnstile and time.monotonic() - ticked_at > RETICK_SECONDS
196
219
  if due and tick_checkbox(browser, page, turnstile):
@@ -199,17 +222,34 @@ def wait_for_cookies(browser: DevTools, page: str, url: str) -> dict:
199
222
  raise TimeoutError(f"challenge not solved in {TIMEOUT_SECONDS}s")
200
223
 
201
224
 
202
- def solve(url: str, headless: bool = True) -> dict:
203
- """Open url in Chrome, tick Turnstile if shown, return cookies and user agent."""
225
+ def browse(url: str, headless: bool, read) -> tuple:
204
226
  executable = find_browser()
205
227
  user_agent = headful_user_agent(executable)
206
228
  with open_browser(user_agent, executable, headless) as browser:
207
229
  page = browser.attach(browser.targets("page")[0])
208
230
  browser.send("Page.navigate", page, url=url)
209
- cookies = wait_for_cookies(browser, page, url)
231
+ return wait_for(browser, page, url, read), user_agent
232
+
233
+
234
+ def solve(url: str, headless: bool = True) -> dict:
235
+ """Open url in Chrome, tick Turnstile if shown, return cookies and user agent."""
236
+ cookies, user_agent = browse(url, headless, read_cookies)
210
237
  return {"cookies": cookies, "user_agent": user_agent}
211
238
 
212
239
 
240
+ def solve_turnstile(
241
+ url: str, sitekey: str | None = None, headless: bool = True, **options
242
+ ) -> str:
243
+ """Return a Turnstile token for url, ticking the checkbox if one is shown.
244
+
245
+ Without sitekey the page's own widget is read. With sitekey (for widgets the site
246
+ renders from JavaScript, e.g. after a click) a widget is rendered on the page;
247
+ options such as action or cData go to turnstile.render.
248
+ """
249
+ render_options = {"sitekey": sitekey, **options} if sitekey else {}
250
+ return browse(url, headless, token_reader(render_options))[0]
251
+
252
+
213
253
  def is_challenge(response) -> bool:
214
254
  return response.headers.get("cf-mitigated") == "challenge"
215
255
 
@@ -0,0 +1,28 @@
1
+ """Fetch a URL through Cloudflare: python -m cloudflare_skip <url>."""
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from cloudflare_skip import get, solve_turnstile
7
+
8
+
9
+ def main() -> None:
10
+ parser = argparse.ArgumentParser(prog="cloudflare-skip", description=__doc__)
11
+ parser.add_argument("url")
12
+ parser.add_argument("--turnstile", action="store_true", help="print a widget token")
13
+ parser.add_argument("--sitekey", help="render this widget instead of the page's")
14
+ parser.add_argument("--action", help="action passed to turnstile.render")
15
+ arguments = parser.parse_args()
16
+ if arguments.turnstile or arguments.sitekey:
17
+ options = {"action": arguments.action} if arguments.action else {}
18
+ print(solve_turnstile(arguments.url, arguments.sitekey, **options))
19
+ return
20
+
21
+ response = get(arguments.url)
22
+ print(response.text)
23
+ print(response.status_code, file=sys.stderr)
24
+ raise SystemExit(response.status_code >= 400)
25
+
26
+
27
+ if __name__ == "__main__":
28
+ main()
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cloudflare-skip"
7
- version = "2.0.0"
7
+ version = "2.1.0"
8
8
  description = "Skip Cloudflare challenges: solve once in a real browser, then reuse the clearance with fast HTTP requests."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -1,3 +1,4 @@
1
+ import os
1
2
  from types import SimpleNamespace
2
3
 
3
4
  import pytest
@@ -112,3 +113,16 @@ def test_get_solves_once_then_reuses_the_cached_clearance(monkeypatch):
112
113
  assert cloudflare_skip.get("https://a.example/").status_code == 200
113
114
  assert cloudflare_skip.get("https://a.example/").status_code == 200
114
115
  assert solved == ["https://a.example/"]
116
+
117
+
118
+ @pytest.mark.skipif("CI" in os.environ, reason="solves on the live site")
119
+ @pytest.mark.parametrize("sitekey", [None, "0x4AAAAAAGXZsO5-kbdi19sE"])
120
+ def test_turnstile_token_passes_server_side_verification(sitekey):
121
+ url = "https://cl-skip.tn3w.dev/turnstile"
122
+ token = cloudflare_skip.solve_turnstile(url, sitekey, action="test")
123
+ response = cloudflare_skip.session.post(
124
+ "https://cl-skip.tn3w.dev/turnstile/verify", data={"cf-turnstile-response": token}
125
+ )
126
+
127
+ assert response.status_code == 200
128
+ assert "✅ You passed the challenge." in response.text
@@ -1,19 +0,0 @@
1
- """Fetch a URL through Cloudflare: python -m cloudflare_skip <url>."""
2
-
3
- import argparse
4
- import sys
5
-
6
- from cloudflare_skip import get
7
-
8
-
9
- def main() -> None:
10
- parser = argparse.ArgumentParser(prog="cloudflare-skip", description=__doc__)
11
- parser.add_argument("url")
12
- response = get(parser.parse_args().url)
13
- print(response.text)
14
- print(response.status_code, file=sys.stderr)
15
- raise SystemExit(response.status_code >= 400)
16
-
17
-
18
- if __name__ == "__main__":
19
- main()
File without changes