ghostcaptcha 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.
@@ -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,5 @@
1
+ ghostcaptcha/__init__.py,sha256=p87bjASra-E0Y7KUcSesemvNxDTrm99IBl1PMGe-PO0,7340
2
+ ghostcaptcha-0.1.0.dist-info/METADATA,sha256=ITsqcGSuXtqjV51icJtjdv6wdeHnCXogQHLXXHfi8oA,3218
3
+ ghostcaptcha-0.1.0.dist-info/WHEEL,sha256=BNRMDyzLkkcmlv0J8ppDQkk2VED33SesJDynr9ED1gc,91
4
+ ghostcaptcha-0.1.0.dist-info/top_level.txt,sha256=zTr8Bi98BFSffzCC1vCex5r67KbdUmy3p_Lip267fO8,13
5
+ ghostcaptcha-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.4)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ ghostcaptcha