python-xiaobiu 0.1.0__py3-none-any.whl
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.
- python_xiaobiu-0.1.0.dist-info/METADATA +68 -0
- python_xiaobiu-0.1.0.dist-info/RECORD +9 -0
- python_xiaobiu-0.1.0.dist-info/WHEEL +4 -0
- python_xiaobiu-0.1.0.dist-info/entry_points.txt +2 -0
- xiaobiu/__init__.py +35 -0
- xiaobiu/captcha_bridge.py +405 -0
- xiaobiu/client.py +1558 -0
- xiaobiu/crypto.py +66 -0
- xiaobiu/models.py +133 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-xiaobiu
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Suning biu smart home SMS login and session client
|
|
5
|
+
Project-URL: Homepage, https://github.com/FaintGhost/python-xiaobiu
|
|
6
|
+
Project-URL: Bug Tracker, https://github.com/FaintGhost/python-xiaobiu/issues
|
|
7
|
+
Author-email: FaintGhost <zhang.yaowei@live.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: climate,home-assistant,smart-home,suning
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Requires-Python: >=3.14
|
|
15
|
+
Requires-Dist: cryptography>=44.0.0
|
|
16
|
+
Requires-Dist: pydantic>=2.0.0
|
|
17
|
+
Requires-Dist: requests>=2.28.0
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# python-xiaobiu
|
|
21
|
+
|
|
22
|
+
Python client for Suning smart home SMS login and session management.
|
|
23
|
+
|
|
24
|
+
Used by the [ha-suning](https://github.com/FaintGhost/ha-suning) Home Assistant custom integration.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install python-xiaobiu
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from xiaobiu import CaptchaRequiredError, SuningSmartHomeClient
|
|
36
|
+
|
|
37
|
+
client = SuningSmartHomeClient(state_path=".suning-session.json")
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
client.send_sms_code("13800000000")
|
|
41
|
+
except CaptchaRequiredError as error:
|
|
42
|
+
print(error.risk_type, error.sms_ticket)
|
|
43
|
+
|
|
44
|
+
client.login_with_sms_code(phone_number="13800000000", sms_code="123456")
|
|
45
|
+
print(client.list_family_infos())
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## CLI
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
# Interactive login
|
|
52
|
+
xiaobiucli login --phone 13800000000 --state-file .suning-session.json
|
|
53
|
+
|
|
54
|
+
# Send SMS only
|
|
55
|
+
xiaobiucli send-sms --phone 13800000000 --state-file .suning-session.json
|
|
56
|
+
|
|
57
|
+
# Check session
|
|
58
|
+
xiaobiucli check --state-file .suning-session.json
|
|
59
|
+
|
|
60
|
+
# List families / devices
|
|
61
|
+
xiaobiucli families --state-file .suning-session.json
|
|
62
|
+
xiaobiucli devices --family-id 37790 --state-file .suning-session.json
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Requirements
|
|
66
|
+
|
|
67
|
+
- Python >= 3.14
|
|
68
|
+
- `cryptography`, `pydantic`, `requests`
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
xiaobiu/__init__.py,sha256=3I1iNM2xCUR1SM93nL2WmNfXbGB5bdgJ6Ai-1VmNImI,641
|
|
2
|
+
xiaobiu/captcha_bridge.py,sha256=l8c3HnspQt1JDM1sDKnvcM4yvf7NZosSQ7x2AlO-kEA,12920
|
|
3
|
+
xiaobiu/client.py,sha256=YXLX7wncVMmPlI8_L1XziLoGlL4Vlh3SX1l1XOZSa9k,51420
|
|
4
|
+
xiaobiu/crypto.py,sha256=C0Lcp2Cfy-075hv65b1RYfn6UbiHneLhp4PhUftzzOk,2424
|
|
5
|
+
xiaobiu/models.py,sha256=Ok_cSKm1D-dhp8hR3HMY_QlD9uTIQNZ6SnOAbNg35oM,3657
|
|
6
|
+
python_xiaobiu-0.1.0.dist-info/METADATA,sha256=J9qAc4DvSjSTLHxZ5zuG8UNoebm8gHOSCsY9IvF5Qbo,1865
|
|
7
|
+
python_xiaobiu-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
8
|
+
python_xiaobiu-0.1.0.dist-info/entry_points.txt,sha256=w1z8h63RRusoSGAbbSMpNcq4qbN3HOedsMlxwuFH3U8,44
|
|
9
|
+
python_xiaobiu-0.1.0.dist-info/RECORD,,
|
xiaobiu/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from .client import (
|
|
2
|
+
AuthenticationError,
|
|
3
|
+
CaptchaRequiredError,
|
|
4
|
+
SmsRateLimitedError,
|
|
5
|
+
SuningError,
|
|
6
|
+
SuningSmartHomeClient,
|
|
7
|
+
main,
|
|
8
|
+
parse_jsonp_or_json,
|
|
9
|
+
)
|
|
10
|
+
from .models import (
|
|
11
|
+
AirConditionerStatus,
|
|
12
|
+
AuthState,
|
|
13
|
+
CaptchaSolution,
|
|
14
|
+
FamilyInfo,
|
|
15
|
+
HAClimatePreview,
|
|
16
|
+
LoginPageConfig,
|
|
17
|
+
SignedRequestTemplate,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"AirConditionerStatus",
|
|
22
|
+
"AuthState",
|
|
23
|
+
"AuthenticationError",
|
|
24
|
+
"CaptchaRequiredError",
|
|
25
|
+
"CaptchaSolution",
|
|
26
|
+
"FamilyInfo",
|
|
27
|
+
"HAClimatePreview",
|
|
28
|
+
"LoginPageConfig",
|
|
29
|
+
"SmsRateLimitedError",
|
|
30
|
+
"SignedRequestTemplate",
|
|
31
|
+
"SuningError",
|
|
32
|
+
"SuningSmartHomeClient",
|
|
33
|
+
"main",
|
|
34
|
+
"parse_jsonp_or_json",
|
|
35
|
+
]
|
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import threading
|
|
5
|
+
from http import HTTPStatus
|
|
6
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .models import CaptchaBridgeResult
|
|
10
|
+
|
|
11
|
+
DEFAULT_RISK_CONTEXT_SCRIPT_URLS = [
|
|
12
|
+
"https://mmds.suning.com/mmds/mmds.js?appCode=qEmt9X4YmoV2Vye8",
|
|
13
|
+
"https://oss.suning.com/mmds/mmds/js/sK1di3Hh1vIKsdA/mmds.XsWjliU4H7uskWk.js",
|
|
14
|
+
"https://dfp.suning.com/dfprs-collect/dist/fp.js?appCode=qEmt9X4YmoV2Vye8",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
HTML_TEMPLATE = """<!doctype html>
|
|
18
|
+
<html lang="zh-CN">
|
|
19
|
+
<head>
|
|
20
|
+
<meta charset="utf-8">
|
|
21
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
22
|
+
<title>苏宁验证码验证</title>
|
|
23
|
+
<script src="https://iar-web.suning.com/iar-web/snstatic/SnCaptcha.js"></script>
|
|
24
|
+
<script>
|
|
25
|
+
window.__RISK_CONTEXT_SCRIPT_URLS__ = {script_urls_json};
|
|
26
|
+
window.__CAPTCHA_CALLBACK_URL__ = {callback_url_json};
|
|
27
|
+
</script>
|
|
28
|
+
<style>
|
|
29
|
+
* {{
|
|
30
|
+
box-sizing: border-box;
|
|
31
|
+
}}
|
|
32
|
+
html {{
|
|
33
|
+
min-height: 100%;
|
|
34
|
+
background: linear-gradient(180deg, #fff8ee 0%, #fff 100%);
|
|
35
|
+
}}
|
|
36
|
+
body {{
|
|
37
|
+
margin: 0;
|
|
38
|
+
min-height: 100vh;
|
|
39
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
40
|
+
color: #222;
|
|
41
|
+
display: flex;
|
|
42
|
+
justify-content: center;
|
|
43
|
+
align-items: flex-start;
|
|
44
|
+
padding: 24px 16px 40px;
|
|
45
|
+
overflow-y: auto;
|
|
46
|
+
}}
|
|
47
|
+
.card {{
|
|
48
|
+
width: min(96vw, 520px);
|
|
49
|
+
background: #fff;
|
|
50
|
+
border: 1px solid #f3d9b8;
|
|
51
|
+
border-radius: 16px;
|
|
52
|
+
box-shadow: 0 18px 48px rgba(197, 112, 26, 0.12);
|
|
53
|
+
padding: 24px;
|
|
54
|
+
}}
|
|
55
|
+
h1 {{
|
|
56
|
+
margin: 0 0 8px;
|
|
57
|
+
font-size: 20px;
|
|
58
|
+
}}
|
|
59
|
+
p {{
|
|
60
|
+
margin: 0 0 16px;
|
|
61
|
+
line-height: 1.6;
|
|
62
|
+
color: #555;
|
|
63
|
+
}}
|
|
64
|
+
.captcha-shell {{
|
|
65
|
+
display: flex;
|
|
66
|
+
justify-content: center;
|
|
67
|
+
width: 100%;
|
|
68
|
+
overflow: visible;
|
|
69
|
+
}}
|
|
70
|
+
.actions {{
|
|
71
|
+
margin-top: 12px;
|
|
72
|
+
display: flex;
|
|
73
|
+
justify-content: center;
|
|
74
|
+
}}
|
|
75
|
+
.start-btn {{
|
|
76
|
+
border: 0;
|
|
77
|
+
border-radius: 999px;
|
|
78
|
+
background: linear-gradient(135deg, #ff8a00 0%, #ff6a00 100%);
|
|
79
|
+
color: #fff;
|
|
80
|
+
font-size: 15px;
|
|
81
|
+
font-weight: 600;
|
|
82
|
+
padding: 12px 22px;
|
|
83
|
+
cursor: pointer;
|
|
84
|
+
box-shadow: 0 10px 24px rgba(255, 122, 0, 0.24);
|
|
85
|
+
}}
|
|
86
|
+
.start-btn[disabled] {{
|
|
87
|
+
cursor: wait;
|
|
88
|
+
opacity: 0.72;
|
|
89
|
+
box-shadow: none;
|
|
90
|
+
}}
|
|
91
|
+
#captcha {{
|
|
92
|
+
width: 100%;
|
|
93
|
+
min-height: 320px;
|
|
94
|
+
overflow: visible;
|
|
95
|
+
}}
|
|
96
|
+
.status {{
|
|
97
|
+
margin-top: 16px;
|
|
98
|
+
font-size: 14px;
|
|
99
|
+
color: #8a4b00;
|
|
100
|
+
white-space: pre-wrap;
|
|
101
|
+
}}
|
|
102
|
+
.status.ok {{
|
|
103
|
+
color: #0f7b0f;
|
|
104
|
+
}}
|
|
105
|
+
.status.err {{
|
|
106
|
+
color: #b42318;
|
|
107
|
+
}}
|
|
108
|
+
@media (max-width: 640px) {{
|
|
109
|
+
body {{
|
|
110
|
+
padding: 12px 10px 24px;
|
|
111
|
+
}}
|
|
112
|
+
.card {{
|
|
113
|
+
width: 100%;
|
|
114
|
+
padding: 16px;
|
|
115
|
+
border-radius: 12px;
|
|
116
|
+
}}
|
|
117
|
+
#captcha {{
|
|
118
|
+
min-height: 280px;
|
|
119
|
+
}}
|
|
120
|
+
}}
|
|
121
|
+
</style>
|
|
122
|
+
</head>
|
|
123
|
+
<body>
|
|
124
|
+
<div class="card">
|
|
125
|
+
<h1>苏宁拼图验证</h1>
|
|
126
|
+
<p>完成下方验证后,这个页面会自动把结果回传给本地程序。请先点击下方按钮开始验证。</p>
|
|
127
|
+
<div class="actions">
|
|
128
|
+
<button id="start-captcha" class="start-btn" type="button">开始验证</button>
|
|
129
|
+
</div>
|
|
130
|
+
<div class="captcha-shell">
|
|
131
|
+
<div id="captcha"></div>
|
|
132
|
+
</div>
|
|
133
|
+
<div id="status" class="status">请点击下方按钮开始验证。</div>
|
|
134
|
+
</div>
|
|
135
|
+
<script>
|
|
136
|
+
const statusEl = document.getElementById("status");
|
|
137
|
+
const cardEl = document.querySelector(".card");
|
|
138
|
+
const startButtonEl = document.getElementById("start-captcha");
|
|
139
|
+
const riskContextScripts = window.__RISK_CONTEXT_SCRIPT_URLS__ || [];
|
|
140
|
+
const callbackUrl = window.__CAPTCHA_CALLBACK_URL__ || "/callback";
|
|
141
|
+
async function loadScript(src) {{
|
|
142
|
+
await new Promise((resolve, reject) => {{
|
|
143
|
+
const script = document.createElement("script");
|
|
144
|
+
script.src = src;
|
|
145
|
+
script.async = false;
|
|
146
|
+
script.onload = resolve;
|
|
147
|
+
script.onerror = function() {{
|
|
148
|
+
reject(new Error("load failed: " + src));
|
|
149
|
+
}};
|
|
150
|
+
document.head.appendChild(script);
|
|
151
|
+
}});
|
|
152
|
+
}}
|
|
153
|
+
async function sleep(ms) {{
|
|
154
|
+
await new Promise((resolve) => window.setTimeout(resolve, ms));
|
|
155
|
+
}}
|
|
156
|
+
function readRiskContextOnce() {{
|
|
157
|
+
let detect = "";
|
|
158
|
+
let dfpToken = "";
|
|
159
|
+
try {{
|
|
160
|
+
if (typeof bd === "object" && typeof bd.rst === "function") {{
|
|
161
|
+
detect = bd.rst({{ scene: "1" }}) || "";
|
|
162
|
+
}}
|
|
163
|
+
}} catch (error) {{
|
|
164
|
+
console.warn("collect detect failed", error);
|
|
165
|
+
}}
|
|
166
|
+
try {{
|
|
167
|
+
if (typeof _dfp === "object" && typeof _dfp.getToken === "function") {{
|
|
168
|
+
dfpToken = _dfp.getToken() || "";
|
|
169
|
+
}}
|
|
170
|
+
}} catch (error) {{
|
|
171
|
+
console.warn("collect dfp token failed", error);
|
|
172
|
+
}}
|
|
173
|
+
return {{ detect, dfpToken }};
|
|
174
|
+
}}
|
|
175
|
+
async function collectRiskContext() {{
|
|
176
|
+
for (const src of riskContextScripts) {{
|
|
177
|
+
await loadScript(src);
|
|
178
|
+
}}
|
|
179
|
+
const deadline = Date.now() + 10000;
|
|
180
|
+
let lastRiskContext = readRiskContextOnce();
|
|
181
|
+
while (Date.now() < deadline) {{
|
|
182
|
+
if (lastRiskContext.detect && lastRiskContext.dfpToken) {{
|
|
183
|
+
return lastRiskContext;
|
|
184
|
+
}}
|
|
185
|
+
await sleep(250);
|
|
186
|
+
lastRiskContext = readRiskContextOnce();
|
|
187
|
+
}}
|
|
188
|
+
throw new Error("未能采集浏览器风控上下文,请刷新页面后重试。");
|
|
189
|
+
}}
|
|
190
|
+
function computeCaptchaSize() {{
|
|
191
|
+
const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 390;
|
|
192
|
+
const availableWidth = Math.max(300, Math.min(viewportWidth - 56, cardEl.clientWidth - 48, 420));
|
|
193
|
+
const width = Math.round(availableWidth);
|
|
194
|
+
const height = Math.max(300, Math.round(width * 0.88));
|
|
195
|
+
return {{
|
|
196
|
+
width: width + "px",
|
|
197
|
+
height: height + "px"
|
|
198
|
+
}};
|
|
199
|
+
}}
|
|
200
|
+
function setStatus(message, klass) {{
|
|
201
|
+
statusEl.textContent = message;
|
|
202
|
+
statusEl.className = "status" + (klass ? " " + klass : "");
|
|
203
|
+
}}
|
|
204
|
+
function setStartButtonState(disabled, label) {{
|
|
205
|
+
startButtonEl.disabled = disabled;
|
|
206
|
+
startButtonEl.textContent = label;
|
|
207
|
+
}}
|
|
208
|
+
async function startCaptcha() {{
|
|
209
|
+
if (captchaLaunchStarted) {{
|
|
210
|
+
return;
|
|
211
|
+
}}
|
|
212
|
+
captchaLaunchStarted = true;
|
|
213
|
+
setStartButtonState(true, "正在准备...");
|
|
214
|
+
riskContextPromise = collectRiskContext();
|
|
215
|
+
try {{
|
|
216
|
+
setStatus("正在准备浏览器风控环境...", "");
|
|
217
|
+
await riskContextPromise;
|
|
218
|
+
setStatus("正在初始化验证码...", "");
|
|
219
|
+
SnCaptcha.init({{
|
|
220
|
+
env: "{env}",
|
|
221
|
+
target: "captcha",
|
|
222
|
+
ticket: "{ticket}",
|
|
223
|
+
client: "app",
|
|
224
|
+
width: captchaSize.width,
|
|
225
|
+
height: captchaSize.height,
|
|
226
|
+
callback: async function(token) {{
|
|
227
|
+
if (captchaSubmitStarted) {{
|
|
228
|
+
return;
|
|
229
|
+
}}
|
|
230
|
+
captchaSubmitStarted = true;
|
|
231
|
+
try {{
|
|
232
|
+
setStatus("验证成功,正在回传结果...", "");
|
|
233
|
+
const riskContext = await riskContextPromise;
|
|
234
|
+
if (!riskContext.detect || !riskContext.dfpToken) {{
|
|
235
|
+
throw new Error("浏览器风控上下文不完整,请刷新页面后重试。");
|
|
236
|
+
}}
|
|
237
|
+
const response = await fetch(callbackUrl, {{
|
|
238
|
+
method: "POST",
|
|
239
|
+
headers: {{
|
|
240
|
+
"Content-Type": "application/json"
|
|
241
|
+
}},
|
|
242
|
+
body: JSON.stringify({{
|
|
243
|
+
token,
|
|
244
|
+
detect: riskContext.detect,
|
|
245
|
+
dfpToken: riskContext.dfpToken
|
|
246
|
+
}})
|
|
247
|
+
}});
|
|
248
|
+
if (!response.ok) {{
|
|
249
|
+
throw new Error("回传失败: " + response.status);
|
|
250
|
+
}}
|
|
251
|
+
setStatus("验证成功,已经回传给本地程序。可以回到终端继续。", "ok");
|
|
252
|
+
}} catch (error) {{
|
|
253
|
+
captchaSubmitStarted = false;
|
|
254
|
+
setStatus("验证码已完成,但回传失败,请把浏览器和终端错误一起反馈。\\n" + error, "err");
|
|
255
|
+
}}
|
|
256
|
+
}},
|
|
257
|
+
onready: function() {{
|
|
258
|
+
setStatus("验证码已加载,请按页面提示完成验证。", "");
|
|
259
|
+
setStartButtonState(true, "验证进行中");
|
|
260
|
+
}},
|
|
261
|
+
onClose: function() {{
|
|
262
|
+
if (captchaSubmitStarted) {{
|
|
263
|
+
return;
|
|
264
|
+
}}
|
|
265
|
+
setStatus("验证码窗口已关闭,如未成功请重新点击开始验证。", "");
|
|
266
|
+
captchaLaunchStarted = false;
|
|
267
|
+
setStartButtonState(false, "重新开始验证");
|
|
268
|
+
}}
|
|
269
|
+
}});
|
|
270
|
+
}} catch (error) {{
|
|
271
|
+
captchaLaunchStarted = false;
|
|
272
|
+
riskContextPromise = null;
|
|
273
|
+
setStartButtonState(false, "重新开始验证");
|
|
274
|
+
setStatus("验证码初始化失败,请刷新页面后重试。\\n" + error, "err");
|
|
275
|
+
}}
|
|
276
|
+
}}
|
|
277
|
+
let captchaSubmitStarted = false;
|
|
278
|
+
let captchaLaunchStarted = false;
|
|
279
|
+
const captchaSize = computeCaptchaSize();
|
|
280
|
+
const captchaEl = document.getElementById("captcha");
|
|
281
|
+
captchaEl.style.width = captchaSize.width;
|
|
282
|
+
captchaEl.style.minHeight = captchaSize.height;
|
|
283
|
+
let riskContextPromise = null;
|
|
284
|
+
startButtonEl.addEventListener("click", startCaptcha);
|
|
285
|
+
</script>
|
|
286
|
+
</body>
|
|
287
|
+
</html>
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def render_captcha_page(
|
|
292
|
+
*,
|
|
293
|
+
ticket: str,
|
|
294
|
+
env: str = "prd",
|
|
295
|
+
script_urls: list[str] | None = None,
|
|
296
|
+
callback_url: str = "/callback",
|
|
297
|
+
) -> str:
|
|
298
|
+
return HTML_TEMPLATE.format(
|
|
299
|
+
env=env,
|
|
300
|
+
ticket=ticket,
|
|
301
|
+
script_urls_json=json.dumps(
|
|
302
|
+
script_urls or DEFAULT_RISK_CONTEXT_SCRIPT_URLS,
|
|
303
|
+
ensure_ascii=False,
|
|
304
|
+
),
|
|
305
|
+
callback_url_json=json.dumps(callback_url, ensure_ascii=False),
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
class _ThreadedHTTPServer(ThreadingHTTPServer):
|
|
309
|
+
daemon_threads = True
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class LocalCaptchaBridge:
|
|
313
|
+
def __init__(
|
|
314
|
+
self,
|
|
315
|
+
*,
|
|
316
|
+
ticket: str,
|
|
317
|
+
env: str = "prd",
|
|
318
|
+
host: str = "127.0.0.1",
|
|
319
|
+
port: int = 0,
|
|
320
|
+
script_urls: list[str] | None = None,
|
|
321
|
+
) -> None:
|
|
322
|
+
self.ticket = ticket
|
|
323
|
+
self.env = env
|
|
324
|
+
self.host = host
|
|
325
|
+
self.port = port
|
|
326
|
+
self.script_urls = script_urls or DEFAULT_RISK_CONTEXT_SCRIPT_URLS
|
|
327
|
+
self._result: CaptchaBridgeResult | None = None
|
|
328
|
+
self._event = threading.Event()
|
|
329
|
+
self._server = self._create_server()
|
|
330
|
+
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
|
331
|
+
|
|
332
|
+
@property
|
|
333
|
+
def url(self) -> str:
|
|
334
|
+
host, port = self._server.server_address[:2]
|
|
335
|
+
return f"http://{host}:{port}/"
|
|
336
|
+
|
|
337
|
+
def start(self) -> None:
|
|
338
|
+
self._thread.start()
|
|
339
|
+
|
|
340
|
+
def wait_for_token(self, timeout: float = 300.0) -> CaptchaBridgeResult:
|
|
341
|
+
completed = self._event.wait(timeout)
|
|
342
|
+
if not completed or not self._result:
|
|
343
|
+
raise TimeoutError("等待验证码结果超时")
|
|
344
|
+
return self._result
|
|
345
|
+
|
|
346
|
+
def close(self) -> None:
|
|
347
|
+
self._server.shutdown()
|
|
348
|
+
self._server.server_close()
|
|
349
|
+
if self._thread.is_alive():
|
|
350
|
+
self._thread.join(timeout=1.0)
|
|
351
|
+
|
|
352
|
+
def _create_server(self) -> _ThreadedHTTPServer:
|
|
353
|
+
bridge = self
|
|
354
|
+
|
|
355
|
+
class Handler(BaseHTTPRequestHandler):
|
|
356
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
357
|
+
return
|
|
358
|
+
|
|
359
|
+
def do_GET(self) -> None:
|
|
360
|
+
if self.path != "/":
|
|
361
|
+
self.send_error(HTTPStatus.NOT_FOUND)
|
|
362
|
+
return
|
|
363
|
+
html = render_captcha_page(
|
|
364
|
+
env=bridge.env,
|
|
365
|
+
script_urls=bridge.script_urls,
|
|
366
|
+
callback_url="/callback",
|
|
367
|
+
ticket=bridge.ticket,
|
|
368
|
+
)
|
|
369
|
+
body = html.encode("utf-8")
|
|
370
|
+
self.send_response(HTTPStatus.OK)
|
|
371
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
372
|
+
self.send_header("Content-Length", str(len(body)))
|
|
373
|
+
self.end_headers()
|
|
374
|
+
self.wfile.write(body)
|
|
375
|
+
|
|
376
|
+
def do_POST(self) -> None:
|
|
377
|
+
if self.path != "/callback":
|
|
378
|
+
self.send_error(HTTPStatus.NOT_FOUND)
|
|
379
|
+
return
|
|
380
|
+
length = int(self.headers.get("Content-Length", "0"))
|
|
381
|
+
raw_body = self.rfile.read(length)
|
|
382
|
+
payload = json.loads(raw_body.decode("utf-8"))
|
|
383
|
+
token = (payload.get("token") or "").strip()
|
|
384
|
+
detect = (payload.get("detect") or "").strip()
|
|
385
|
+
dfp_token = (payload.get("dfpToken") or "").strip()
|
|
386
|
+
if not token:
|
|
387
|
+
self.send_error(HTTPStatus.BAD_REQUEST, "missing token")
|
|
388
|
+
return
|
|
389
|
+
if not detect or not dfp_token:
|
|
390
|
+
self.send_error(HTTPStatus.BAD_REQUEST, "missing risk context")
|
|
391
|
+
return
|
|
392
|
+
bridge._result = CaptchaBridgeResult(
|
|
393
|
+
token=token,
|
|
394
|
+
detect=detect,
|
|
395
|
+
dfp_token=dfp_token,
|
|
396
|
+
)
|
|
397
|
+
bridge._event.set()
|
|
398
|
+
body = json.dumps({"ok": True}).encode("utf-8")
|
|
399
|
+
self.send_response(HTTPStatus.OK)
|
|
400
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
401
|
+
self.send_header("Content-Length", str(len(body)))
|
|
402
|
+
self.end_headers()
|
|
403
|
+
self.wfile.write(body)
|
|
404
|
+
|
|
405
|
+
return _ThreadedHTTPServer((self.host, self.port), Handler)
|