ghostcaptcha 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.
- ghostcaptcha-0.1.0/PKG-INFO +104 -0
- ghostcaptcha-0.1.0/README.md +83 -0
- ghostcaptcha-0.1.0/ghostcaptcha/__init__.py +176 -0
- ghostcaptcha-0.1.0/ghostcaptcha.egg-info/PKG-INFO +104 -0
- ghostcaptcha-0.1.0/ghostcaptcha.egg-info/SOURCES.txt +8 -0
- ghostcaptcha-0.1.0/ghostcaptcha.egg-info/dependency_links.txt +1 -0
- ghostcaptcha-0.1.0/ghostcaptcha.egg-info/top_level.txt +1 -0
- ghostcaptcha-0.1.0/pyproject.toml +32 -0
- ghostcaptcha-0.1.0/setup.cfg +4 -0
- ghostcaptcha-0.1.0/tests/test_client.py +183 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: ghostcaptcha
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 幽灵验证码服务端 SDK:校验票据、查用量、错误码翻译(fail-closed)
|
|
5
|
+
Author: GhostCAPTCHA
|
|
6
|
+
License: UNLICENSED
|
|
7
|
+
Project-URL: Homepage, https://bwbdai.cn/api
|
|
8
|
+
Project-URL: Repository, https://github.com/ghostcaptcha/ghostcaptcha
|
|
9
|
+
Project-URL: Issues, https://github.com/ghostcaptcha/ghostcaptcha/issues
|
|
10
|
+
Keywords: captcha,ghostcaptcha,verification,bot-protection
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: License :: Other/Proprietary License
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# 幽灵验证码 · Python 服务端 SDK
|
|
23
|
+
|
|
24
|
+
零依赖(只用标准库),Python 3.8+。只做三件事:**校验票据**、**查用量**、把错误码翻译成可判断的结果。
|
|
25
|
+
|
|
26
|
+
## 安装
|
|
27
|
+
|
|
28
|
+
PyPI 尚未发布,当前从仓库本地路径安装:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install /path/to/ghostcaptcha/sdk/python
|
|
32
|
+
# 或开发模式
|
|
33
|
+
pip install -e /path/to/ghostcaptcha/sdk/python
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
发布到 PyPI 之后改成:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install ghostcaptcha
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## 快速开始
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import os
|
|
46
|
+
from ghostcaptcha import create_client, GhostCaptchaError
|
|
47
|
+
|
|
48
|
+
gc = create_client(
|
|
49
|
+
"https://api.your-domain.com",
|
|
50
|
+
os.environ["GC_SITE_KEY"],
|
|
51
|
+
os.environ["GC_SITE_SECRET"], # 只在服务端
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
verdict = gc.verify_ticket(request.form["captcha_ticket"])
|
|
55
|
+
if not verdict["valid"]:
|
|
56
|
+
return {"error": "人机验证未通过,请重试"}, 401
|
|
57
|
+
|
|
58
|
+
# 验票通过后再执行业务(顺序不要反)
|
|
59
|
+
...
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## 返回值
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
# 通过
|
|
66
|
+
{"valid": True, "score": 18, "site_id": ..., "issued_at": ..., "expires_at": ..., "nonce": ..., "request_id": ...}
|
|
67
|
+
|
|
68
|
+
# 不通过(不抛异常,方便 fail-closed)
|
|
69
|
+
{"valid": False, "reason": "票据已被使用", "code": 1011, "retryable": False}
|
|
70
|
+
{"valid": False, "reason": "verify_unavailable", "retryable": True} # 超时/网络
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
**例外**:`1001` / `1002`(密钥错、站点无效、域名不在白名单)抛 `GhostCaptchaError`。
|
|
74
|
+
那是部署配置问题,不该被 `except` 成「用户没通过」悄悄上线。
|
|
75
|
+
|
|
76
|
+
## HMAC 模式
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
gc = create_client(base_url, site_key, site_secret, auth="hmac")
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
SDK 会对**实际发送的 body 字节**签名(`timestamp + "." + raw_body`)。
|
|
83
|
+
|
|
84
|
+
## 查用量
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
usage = gc.get_usage()
|
|
88
|
+
print(usage["products"]["api"]["remaining"], usage["products"]["gen"]["remaining"])
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`usage` 是账号级;测试站点 `test: True`,发题不计量,出图照常扣额度。
|
|
92
|
+
|
|
93
|
+
## 三条不要做
|
|
94
|
+
|
|
95
|
+
1. 不要重试验票(票据一次性,重试会拿到 1011);
|
|
96
|
+
2. 不要缓存票据;票一次一用,业务失败就让用户重做一次验证;
|
|
97
|
+
3. 不要只看前端有没有票,必须服务端 `verify_ticket`。
|
|
98
|
+
|
|
99
|
+
## 测试
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
cd sdk/python
|
|
103
|
+
python -m unittest discover -s tests -v
|
|
104
|
+
```
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# 幽灵验证码 · Python 服务端 SDK
|
|
2
|
+
|
|
3
|
+
零依赖(只用标准库),Python 3.8+。只做三件事:**校验票据**、**查用量**、把错误码翻译成可判断的结果。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
PyPI 尚未发布,当前从仓库本地路径安装:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install /path/to/ghostcaptcha/sdk/python
|
|
11
|
+
# 或开发模式
|
|
12
|
+
pip install -e /path/to/ghostcaptcha/sdk/python
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
发布到 PyPI 之后改成:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install ghostcaptcha
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## 快速开始
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import os
|
|
25
|
+
from ghostcaptcha import create_client, GhostCaptchaError
|
|
26
|
+
|
|
27
|
+
gc = create_client(
|
|
28
|
+
"https://api.your-domain.com",
|
|
29
|
+
os.environ["GC_SITE_KEY"],
|
|
30
|
+
os.environ["GC_SITE_SECRET"], # 只在服务端
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
verdict = gc.verify_ticket(request.form["captcha_ticket"])
|
|
34
|
+
if not verdict["valid"]:
|
|
35
|
+
return {"error": "人机验证未通过,请重试"}, 401
|
|
36
|
+
|
|
37
|
+
# 验票通过后再执行业务(顺序不要反)
|
|
38
|
+
...
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## 返回值
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
# 通过
|
|
45
|
+
{"valid": True, "score": 18, "site_id": ..., "issued_at": ..., "expires_at": ..., "nonce": ..., "request_id": ...}
|
|
46
|
+
|
|
47
|
+
# 不通过(不抛异常,方便 fail-closed)
|
|
48
|
+
{"valid": False, "reason": "票据已被使用", "code": 1011, "retryable": False}
|
|
49
|
+
{"valid": False, "reason": "verify_unavailable", "retryable": True} # 超时/网络
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
**例外**:`1001` / `1002`(密钥错、站点无效、域名不在白名单)抛 `GhostCaptchaError`。
|
|
53
|
+
那是部署配置问题,不该被 `except` 成「用户没通过」悄悄上线。
|
|
54
|
+
|
|
55
|
+
## HMAC 模式
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
gc = create_client(base_url, site_key, site_secret, auth="hmac")
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
SDK 会对**实际发送的 body 字节**签名(`timestamp + "." + raw_body`)。
|
|
62
|
+
|
|
63
|
+
## 查用量
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
usage = gc.get_usage()
|
|
67
|
+
print(usage["products"]["api"]["remaining"], usage["products"]["gen"]["remaining"])
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`usage` 是账号级;测试站点 `test: True`,发题不计量,出图照常扣额度。
|
|
71
|
+
|
|
72
|
+
## 三条不要做
|
|
73
|
+
|
|
74
|
+
1. 不要重试验票(票据一次性,重试会拿到 1011);
|
|
75
|
+
2. 不要缓存票据;票一次一用,业务失败就让用户重做一次验证;
|
|
76
|
+
3. 不要只看前端有没有票,必须服务端 `verify_ticket`。
|
|
77
|
+
|
|
78
|
+
## 测试
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
cd sdk/python
|
|
82
|
+
python -m unittest discover -s tests -v
|
|
83
|
+
```
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""幽灵验证码 · 服务端 Python SDK(零依赖,Python 3.8+)。
|
|
3
|
+
|
|
4
|
+
只做三件事:校验票据、查用量、把错误码翻译成可判断的结果。
|
|
5
|
+
|
|
6
|
+
设计原则(与官方文档一致):
|
|
7
|
+
1. fail-closed:网络错误/超时/5xx 一律返回 valid=False,绝不默认放行;
|
|
8
|
+
2. 票据一次性:同一次提交不要重试验票;
|
|
9
|
+
3. 配置错误要响:1001/1002(密钥错、站点/域名无效)抛 GhostCaptchaError,
|
|
10
|
+
不要被 except 成"用户没通过"悄悄上线。
|
|
11
|
+
"""
|
|
12
|
+
import hashlib
|
|
13
|
+
import hmac
|
|
14
|
+
import json
|
|
15
|
+
import socket
|
|
16
|
+
import time
|
|
17
|
+
import urllib.error
|
|
18
|
+
import urllib.request
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
_USER_AGENT = "ghostcaptcha-python/%s" % __version__
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class GhostCaptchaError(Exception):
|
|
25
|
+
"""配置/协议级错误(调用方应修复,而不是重试)。"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, message, code=0, status=0, request_id=""):
|
|
28
|
+
super(GhostCaptchaError, self).__init__(message)
|
|
29
|
+
self.code = code
|
|
30
|
+
self.status = status
|
|
31
|
+
self.request_id = request_id
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def signature(secret, timestamp, raw_body):
|
|
35
|
+
"""hex(HMAC_SHA256(secret, timestamp + "." + raw_body));raw_body 是实际发送的字节。"""
|
|
36
|
+
if isinstance(raw_body, str):
|
|
37
|
+
raw_body = raw_body.encode("utf-8")
|
|
38
|
+
return hmac.new(
|
|
39
|
+
str(secret).encode("utf-8"),
|
|
40
|
+
str(timestamp).encode("utf-8") + b"." + raw_body,
|
|
41
|
+
hashlib.sha256,
|
|
42
|
+
).hexdigest()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Client(object):
|
|
46
|
+
"""create_client(...) 的返回类型;直接用 Client(...) 也可以。"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, base_url, site_key, site_secret, auth="secret",
|
|
49
|
+
timeout=5.0, user_agent=_USER_AGENT):
|
|
50
|
+
self.base_url = str(base_url or "").strip().rstrip("/")
|
|
51
|
+
self.site_key = str(site_key or "").strip()
|
|
52
|
+
self.site_secret = str(site_secret or "")
|
|
53
|
+
self.auth = "hmac" if auth == "hmac" else "secret"
|
|
54
|
+
self.timeout = float(timeout or 5.0)
|
|
55
|
+
self.user_agent = user_agent
|
|
56
|
+
|
|
57
|
+
if not self.base_url:
|
|
58
|
+
raise GhostCaptchaError("base_url 必填,例如 https://api.example.com")
|
|
59
|
+
if not (self.base_url.startswith("http://") or self.base_url.startswith("https://")):
|
|
60
|
+
raise GhostCaptchaError("base_url 必须是 http(s) 绝对地址")
|
|
61
|
+
if not self.site_key:
|
|
62
|
+
raise GhostCaptchaError("site_key 必填")
|
|
63
|
+
if not self.site_secret:
|
|
64
|
+
raise GhostCaptchaError("site_secret 必填(只能放服务端)")
|
|
65
|
+
|
|
66
|
+
# ---------------------------------------------------------------- 底层请求
|
|
67
|
+
|
|
68
|
+
def _request(self, method, path, payload=None):
|
|
69
|
+
"""返回 dict:{status, body, request_id} 或 {network_error}。"""
|
|
70
|
+
if payload is None:
|
|
71
|
+
raw = b""
|
|
72
|
+
else:
|
|
73
|
+
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
|
74
|
+
|
|
75
|
+
headers = {
|
|
76
|
+
"User-Agent": self.user_agent,
|
|
77
|
+
"Accept": "application/json",
|
|
78
|
+
"X-Site-Key": self.site_key,
|
|
79
|
+
}
|
|
80
|
+
if raw:
|
|
81
|
+
headers["Content-Type"] = "application/json"
|
|
82
|
+
if self.auth == "hmac":
|
|
83
|
+
ts = str(int(time.time()))
|
|
84
|
+
headers["X-Timestamp"] = ts
|
|
85
|
+
headers["X-Signature"] = signature(self.site_secret, ts, raw)
|
|
86
|
+
else:
|
|
87
|
+
headers["X-Site-Secret"] = self.site_secret
|
|
88
|
+
|
|
89
|
+
req = urllib.request.Request(
|
|
90
|
+
self.base_url + path,
|
|
91
|
+
data=raw if payload is not None else None,
|
|
92
|
+
headers=headers,
|
|
93
|
+
method=method,
|
|
94
|
+
)
|
|
95
|
+
try:
|
|
96
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
97
|
+
status = resp.status
|
|
98
|
+
body = resp.read()
|
|
99
|
+
request_id = resp.headers.get("X-Request-Id", "") or ""
|
|
100
|
+
except urllib.error.HTTPError as e:
|
|
101
|
+
status = e.code
|
|
102
|
+
body = e.read()
|
|
103
|
+
request_id = e.headers.get("X-Request-Id", "") if e.headers else ""
|
|
104
|
+
except (urllib.error.URLError, socket.timeout, TimeoutError, OSError) as e:
|
|
105
|
+
return {"network_error": str(e) or "network_error"}
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
parsed = json.loads(body.decode("utf-8")) if body else None
|
|
109
|
+
except (ValueError, UnicodeDecodeError):
|
|
110
|
+
parsed = None
|
|
111
|
+
return {"status": status, "body": parsed, "request_id": request_id}
|
|
112
|
+
|
|
113
|
+
# ---------------------------------------------------------------- 票据校验
|
|
114
|
+
|
|
115
|
+
def verify_ticket(self, ticket):
|
|
116
|
+
"""校验票据,返回 dict。
|
|
117
|
+
|
|
118
|
+
通过:{"valid": True, "score": ..., "site_id": ..., "nonce": ..., "request_id": ...}
|
|
119
|
+
不通过:{"valid": False, "reason": ..., "code": ..., "retryable": ...}
|
|
120
|
+
1001/1002 抛 GhostCaptchaError(部署配置问题,不该被静默吞掉)。
|
|
121
|
+
"""
|
|
122
|
+
if not ticket or not isinstance(ticket, str):
|
|
123
|
+
return {"valid": False, "reason": "empty_ticket", "retryable": False}
|
|
124
|
+
|
|
125
|
+
r = self._request("POST", "/v1/ticket/verify", {"ticket": ticket})
|
|
126
|
+
if "network_error" in r:
|
|
127
|
+
return {"valid": False, "reason": "verify_unavailable",
|
|
128
|
+
"detail": r["network_error"], "retryable": True}
|
|
129
|
+
|
|
130
|
+
body = r.get("body") or {}
|
|
131
|
+
code = body.get("code")
|
|
132
|
+
if code in (1001, 1002):
|
|
133
|
+
raise GhostCaptchaError(
|
|
134
|
+
body.get("message") or ("验票被拒(code=%s),请检查 site_key/site_secret/域名白名单" % code),
|
|
135
|
+
code=code, status=r.get("status", 0), request_id=r.get("request_id", ""))
|
|
136
|
+
|
|
137
|
+
data = body.get("data") or {}
|
|
138
|
+
if r.get("status") == 200 and code == 0 and data.get("valid") is True:
|
|
139
|
+
return {
|
|
140
|
+
"valid": True,
|
|
141
|
+
"score": data.get("score"),
|
|
142
|
+
"site_id": data.get("site_id"),
|
|
143
|
+
"issued_at": data.get("issued_at"),
|
|
144
|
+
"expires_at": data.get("expires_at"),
|
|
145
|
+
"nonce": data.get("nonce"),
|
|
146
|
+
"request_id": r.get("request_id", ""),
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
"valid": False,
|
|
151
|
+
"reason": data.get("reason") or body.get("message") or ("verify_failed_%s" % r.get("status")),
|
|
152
|
+
"code": code,
|
|
153
|
+
"retryable": code in (1003, 1007) or (r.get("status") or 0) >= 500,
|
|
154
|
+
"request_id": r.get("request_id", ""),
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
# ---------------------------------------------------------------- 查用量
|
|
158
|
+
|
|
159
|
+
def get_usage(self):
|
|
160
|
+
"""返回 {site_key, test, period, products:{api,gen}};失败抛 GhostCaptchaError。"""
|
|
161
|
+
r = self._request("GET", "/v1/usage")
|
|
162
|
+
if "network_error" in r:
|
|
163
|
+
raise GhostCaptchaError("查询用量失败:" + r["network_error"],
|
|
164
|
+
request_id=r.get("request_id", ""))
|
|
165
|
+
body = r.get("body") or {}
|
|
166
|
+
if r.get("status") != 200 or body.get("code") != 0:
|
|
167
|
+
raise GhostCaptchaError(
|
|
168
|
+
body.get("message") or ("查询用量失败(HTTP %s)" % r.get("status")),
|
|
169
|
+
code=body.get("code", 0), status=r.get("status", 0),
|
|
170
|
+
request_id=r.get("request_id", ""))
|
|
171
|
+
return body.get("data") or {}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def create_client(base_url, site_key, site_secret, **kwargs):
|
|
175
|
+
"""便捷构造:create_client(base_url, site_key, site_secret, auth="hmac", timeout=5)。"""
|
|
176
|
+
return Client(base_url, site_key, site_secret, **kwargs)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: ghostcaptcha
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 幽灵验证码服务端 SDK:校验票据、查用量、错误码翻译(fail-closed)
|
|
5
|
+
Author: GhostCAPTCHA
|
|
6
|
+
License: UNLICENSED
|
|
7
|
+
Project-URL: Homepage, https://bwbdai.cn/api
|
|
8
|
+
Project-URL: Repository, https://github.com/ghostcaptcha/ghostcaptcha
|
|
9
|
+
Project-URL: Issues, https://github.com/ghostcaptcha/ghostcaptcha/issues
|
|
10
|
+
Keywords: captcha,ghostcaptcha,verification,bot-protection
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: License :: Other/Proprietary License
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# 幽灵验证码 · Python 服务端 SDK
|
|
23
|
+
|
|
24
|
+
零依赖(只用标准库),Python 3.8+。只做三件事:**校验票据**、**查用量**、把错误码翻译成可判断的结果。
|
|
25
|
+
|
|
26
|
+
## 安装
|
|
27
|
+
|
|
28
|
+
PyPI 尚未发布,当前从仓库本地路径安装:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install /path/to/ghostcaptcha/sdk/python
|
|
32
|
+
# 或开发模式
|
|
33
|
+
pip install -e /path/to/ghostcaptcha/sdk/python
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
发布到 PyPI 之后改成:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install ghostcaptcha
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## 快速开始
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import os
|
|
46
|
+
from ghostcaptcha import create_client, GhostCaptchaError
|
|
47
|
+
|
|
48
|
+
gc = create_client(
|
|
49
|
+
"https://api.your-domain.com",
|
|
50
|
+
os.environ["GC_SITE_KEY"],
|
|
51
|
+
os.environ["GC_SITE_SECRET"], # 只在服务端
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
verdict = gc.verify_ticket(request.form["captcha_ticket"])
|
|
55
|
+
if not verdict["valid"]:
|
|
56
|
+
return {"error": "人机验证未通过,请重试"}, 401
|
|
57
|
+
|
|
58
|
+
# 验票通过后再执行业务(顺序不要反)
|
|
59
|
+
...
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## 返回值
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
# 通过
|
|
66
|
+
{"valid": True, "score": 18, "site_id": ..., "issued_at": ..., "expires_at": ..., "nonce": ..., "request_id": ...}
|
|
67
|
+
|
|
68
|
+
# 不通过(不抛异常,方便 fail-closed)
|
|
69
|
+
{"valid": False, "reason": "票据已被使用", "code": 1011, "retryable": False}
|
|
70
|
+
{"valid": False, "reason": "verify_unavailable", "retryable": True} # 超时/网络
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
**例外**:`1001` / `1002`(密钥错、站点无效、域名不在白名单)抛 `GhostCaptchaError`。
|
|
74
|
+
那是部署配置问题,不该被 `except` 成「用户没通过」悄悄上线。
|
|
75
|
+
|
|
76
|
+
## HMAC 模式
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
gc = create_client(base_url, site_key, site_secret, auth="hmac")
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
SDK 会对**实际发送的 body 字节**签名(`timestamp + "." + raw_body`)。
|
|
83
|
+
|
|
84
|
+
## 查用量
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
usage = gc.get_usage()
|
|
88
|
+
print(usage["products"]["api"]["remaining"], usage["products"]["gen"]["remaining"])
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`usage` 是账号级;测试站点 `test: True`,发题不计量,出图照常扣额度。
|
|
92
|
+
|
|
93
|
+
## 三条不要做
|
|
94
|
+
|
|
95
|
+
1. 不要重试验票(票据一次性,重试会拿到 1011);
|
|
96
|
+
2. 不要缓存票据;票一次一用,业务失败就让用户重做一次验证;
|
|
97
|
+
3. 不要只看前端有没有票,必须服务端 `verify_ticket`。
|
|
98
|
+
|
|
99
|
+
## 测试
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
cd sdk/python
|
|
103
|
+
python -m unittest discover -s tests -v
|
|
104
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ghostcaptcha
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ghostcaptcha"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "幽灵验证码服务端 SDK:校验票据、查用量、错误码翻译(fail-closed)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { text = "UNLICENSED" }
|
|
12
|
+
authors = [{ name = "GhostCAPTCHA" }]
|
|
13
|
+
keywords = ["captcha", "ghostcaptcha", "verification", "bot-protection"]
|
|
14
|
+
dependencies = []
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.8",
|
|
18
|
+
"Programming Language :: Python :: 3.9",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"License :: Other/Proprietary License",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://bwbdai.cn/api"
|
|
28
|
+
Repository = "https://github.com/ghostcaptcha/ghostcaptcha"
|
|
29
|
+
Issues = "https://github.com/ghostcaptcha/ghostcaptcha/issues"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools]
|
|
32
|
+
packages = ["ghostcaptcha"]
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import json
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
import unittest
|
|
7
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
8
|
+
|
|
9
|
+
from ghostcaptcha import Client, GhostCaptchaError, create_client, signature
|
|
10
|
+
|
|
11
|
+
KEY = "pk_live_test"
|
|
12
|
+
SECRET = "sk_live_test_secret"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Handler(BaseHTTPRequestHandler):
|
|
16
|
+
"""可编程假服务:handler(req, raw) 返回 (status, obj, extra_headers)。"""
|
|
17
|
+
|
|
18
|
+
def do_POST(self):
|
|
19
|
+
self._handle()
|
|
20
|
+
|
|
21
|
+
def do_GET(self):
|
|
22
|
+
self._handle()
|
|
23
|
+
|
|
24
|
+
def _handle(self):
|
|
25
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
26
|
+
raw = self.rfile.read(n) if n else b""
|
|
27
|
+
status, obj, extra = self.server.reply(self, raw) # type: ignore[attr-defined]
|
|
28
|
+
body = json.dumps(obj).encode("utf-8")
|
|
29
|
+
self.send_response(status)
|
|
30
|
+
self.send_header("Content-Type", "application/json")
|
|
31
|
+
self.send_header("Content-Length", str(len(body)))
|
|
32
|
+
for k, v in (extra or {}).items():
|
|
33
|
+
self.send_header(k, v)
|
|
34
|
+
self.end_headers()
|
|
35
|
+
try:
|
|
36
|
+
self.wfile.write(body)
|
|
37
|
+
except (ConnectionAbortedError, BrokenPipeError):
|
|
38
|
+
pass # 客户端已超时/断开(fail-closed 用例里是预期的)
|
|
39
|
+
|
|
40
|
+
def log_message(self, *args):
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Base(unittest.TestCase):
|
|
45
|
+
def setUp(self):
|
|
46
|
+
self.captured = []
|
|
47
|
+
|
|
48
|
+
def reply(req, raw):
|
|
49
|
+
self.captured.append({
|
|
50
|
+
"path": req.path, "method": req.command, "raw": raw,
|
|
51
|
+
"headers": {k.lower(): v for k, v in req.headers.items()},
|
|
52
|
+
})
|
|
53
|
+
return self.route(req, raw)
|
|
54
|
+
|
|
55
|
+
self.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
56
|
+
self.server.reply = reply # type: ignore[attr-defined]
|
|
57
|
+
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
|
58
|
+
self.thread.start()
|
|
59
|
+
self.base = "http://127.0.0.1:%d" % self.server.server_port
|
|
60
|
+
|
|
61
|
+
def tearDown(self):
|
|
62
|
+
self.server.shutdown()
|
|
63
|
+
self.server.server_close()
|
|
64
|
+
|
|
65
|
+
def route(self, req, raw):
|
|
66
|
+
raise NotImplementedError
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class TestVerify(Base):
|
|
70
|
+
def route(self, req, raw):
|
|
71
|
+
if req.path == "/v1/ticket/verify":
|
|
72
|
+
return 200, {"code": 0, "message": "ok", "data": {
|
|
73
|
+
"valid": True, "score": 12, "site_id": "site_1",
|
|
74
|
+
"nonce": "n1", "issued_at": "2026-12-02T00:00:00+08:00",
|
|
75
|
+
}}, {"X-Request-Id": "req_abc"}
|
|
76
|
+
return 404, {"code": 1004}, {}
|
|
77
|
+
|
|
78
|
+
def test_success(self):
|
|
79
|
+
c = Client(self.base, KEY, SECRET)
|
|
80
|
+
r = c.verify_ticket("ticket-1")
|
|
81
|
+
self.assertTrue(r["valid"])
|
|
82
|
+
self.assertEqual(r["score"], 12)
|
|
83
|
+
self.assertEqual(r["nonce"], "n1")
|
|
84
|
+
self.assertEqual(r["request_id"], "req_abc")
|
|
85
|
+
cap = self.captured[0]
|
|
86
|
+
self.assertEqual(cap["path"], "/v1/ticket/verify")
|
|
87
|
+
self.assertEqual(cap["headers"]["x-site-key"], KEY)
|
|
88
|
+
self.assertEqual(cap["headers"]["x-site-secret"], SECRET)
|
|
89
|
+
self.assertEqual(cap["raw"], b'{"ticket":"ticket-1"}')
|
|
90
|
+
|
|
91
|
+
def test_empty_ticket_no_request(self):
|
|
92
|
+
c = Client(self.base, KEY, SECRET)
|
|
93
|
+
r = c.verify_ticket("")
|
|
94
|
+
self.assertFalse(r["valid"])
|
|
95
|
+
self.assertEqual(r["reason"], "empty_ticket")
|
|
96
|
+
self.assertEqual(len(self.captured), 0)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class TestStatusMapping(Base):
|
|
100
|
+
def route(self, req, raw):
|
|
101
|
+
if req.path == "/v1/ticket/verify":
|
|
102
|
+
return 400, {"code": 1011, "message": "票据已被使用",
|
|
103
|
+
"data": {"valid": False, "reason": "票据已被使用"}}, {}
|
|
104
|
+
if req.path == "/v1/usage":
|
|
105
|
+
return 200, {"code": 0, "data": {"site_key": KEY, "products": {
|
|
106
|
+
"api": {"remaining": 4998}, "gen": {"remaining": 500}}}}, {}
|
|
107
|
+
return 404, {"code": 1004}, {}
|
|
108
|
+
|
|
109
|
+
def test_invalid_ticket(self):
|
|
110
|
+
c = Client(self.base, KEY, SECRET)
|
|
111
|
+
r = c.verify_ticket("used")
|
|
112
|
+
self.assertFalse(r["valid"])
|
|
113
|
+
self.assertEqual(r["code"], 1011)
|
|
114
|
+
self.assertEqual(r["reason"], "票据已被使用")
|
|
115
|
+
self.assertFalse(r["retryable"])
|
|
116
|
+
|
|
117
|
+
def test_usage(self):
|
|
118
|
+
c = Client(self.base, KEY, SECRET)
|
|
119
|
+
u = c.get_usage()
|
|
120
|
+
self.assertEqual(u["products"]["api"]["remaining"], 4998)
|
|
121
|
+
self.assertEqual(self.captured[-1]["path"], "/v1/usage")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class TestConfigError(Base):
|
|
125
|
+
def route(self, req, raw):
|
|
126
|
+
return 400, {"code": 1002, "message": "X-Site-Secret 不正确"}, {}
|
|
127
|
+
|
|
128
|
+
def test_raises(self):
|
|
129
|
+
c = Client(self.base, KEY, SECRET)
|
|
130
|
+
with self.assertRaises(GhostCaptchaError) as ctx:
|
|
131
|
+
c.verify_ticket("t")
|
|
132
|
+
self.assertEqual(ctx.exception.code, 1002)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class TestHmac(Base):
|
|
136
|
+
def route(self, req, raw):
|
|
137
|
+
ts = req.headers.get("X-Timestamp")
|
|
138
|
+
sig = req.headers.get("X-Signature")
|
|
139
|
+
want = hmac.new(SECRET.encode(), (ts or "").encode() + b"." + raw,
|
|
140
|
+
hashlib.sha256).hexdigest()
|
|
141
|
+
if ts and sig == want:
|
|
142
|
+
return 200, {"code": 0, "data": {"valid": True}}, {}
|
|
143
|
+
return 401, {"code": 1001, "message": "签名不对"}, {}
|
|
144
|
+
|
|
145
|
+
def test_hmac_signature(self):
|
|
146
|
+
c = create_client(self.base, KEY, SECRET, auth="hmac")
|
|
147
|
+
r = c.verify_ticket("ticket-hmac")
|
|
148
|
+
self.assertTrue(r["valid"])
|
|
149
|
+
h = self.captured[0]["headers"]
|
|
150
|
+
self.assertNotIn("x-site-secret", h)
|
|
151
|
+
self.assertTrue(h.get("x-signature"))
|
|
152
|
+
self.assertTrue(h.get("x-timestamp"))
|
|
153
|
+
|
|
154
|
+
def test_signature_helper(self):
|
|
155
|
+
self.assertEqual(signature("secret", "123", b'{"a":1}'),
|
|
156
|
+
hmac.new(b"secret", b'123.{"a":1}', hashlib.sha256).hexdigest())
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class TestTimeout(Base):
|
|
160
|
+
def route(self, req, raw):
|
|
161
|
+
time.sleep(0.4)
|
|
162
|
+
return 200, {"code": 0, "data": {"valid": True}}, {}
|
|
163
|
+
|
|
164
|
+
def test_fail_closed(self):
|
|
165
|
+
c = Client(self.base, KEY, SECRET, timeout=0.1)
|
|
166
|
+
r = c.verify_ticket("t")
|
|
167
|
+
self.assertFalse(r["valid"])
|
|
168
|
+
self.assertEqual(r["reason"], "verify_unavailable")
|
|
169
|
+
self.assertTrue(r["retryable"])
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class TestArgs(unittest.TestCase):
|
|
173
|
+
def test_missing_args(self):
|
|
174
|
+
with self.assertRaises(GhostCaptchaError):
|
|
175
|
+
Client("", KEY, SECRET)
|
|
176
|
+
with self.assertRaises(GhostCaptchaError):
|
|
177
|
+
Client("http://x", "", SECRET)
|
|
178
|
+
with self.assertRaises(GhostCaptchaError):
|
|
179
|
+
Client("http://x", KEY, "")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if __name__ == "__main__":
|
|
183
|
+
unittest.main()
|