-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathcf_bypass.py
More file actions
244 lines (205 loc) · 10.2 KB
/
Copy pathcf_bypass.py
File metadata and controls
244 lines (205 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Cloudflare 绕过模块
借鉴 newapi-auto-checkin Chrome 扩展的思路:
- 检测 CF 拦截(403 + HTML 验证页面)
- 使用 Playwright 无头浏览器自动过 CF 防护
- 在同一浏览器会话中完成 CF 绕过 + 直接签到(不拆分为两步)
两种模式映射:
Chrome 扩展: service worker fetch → CF 拦截 → 标签页 executeScript
本项目: requests 直连 → CF 拦截 → Playwright 同会话内完成签到
"""
import os
import re
import time
from typing import Optional, Tuple
def detect_cloudflare_block(status_code: int, response_text: str) -> Tuple[bool, str]:
"""
检测 Cloudflare 拦截
借鉴 background.js:153-156 的检测逻辑:
- 403 + "Just a moment" / <!DOCTYPE html>
- 非 JSON 响应包含 <!DOCTYPE 标签
"""
if status_code == 403:
if 'Just a moment' in response_text or 'just a moment' in response_text.lower():
return True, 'Cloudflare JS Challenge (403 + Just a moment)'
if '<!DOCTYPE html' in response_text.lower() and 'cloudflare' in response_text.lower():
return True, 'Cloudflare HTML Challenge (403 + Cloudflare page)'
if status_code == 503:
if 'cloudflare' in response_text.lower() and ('challenge' in response_text.lower() or 'checking your browser' in response_text.lower()):
return True, 'Cloudflare Challenge (503)'
try:
import json
json.loads(response_text)
except (json.JSONDecodeError, ValueError):
if '<!DOCTYPE' in response_text and ('Just a moment' in response_text or 'challenge-platform' in response_text or 'cf-challenge' in response_text):
return True, 'Cloudflare Challenge (non-JSON HTML response)'
return False, ''
class CloudflareBypasser:
"""
使用 Playwright 无头浏览器绕过 Cloudflare 防护
核心设计: 在同一个浏览器会话中完成 CF 绕过和签到
(对应 Chrome 扩展在同一标签页中完成所有操作)
"""
def __init__(self, base_url: str, session_cookie: str = None, user_id: str = None):
self.base_url = base_url.rstrip('/')
self.session_cookie = session_cookie
self.user_id = user_id
self._playwright_available = self._check_playwright()
def _check_playwright(self) -> bool:
try:
from playwright.sync_api import sync_playwright
return True
except ImportError:
return False
def is_available(self) -> bool:
return self._playwright_available
def _solve_cf_challenge(self, page, max_attempts: int = 5, wait_seconds: int = 8) -> bool:
"""
解决 CF 验证挑战
"""
for attempt in range(max_attempts):
title = page.title()
current_url = page.url
print(f'[CF 绕过] 检查 CF 验证状态 (尝试 {attempt + 1}/{max_attempts}): Title="{title[:50]}"')
is_cf_challenge = (
'Just a moment' in title or
'Checking your browser' in title or
'Attention Required' in title or
'cloudflare' in title.lower() and 'challenge' in title.lower()
)
if not is_cf_challenge:
print(f'[CF 绕过] CF 验证已通过: Title="{title}"')
return True
print(f'[CF 绕过] CF 验证页面,等待自动解决 ({attempt + 1}/{max_attempts})...')
try:
page.wait_for_load_state('networkidle', timeout=30000)
except Exception:
pass
time.sleep(wait_seconds)
title = page.title()
is_cf_challenge = (
'Just a moment' in title or
'Checking your browser' in title or
'Attention Required' in title or
'cloudflare' in title.lower() and 'challenge' in title.lower()
)
if not is_cf_challenge:
print(f'[CF 绕过] CF 验证已通过: Title="{title}"')
return True
print('[CF 绕过] CF 验证未能自动解决')
return False
def bypass_and_checkin(self, timeout: int = 90) -> Optional[dict]:
"""
在同一个 Playwright 会话中完成 CF 绕过 + 签到
流程 (对应 Chrome 扩展 background.js:115-248):
1. 启动 Playwright 无头浏览器 (stealth 模式)
2. 设置 session cookie
3. 导航到目标站点,等待 CF 验证自动解决
4. CF 验证通过后,注入 user_id 到 localStorage
5. 在同一页面内调用 /api/user/checkin 完成签到
6. 返回签到结果
"""
if not self._playwright_available:
print('[CF 绕过] Playwright 未安装,无法绕过 Cloudflare')
return None
print(f'[CF 绕过] 使用 Playwright 访问 {self._mask_url(self.base_url)}...')
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
try:
browser = p.chromium.launch(
headless=True,
args=[
'--disable-blink-features=AutomationControlled',
'--no-sandbox',
'--disable-dev-shm-usage',
]
)
context = browser.new_context(
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
viewport={'width': 1920, 'height': 1080},
locale='zh-CN',
)
context.add_init_script("""
Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
window.chrome = { runtime: {} };
Object.defineProperty(navigator, 'plugins', {get: () => [1, 2, 3, 4, 5]});
Object.defineProperty(navigator, 'languages', {get: () => ['zh-CN', 'zh', 'en']});
""")
if self.session_cookie:
domain = self.base_url.replace('https://', '').replace('http://', '').split('/')[0]
context.add_cookies([
{'name': 'session', 'value': self.session_cookie, 'domain': domain, 'path': '/'}
])
page = context.new_page()
print('[CF 绕过] 正在加载页面并等待 CF 验证...')
page.goto(self.base_url, wait_until='domcontentloaded', timeout=timeout * 1000)
cf_solved = self._solve_cf_challenge(page, max_attempts=6, wait_seconds=8)
if not cf_solved:
print('[CF 绕过] CF 验证无法自动通过,尝试直接签到...')
else:
print('[CF 绕过] CF 验证已通过,准备执行签到...')
if self.user_id:
page.evaluate(f'() => localStorage.setItem("user", JSON.stringify({{"id": {self.user_id}}}))')
try:
user_text = page.evaluate('() => localStorage.getItem("user")')
if not user_text and self.session_cookie:
print('[CF 绕过] localStorage 无 user 数据, 尝试访问登录页...')
page.goto(f'{self.base_url}/login', wait_until='domcontentloaded', timeout=20000)
self._solve_cf_challenge(page, max_attempts=3, wait_seconds=5)
user_text = page.evaluate('() => localStorage.getItem("user")')
except Exception:
pass
checkin_result = page.evaluate('''async () => {
try {
const resp = await fetch('/api/user/checkin', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
credentials: 'include'
});
const text = await resp.text();
try {
const data = JSON.parse(text);
const success = data.success === true || data.status === 'success' || data.ret === 1 || data.code === 0;
const message = data.message || data.msg || data.data || '签到完成';
const msgStr = typeof message === 'string' ? message : JSON.stringify(message);
const alreadyKeywords = ['已签到', '已经签到', 'already', '重复签到'];
const alreadyCheckedIn = !success && alreadyKeywords.some(k => msgStr.includes(k));
return {
success: success || alreadyCheckedIn,
alreadyCheckedIn,
message: msgStr,
httpStatus: resp.status,
data: data
};
} catch(e) {
return { error: 'Response is not JSON: ' + text.substring(0, 200), httpStatus: resp.status, success: false };
}
} catch(e) {
return { error: e.message, success: false, httpStatus: 0 };
}
}''')
print(f'[CF 绕过] 签到结果: {checkin_result.get("message", checkin_result.get("error", "unknown"))}')
browser.close()
return checkin_result
except Exception as e:
print(f'[CF 绕过] Playwright 执行失败: {e}')
try:
browser.close()
except Exception:
pass
return None
@staticmethod
def _mask_url(url: str) -> str:
try:
from urllib.parse import urlparse
parsed = urlparse(url)
domain_parts = parsed.netloc.split('.')
if len(domain_parts) >= 2:
masked_domain = f"{domain_parts[0]}.***." + '.'.join(domain_parts[-1:])
else:
masked_domain = '***'
return f"{parsed.scheme}://{masked_domain}"
except Exception:
return 'https://***'