feat(feedback): 留言反馈API — 提交(图形验证码+IP一小时限1条)、后台列表/改状态/删除(X-Admin-Token鉴权)
This commit is contained in:
1 parent
16e649633b
commit
d5cf278073
1 file changed
+288
-5
@@ -1196,6 +1196,28 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
_save_reco(clean)
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
# ---------- 站内留言反馈(管理端查看/改状态/删除) ----------
|
||||
if method == "GET" and sub == "/feedback":
|
||||
items = sorted(_load_feedback(), key=lambda x: float(x.get("ts") or 0), reverse=True)
|
||||
return 200, {"code": 200, "message": "ok", "data": items}
|
||||
|
||||
if method == "POST" and sub == "/feedback":
|
||||
fid = str(payload.get("id") or "")
|
||||
if not fid:
|
||||
return 400, {"code": 400, "message": "缺少留言 id"}
|
||||
with FEEDBACK_LOCK:
|
||||
items = _load_feedback()
|
||||
hit = next((it for it in items if it.get("id") == fid), None)
|
||||
if not hit:
|
||||
return 404, {"code": 404, "message": "留言不存在"}
|
||||
if str(payload.get("action") or "") == "delete":
|
||||
items = [it for it in items if it.get("id") != fid]
|
||||
else:
|
||||
status = str(payload.get("status") or "new")
|
||||
hit["status"] = status if status in ("new", "replied", "done") else "new"
|
||||
_save_feedback(items)
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
if method == "GET" and sub == "/storage":
|
||||
total = _dir_size(USERS_ROOT) if os.path.isdir(USERS_ROOT) else 0
|
||||
for extra in ("users.db", "usage.db", "trials.json"):
|
||||
@@ -1294,11 +1316,211 @@ def _req_machine(handler):
|
||||
return handler.headers.get("X-Machine-Id", "") if handler else ""
|
||||
|
||||
|
||||
# ---- 本地图片验证码(替代 Cloudflare Turnstile:不依赖外网,服务端出图) ----
|
||||
try:
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
_HAS_PIL = True
|
||||
except Exception: # pragma: no cover
|
||||
_HAS_PIL = False
|
||||
|
||||
CAPTCHA_TTL = 300 # 验证码有效期(秒)
|
||||
_CAPTCHA_MAX = 5000 # 内存上限(防撑爆)
|
||||
_CAPTCHAS = {} # id -> (code, expire_ts),单次核销
|
||||
_CAPTCHA_LOCK = threading.Lock()
|
||||
_CAPTCHA_CHARS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # 去掉易混字符 0/O/1/I/L
|
||||
|
||||
|
||||
def _gen_captcha():
|
||||
"""返回 (captcha_id, png_base64)。4 位干扰码,5 分钟过期,取用即销毁。"""
|
||||
import base64
|
||||
import random
|
||||
import uuid
|
||||
|
||||
code = "".join(random.choice(_CAPTCHA_CHARS) for _ in range(4))
|
||||
cid = uuid.uuid4().hex
|
||||
w, h = 148, 52
|
||||
img = Image.new("RGB", (w, h), (247, 248, 251))
|
||||
d = ImageDraw.Draw(img)
|
||||
try:
|
||||
font = ImageFont.load_default(size=36)
|
||||
except TypeError: # pragma: no cover
|
||||
font = ImageFont.load_default()
|
||||
# 干扰线 + 噪点
|
||||
for _ in range(7):
|
||||
d.line([random.randrange(w), random.randrange(h),
|
||||
random.randrange(w), random.randrange(h)],
|
||||
fill=(random.randint(160, 210), random.randint(160, 210), random.randint(160, 210)),
|
||||
width=1)
|
||||
for _ in range(60):
|
||||
d.point((random.randrange(w), random.randrange(h)),
|
||||
fill=(random.randint(150, 220), random.randint(150, 220), random.randint(150, 220)))
|
||||
# 逐字带抖动绘制
|
||||
x = 14
|
||||
for ch in code:
|
||||
d.text((x, 6 + random.randint(-4, 4)), ch, font=font,
|
||||
fill=(random.randint(10, 90), random.randint(10, 90), random.randint(10, 90)))
|
||||
x += 33
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
now = time.time()
|
||||
with _CAPTCHA_LOCK:
|
||||
for k in [k for k, v in _CAPTCHAS.items() if v[1] < now]:
|
||||
_CAPTCHAS.pop(k, None)
|
||||
while len(_CAPTCHAS) >= _CAPTCHA_MAX:
|
||||
_CAPTCHAS.pop(next(iter(_CAPTCHAS)), None)
|
||||
_CAPTCHAS[cid] = (code, now + CAPTCHA_TTL)
|
||||
return cid, base64.b64encode(buf.getvalue()).decode()
|
||||
|
||||
|
||||
def verify_captcha(payload) -> bool:
|
||||
"""核销 captcha_id + captcha_code(单次有效,大小写不敏感)。"""
|
||||
cid = str(payload.get("captcha_id") or "")
|
||||
got = str(payload.get("captcha_code") or "").strip().upper()
|
||||
if not cid or not got:
|
||||
return False
|
||||
with _CAPTCHA_LOCK:
|
||||
entry = _CAPTCHAS.pop(cid, None) # 无论对错都销毁,防爆破
|
||||
if not entry:
|
||||
return False
|
||||
stored, exp = entry
|
||||
if time.time() > exp:
|
||||
return False
|
||||
import secrets as _secrets
|
||||
return _secrets.compare_digest(stored, got)
|
||||
|
||||
|
||||
# ============ 站内留言反馈(独立于卡密/授权系统,任何人可用) ============
|
||||
# GET /feedback/captcha 图形验证码
|
||||
# POST /feedback {type,content,contact,captcha_id,captcha_code}
|
||||
FEEDBACK_FILE = os.path.join(DATA_DIR, "feedback.json")
|
||||
FEEDBACK_TYPES = ("功能建议", "意见反馈")
|
||||
FEEDBACK_WINDOW = 3600 # 同一 IP 两次提交的最小间隔(秒,1 小时)
|
||||
FEEDBACK_MAX = 2000 # 存档上限,超出丢弃最旧
|
||||
FEEDBACK_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _load_feedback() -> list:
|
||||
try:
|
||||
with open(FEEDBACK_FILE, "r", encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
|
||||
|
||||
def _save_feedback(items: list) -> None:
|
||||
tmp = FEEDBACK_FILE + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as fh:
|
||||
json.dump(items, fh, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, FEEDBACK_FILE)
|
||||
|
||||
|
||||
def _ip_is_public(value: str) -> bool:
|
||||
try:
|
||||
import ipaddress
|
||||
ip = ipaddress.ip_address(value)
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
return not (
|
||||
ip.is_private or ip.is_loopback or ip.is_link_local
|
||||
or ip.is_reserved or ip.is_multicast
|
||||
)
|
||||
|
||||
|
||||
def _real_client_ip(handler) -> str:
|
||||
"""取真实客户端 IP(限频用)。
|
||||
|
||||
链路:浏览器 → nps/frp 隧道(注入真实 IP 的 X-Forwarded-For)
|
||||
→ nginx(再追加 $remote_addr = 隧道/内网地址)→ relay。
|
||||
因此 XFF 从右往左取第一个公网地址:先跳过隧道与内网地址,
|
||||
客户端在链路最左侧伪造的头也不会被采信。
|
||||
"""
|
||||
raw = handler.headers.get("X-Forwarded-For") or handler.headers.get("X-Real-IP") or ""
|
||||
parts = [p.strip() for p in raw.split(",") if p.strip()]
|
||||
for part in reversed(parts):
|
||||
if _ip_is_public(part):
|
||||
return part
|
||||
if parts:
|
||||
return parts[0]
|
||||
try:
|
||||
return handler.client_address[0] or "unknown"
|
||||
except Exception: # noqa: BLE001
|
||||
return "unknown"
|
||||
|
||||
|
||||
def feedback_api(method: str, payload: dict, handler) -> tuple:
|
||||
"""公开留言接口:GET 出图形验证码,POST 提交留言。"""
|
||||
if method == "GET":
|
||||
if not _HAS_PIL:
|
||||
return 503, {"code": 503, "message": "验证码组件未就绪,请稍后再试"}
|
||||
cid, img_b64 = _gen_captcha()
|
||||
return 200, {"code": 200, "message": "ok", "data": {"id": cid, "img": img_b64}}
|
||||
|
||||
# POST:先人机验证,再业务校验,最后同 IP 1 小时限频
|
||||
if not verify_captcha(payload):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请刷新验证码后重试"}
|
||||
|
||||
ftype = str(payload.get("type") or "").strip()
|
||||
if ftype not in FEEDBACK_TYPES:
|
||||
return 400, {"code": 400, "message": "请选择留言类型:功能建议 / 意见反馈"}
|
||||
|
||||
content = str(payload.get("content") or "").replace("\r\n", "\n").strip()
|
||||
if not content:
|
||||
return 400, {"code": 400, "message": "请填写留言内容"}
|
||||
if len(content) > 1000:
|
||||
return 400, {"code": 400, "message": "留言内容最多 1000 字"}
|
||||
|
||||
contact = str(payload.get("contact") or "").strip()
|
||||
if len(contact) > 64:
|
||||
return 400, {"code": 400, "message": "联系方式最多 64 字"}
|
||||
if any(ord(c) < 32 for c in contact):
|
||||
return 400, {"code": 400, "message": "联系方式含非法字符"}
|
||||
|
||||
ip = _real_client_ip(handler)
|
||||
now = time.time()
|
||||
|
||||
with FEEDBACK_LOCK:
|
||||
items = _load_feedback()
|
||||
last_ts = 0.0
|
||||
for it in reversed(items):
|
||||
if it.get("ip") == ip:
|
||||
try:
|
||||
last_ts = float(it.get("ts") or 0)
|
||||
except Exception: # noqa: BLE001
|
||||
last_ts = 0.0
|
||||
break
|
||||
if now - last_ts < FEEDBACK_WINDOW:
|
||||
wait_min = max(int((FEEDBACK_WINDOW - (now - last_ts)) / 60), 1)
|
||||
return 429, {"code": 429, "message": f"同一 IP 一小时内只能提交一次,请 {wait_min} 分钟后再试"}
|
||||
|
||||
items.append({
|
||||
"id": f"{int(now)}-{secrets.token_hex(4)}",
|
||||
"ts": int(now),
|
||||
"ip": ip,
|
||||
"type": ftype,
|
||||
"content": content,
|
||||
"contact": contact,
|
||||
"status": "new",
|
||||
})
|
||||
if len(items) > FEEDBACK_MAX:
|
||||
items = items[-FEEDBACK_MAX:]
|
||||
_save_feedback(items)
|
||||
|
||||
print(f"[feedback] new from {ip} [{ftype}] {len(content)} chars", flush=True)
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
|
||||
def user_api(method, sub, payload, handler):
|
||||
"""returns (status, body_dict)"""
|
||||
if method == "GET" and sub == "/captcha":
|
||||
if not _HAS_PIL:
|
||||
return 503, {"code": 503, "message": "验证码组件未就绪"}
|
||||
cid, img_b64 = _gen_captcha()
|
||||
return 200, {"code": 200, "message": "ok", "data": {"id": cid, "img": img_b64}}
|
||||
|
||||
if method == "POST" and sub == "/register":
|
||||
if not verify_turnstile(str(payload.get("cf_token") or "")):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请完成验证后重试"}
|
||||
if not verify_captcha(payload):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请刷新验证码后重试"}
|
||||
username = str(payload.get("username") or "").strip()
|
||||
password = str(payload.get("password") or "")
|
||||
if not USER_NAME_RE.match(username):
|
||||
@@ -1321,10 +1543,10 @@ def user_api(method, sub, payload, handler):
|
||||
if method == "POST" and sub == "/login":
|
||||
username = str(payload.get("username") or "").strip()
|
||||
password = str(payload.get("password") or "")
|
||||
# admin accounts skip the human check (admin panel login has no Turnstile widget)
|
||||
# admin accounts skip the human check (admin panel login has no captcha widget)
|
||||
role, _disabled = _user_attr(username)
|
||||
if role != "admin" and not verify_turnstile(str(payload.get("cf_token") or "")):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请完成验证后重试"}
|
||||
if role != "admin" and not verify_captcha(payload):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请刷新验证码后重试"}
|
||||
conn = _db()
|
||||
row = conn.execute("SELECT salt, pw_hash FROM users WHERE username=?", (username,)).fetchone()
|
||||
conn.close()
|
||||
@@ -1591,6 +1813,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
if parsed.path == "/feedback/captcha":
|
||||
status, body = feedback_api("GET", {}, self)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
if parsed.path == "/reco":
|
||||
items = [x for x in _load_reco() if x.get("enabled")][:24]
|
||||
body = json.dumps({"code": 200, "message": "ok", "data": items}, ensure_ascii=False).encode("utf-8")
|
||||
@@ -1677,6 +1904,16 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
# ---- 代理/VPN 判定(/ip-check?ip= 浏览器侧自己的公网 IP)----
|
||||
if parsed.path == "/ip-check":
|
||||
ipq = (parse.parse_qs(parsed.query or "").get("ip") or [""])[0].strip()
|
||||
if not ipq or not _ip_valid(ipq):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "缺少或非法 ip 参数"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
data = _ip_check(ipq)
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
self._reply(404, b"not found")
|
||||
|
||||
# ---------- POST ----------
|
||||
@@ -2465,6 +2702,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/speed":
|
||||
self._handle_speed_post()
|
||||
return
|
||||
if parsed.path == "/feedback":
|
||||
payload = self._read_payload()
|
||||
status, body = feedback_api("POST", payload, self)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path.startswith("/admin"):
|
||||
self._handle_admin("POST")
|
||||
return
|
||||
@@ -3476,6 +3718,47 @@ def _ip_info(ip):
|
||||
return info
|
||||
|
||||
|
||||
# ---------- 代理/VPN 判定(proxycheck.io 免 key,内存缓存) ----------
|
||||
_IPCHECK_CACHE = {}
|
||||
|
||||
|
||||
def _ip_check(ip):
|
||||
"""出口 IP 代理/VPN/数据中心判定:proxycheck.io + 内存缓存;内网地址不外查。
|
||||
返回 {ip, lan, proxy(bool|None), type, provider, hostname, asn};
|
||||
查询失败 proxy=None(前端降级为“无法判定”)。"""
|
||||
ip = (ip or "").strip()
|
||||
if not ip or not _ip_valid(ip):
|
||||
return None
|
||||
import ipaddress
|
||||
addr = ipaddress.ip_address(ip)
|
||||
lan = bool(addr.is_private or addr.is_loopback or addr.is_link_local)
|
||||
cached = _IPCHECK_CACHE.get(ip)
|
||||
if cached is not None:
|
||||
return cached
|
||||
out = {"ip": ip, "lan": lan, "proxy": None, "type": "", "provider": "", "hostname": "", "asn": ""}
|
||||
if not lan:
|
||||
try:
|
||||
url = "http://proxycheck.io/v2/%s?vpn=1&asn=1" % ip
|
||||
with request.urlopen(url, timeout=8) as resp:
|
||||
d = json.loads(resp.read().decode("utf-8", "ignore"))
|
||||
if d.get("status") == "ok":
|
||||
rec = d.get(ip) or {}
|
||||
out = {
|
||||
"ip": ip, "lan": False,
|
||||
"proxy": str(rec.get("proxy") or "").lower() == "yes",
|
||||
"type": rec.get("type") or "",
|
||||
"provider": rec.get("provider") or rec.get("organisation") or "",
|
||||
"hostname": rec.get("hostname") or "",
|
||||
"asn": rec.get("asn") or "",
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
if len(_IPCHECK_CACHE) > 1500:
|
||||
_IPCHECK_CACHE.clear()
|
||||
_IPCHECK_CACHE[ip] = out
|
||||
return out
|
||||
|
||||
|
||||
def _tr_chunks(text: str, limit: int = 1200):
|
||||
"""按行/长度切块,保留换行结构;返回 [(块文本, 块后是否接换行)]"""
|
||||
lines = text.split("\n")
|
||||
|
||||
Reference in new issue
Block a user