779 lines
36 KiB
Python
779 lines
36 KiB
Python
"""it-tools relay: translate upstream + license check + card activation.
|
||
|
||
Endpoints
|
||
GET /translate?... -> proxy Google Translate via host proxy (CN workaround)
|
||
GET /check -> license gate for nginx auth_request
|
||
headers: X-Machine-Id (10-16 digits), X-Tool (protected tool key)
|
||
200 = allowed (IT-Tools project authorization OR trial window open)
|
||
403 = blocked
|
||
POST /activate -> card activation proxy (body: card_key, machine_id, contact_qq)
|
||
uses server-side CARD_AUTH_KEY for /public/verify pre-check, then
|
||
/public/authorizations/activate. The key never leaves this container.
|
||
|
||
Authorization rules
|
||
* Query CardAuth /public/authorizations/query?bot_qq=<machine> (60s cache).
|
||
* Only cards of the PROJECT_NAME project count as authorized (other projects'
|
||
cards must not unlock this site).
|
||
* Network failure -> fail OPEN (auth server down must not lock paying users).
|
||
|
||
Trial state persisted to /app/data/trials.json (mounted volume).
|
||
"""
|
||
import cgi
|
||
import io
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import tempfile
|
||
import threading
|
||
import time
|
||
import zipfile
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
from urllib import parse, request
|
||
|
||
UPSTREAM = "https://translate.googleapis.com/translate_a/single"
|
||
PROXY = os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or ""
|
||
TIMEOUT = float(os.environ.get("RELAY_TIMEOUT", "25"))
|
||
|
||
AUTH_BASE = os.environ.get("AUTH_BASE", "https://auth.88531.cn/api")
|
||
CARD_AUTH_KEY = os.environ.get("CARD_AUTH_KEY", "")
|
||
# Optional admin login: cards bound to a user require a logged-in session to activate
|
||
AUTH_USER = os.environ.get("AUTH_USER", "")
|
||
AUTH_PASS = os.environ.get("AUTH_PASS", "")
|
||
PROJECT_NAME = os.environ.get("PROJECT_NAME", "IT-Tools")
|
||
TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json")
|
||
TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000
|
||
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools"}
|
||
MACHINE_RE = re.compile(r"^\d{10,16}$")
|
||
|
||
# verify() messages that unconditionally block activation
|
||
BLOCK_WORDS = ("不存在", "已过期", "过期", "作废", "禁用", "停用", "已禁")
|
||
|
||
_lock = threading.Lock()
|
||
|
||
|
||
def _opener(with_proxy: bool):
|
||
handlers = []
|
||
if with_proxy and PROXY:
|
||
handlers.append(request.ProxyHandler({"http": PROXY, "https": PROXY}))
|
||
elif not with_proxy:
|
||
handlers.append(request.ProxyHandler({})) # force direct
|
||
return request.build_opener(*handlers)
|
||
|
||
|
||
OPENER_PROXY = _opener(True)
|
||
OPENER_DIRECT = _opener(False)
|
||
|
||
# ---- authorization cache: machine -> (authorized, fetched_at) ----
|
||
_auth_cache: dict = {}
|
||
AUTH_CACHE_TTL = 60
|
||
|
||
|
||
def _list_has_ittools_auth(data: dict) -> bool:
|
||
"""Only cards of PROJECT_NAME with active status count.
|
||
|
||
Falls back to has_valid_auth when the payload has no usable list
|
||
(keeps working if CardAuth response shape changes).
|
||
"""
|
||
lst = data.get("list")
|
||
if not isinstance(lst, list) or not lst:
|
||
# empty list -> no cards at all
|
||
if lst == []:
|
||
return False
|
||
return bool(data.get("has_valid_auth"))
|
||
matched = False
|
||
for item in lst:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
name = item.get("project_name")
|
||
if name is None:
|
||
# shape unknown -> do not filter
|
||
return bool(data.get("has_valid_auth"))
|
||
matched = True
|
||
if (
|
||
name == PROJECT_NAME
|
||
and item.get("status") == "active"
|
||
and not item.get("is_expired", False)
|
||
):
|
||
return True
|
||
if matched:
|
||
return False
|
||
return bool(data.get("has_valid_auth"))
|
||
|
||
|
||
def query_authorized(machine: str) -> bool:
|
||
now = time.time()
|
||
hit = _auth_cache.get(machine)
|
||
if hit and now - hit[1] < AUTH_CACHE_TTL:
|
||
return hit[0]
|
||
ok = False
|
||
try:
|
||
url = f"{AUTH_BASE}/public/authorizations/query?bot_qq={machine}"
|
||
with OPENER_DIRECT.open(url, timeout=10) as resp:
|
||
data = json.loads(resp.read().decode("utf-8"))
|
||
if data.get("code") == 200:
|
||
ok = _list_has_ittools_auth(data.get("data") or {})
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f"[check] auth query failed ({exc}) -> fail open", flush=True)
|
||
_auth_cache.pop(machine, None)
|
||
return True # fail open
|
||
_auth_cache[machine] = (ok, now)
|
||
return ok
|
||
|
||
|
||
# ---- trial persistence ----
|
||
def _load_trials() -> dict:
|
||
try:
|
||
with open(TRIAL_FILE, "r", encoding="utf-8") as fh:
|
||
return json.load(fh)
|
||
except Exception: # noqa: BLE001
|
||
return {}
|
||
|
||
|
||
def _save_trials(trials: dict) -> None:
|
||
os.makedirs(os.path.dirname(TRIAL_FILE), exist_ok=True)
|
||
tmp = TRIAL_FILE + ".tmp"
|
||
with open(tmp, "w", encoding="utf-8") as fh:
|
||
json.dump(trials, fh)
|
||
os.replace(tmp, TRIAL_FILE)
|
||
|
||
|
||
def trial_allowed(machine: str, tool: str) -> bool:
|
||
key = f"{machine}|{tool}"
|
||
now_ms = int(time.time() * 1000)
|
||
with _lock:
|
||
trials = _load_trials()
|
||
start = trials.get(key)
|
||
if start is None:
|
||
trials[key] = now_ms
|
||
_save_trials(trials)
|
||
return True
|
||
return (now_ms - start) < TRIAL_MS
|
||
|
||
|
||
def deactivate_card(machine_id: str) -> tuple[int, dict]:
|
||
"""Revoke authorization for this machine.
|
||
|
||
Local revocation list takes effect immediately (no CardAuth dependency);
|
||
syncing the revoke to CardAuth is best-effort.
|
||
"""
|
||
# 1) local blacklist - instant, offline-proof
|
||
rev = _load_revoked()
|
||
already = machine_id in rev
|
||
rev.add(machine_id)
|
||
_save_revoked(rev)
|
||
_auth_cache.pop(machine_id, None)
|
||
|
||
# 2) best-effort sync to CardAuth (ignored failures)
|
||
synced = 0
|
||
tok = _admin_token()
|
||
if tok:
|
||
auth_hdr = {"Authorization": f"Bearer {tok}"}
|
||
try:
|
||
res = _get_json(f"/authorizations?bot_qq={machine_id}&status=active&page=1&page_size=20", auth_hdr)
|
||
for item in ((res or {}).get("data") or {}).get("list") or []:
|
||
if item.get("project_name") != PROJECT_NAME:
|
||
continue
|
||
try:
|
||
r = _put_json(f"/authorizations/{item['id']}/revoke", {"reason": "用户在客户端自助撤销"}, auth_hdr)
|
||
if (r or {}).get("code") == 200:
|
||
synced += 1
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
else:
|
||
print("[deactivate] admin login unavailable -> local revoke only", flush=True)
|
||
|
||
if already:
|
||
return 200, {"code": 200, "message": "本机已处于撤销状态", "data": {"synced": synced}}
|
||
return 200, {"code": 200, "message": "已撤销授权", "data": {"synced": synced}}
|
||
|
||
|
||
# ================= local revocation list (instant, no CardAuth needed) ==========
|
||
REVOKED_FILE = "/app/data/revoked.json"
|
||
|
||
|
||
def _load_revoked() -> set:
|
||
try:
|
||
with open(REVOKED_FILE, "r", encoding="utf-8") as fh:
|
||
data = json.load(fh)
|
||
return set(data) if isinstance(data, list) else set()
|
||
except Exception: # noqa: BLE001
|
||
return set()
|
||
|
||
|
||
def _save_revoked(s: set) -> None:
|
||
tmp = REVOKED_FILE + ".tmp"
|
||
with open(tmp, "w", encoding="utf-8") as fh:
|
||
json.dump(sorted(s), fh)
|
||
os.replace(tmp, REVOKED_FILE)
|
||
|
||
|
||
# ================= document format conversion (calibre ebook-convert) ==========
|
||
CONVERT_FMTS = {"pdf", "docx", "txt", "rtf", "odt", "epub", "mobi", "azw3", "html"}
|
||
CONVERT_TIMEOUT = 180
|
||
|
||
|
||
def _text_to_odt(text: str, out_path: str) -> None:
|
||
"""Build a minimal, valid ODT (OpenDocument Text) package from plain text."""
|
||
import html as _h
|
||
|
||
paras = "\n".join(
|
||
f'<text:p xml:space="preserve">{_h.escape(line) or " "}</text:p>'
|
||
for line in text.splitlines()
|
||
)
|
||
content = (
|
||
'<?xml version="1.0" encoding="UTF-8"?>'
|
||
'<office:document-content '
|
||
'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" '
|
||
'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" '
|
||
'xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" '
|
||
'xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" '
|
||
'office:version="1.2">'
|
||
"<office:body><office:text>"
|
||
f"{paras}"
|
||
"</office:text></office:body></office:document-content>"
|
||
)
|
||
manifest = (
|
||
'<?xml version="1.0" encoding="UTF-8"?>'
|
||
'<manifest:manifest '
|
||
'xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" '
|
||
'manifest:version="1.2">'
|
||
'<manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.text"/>'
|
||
'<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>'
|
||
"</manifest:manifest>"
|
||
)
|
||
styles = (
|
||
'<?xml version="1.0" encoding="UTF-8"?>'
|
||
'<office:document-styles '
|
||
'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" '
|
||
'xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" '
|
||
'xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" '
|
||
'office:version="1.2"><office:styles/></office:document-styles>'
|
||
)
|
||
with zipfile.ZipFile(out_path, "w") as zf:
|
||
zf.writestr("mimetype", "application/vnd.oasis.opendocument.text", zipfile.ZIP_STORED)
|
||
zf.writestr("META-INF/manifest.xml", manifest)
|
||
zf.writestr("content.xml", content)
|
||
zf.writestr("styles.xml", styles)
|
||
|
||
|
||
def _convert_files(tmpdir: str, src_names: list, fmt: str) -> list:
|
||
"""Run ebook-convert for each source file; returns converted file paths."""
|
||
done = []
|
||
for name in src_names:
|
||
src = os.path.join(tmpdir, name)
|
||
stem = os.path.splitext(name)[0]
|
||
out = os.path.join(tmpdir, f"{stem}.{fmt}")
|
||
env = {**os.environ, "QTWEBENGINE_CHROMIUM_FLAGS": "--no-sandbox"}
|
||
|
||
def _run_convert(src_path: str, dst_path: str):
|
||
try:
|
||
proc = subprocess.run(
|
||
["ebook-convert", src_path, dst_path],
|
||
capture_output=True, timeout=CONVERT_TIMEOUT, env=env,
|
||
)
|
||
except subprocess.TimeoutExpired:
|
||
raise RuntimeError(f"{name} 转换超时(>{CONVERT_TIMEOUT}s)")
|
||
if proc.returncode != 0 or not os.path.exists(dst_path):
|
||
tail = (proc.stderr or proc.stdout or b"").decode("utf-8", "ignore")[-300:]
|
||
raise RuntimeError(f"{name} 转换失败:{tail or '未知错误'}")
|
||
|
||
if fmt == "odt":
|
||
# calibre has no odt exporter; convert to text first, then wrap a minimal ODT package
|
||
tmp_txt = out + ".tmp.txt"
|
||
_run_convert(src, tmp_txt)
|
||
text = open(tmp_txt, "r", encoding="utf-8", errors="ignore").read()
|
||
os.remove(tmp_txt)
|
||
_text_to_odt(text, out)
|
||
else:
|
||
# calibre exports "htmlz" (zipped html) instead of bare html; unwrap it
|
||
target = out + ("z" if fmt == "html" else "")
|
||
_run_convert(src, target)
|
||
if fmt == "html":
|
||
with zipfile.ZipFile(target) as zf:
|
||
names = zf.namelist()
|
||
html_name = next((n for n in names if n.lower().endswith("index.html")), None) or next((n for n in names if n.lower().endswith(".html")), None)
|
||
if not html_name:
|
||
raise RuntimeError(f"{name} 转换失败:htmlz 内未找到 HTML 文件")
|
||
with open(out, "wb") as fh:
|
||
fh.write(zf.read(html_name))
|
||
os.remove(target)
|
||
done.append(out)
|
||
return done
|
||
|
||
|
||
# ================= IT site bookmarks (shared, file-backed) =================
|
||
SITES_DIR_DEFAULT = "/app/data"
|
||
SITES_CFG = os.path.join(SITES_DIR_DEFAULT, "sites-config.json")
|
||
|
||
SEED_SITES = [
|
||
{"name": "GitHub", "url": "https://github.com", "category": "社区", "desc": "全球最大代码托管与开源社区"},
|
||
{"name": "Stack Overflow", "url": "https://stackoverflow.com", "category": "社区", "desc": "程序员问答社区"},
|
||
{"name": "V2EX", "url": "https://www.v2ex.com", "category": "社区", "desc": "开发者创意工作者社区"},
|
||
{"name": "Hacker News", "url": "https://news.ycombinator.com", "category": "社区", "desc": "硅谷科技资讯与讨论"},
|
||
{"name": "掘金", "url": "https://juejin.cn", "category": "社区", "desc": "中文开发者技术社区"},
|
||
{"name": "思否 SegmentFault", "url": "https://segmentfault.com", "category": "社区", "desc": "中文技术问答与专栏"},
|
||
{"name": "CSDN", "url": "https://www.csdn.net", "category": "社区", "desc": "中文IT技术社区"},
|
||
{"name": "博客园", "url": "https://www.cnblogs.com", "category": "社区", "desc": "老牌中文开发博客社区"},
|
||
{"name": "MDN Web Docs", "url": "https://developer.mozilla.org/zh-CN/", "category": "文档", "desc": "Web 标准权威文档(中文)"},
|
||
{"name": "Vue 3 文档", "url": "https://cn.vuejs.org", "category": "文档", "desc": "渐进式框架官方中文文档"},
|
||
{"name": "React 中文文档", "url": "https://zh-hans.react.dev", "category": "文档", "desc": "React 官方中文站"},
|
||
{"name": "TypeScript 手册", "url": "https://www.typescriptlang.org/zh/docs/", "category": "文档", "desc": "TS 官方中文 handbook"},
|
||
{"name": "Node.js 文档", "url": "https://nodejs.org/docs/latest/api/", "category": "文档", "desc": "Node.js API 官方文档"},
|
||
{"name": "Python 文档", "url": "https://docs.python.org/zh-cn/3/", "category": "文档", "desc": "Python 3 官方中文文档"},
|
||
{"name": "Rust 中文文档", "url": "https://doc.rust-lang.org/book/", "category": "文档", "desc": "Rust 程序设计语言"},
|
||
{"name": "Docker 文档", "url": "https://docs.docker.com/", "category": "文档", "desc": "Docker 官方文档"},
|
||
{"name": "Linux 命令大全", "url": "https://www.runoob.com/linux/linux-command-manual.html", "category": "文档", "desc": "菜鸟教程 Linux 命令手册"},
|
||
{"name": "Can I Use", "url": "https://caniuse.com", "category": "工具", "desc": "浏览器特性兼容性查询"},
|
||
{"name": "Regex101", "url": "https://regex101.com", "category": "工具", "desc": "正则表达式在线调试与解释"},
|
||
{"name": "JSON.cn", "url": "https://json.cn", "category": "工具", "desc": "JSON 在线解析与格式化"},
|
||
{"name": "CodePen", "url": "https://codepen.io", "category": "工具", "desc": "前端在线编辑与演示"},
|
||
{"name": "StackBlitz", "url": "https://stackblitz.com", "category": "工具", "desc": "浏览器里的完整 VS Code 项目环境"},
|
||
{"name": "npm", "url": "https://www.npmjs.com", "category": "工具", "desc": "Node 包注册与搜索"},
|
||
{"name": "PyPI", "url": "https://pypi.org", "category": "工具", "desc": "Python 包索引"},
|
||
{"name": "Docker Hub", "url": "https://hub.docker.com", "category": "工具", "desc": "容器镜像仓库"},
|
||
{"name": "crates.io", "url": "https://crates.io", "category": "工具", "desc": "Rust 包注册中心"},
|
||
{"name": "VS Code Web", "url": "https://vscode.dev", "category": "工具", "desc": "浏览器版 VS Code"},
|
||
{"name": "Git 官方", "url": "https://git-scm.com/doc", "category": "工具", "desc": "Git 版本控制文档与下载"},
|
||
{"name": "Postman 替代 Hoppscotch", "url": "https://hoppscotch.io", "category": "工具", "desc": "开源在线 API 调试工具"},
|
||
{"name": "ChatGPT", "url": "https://chat.openai.com", "category": "AI", "desc": "OpenAI 对话助手"},
|
||
{"name": "DeepSeek", "url": "https://chat.deepseek.com", "category": "AI", "desc": "深度求索对话助手"},
|
||
{"name": "Kimi", "url": "https://kimi.moonshot.cn", "category": "AI", "desc": "月之暗面长文本助手"},
|
||
{"name": "通义千问", "url": "https://tongyi.aliyun.com", "category": "AI", "desc": "阿里云大模型助手"},
|
||
{"name": "GitHub Copilot Chat", "url": "https://github.com/features/copilot", "category": "AI", "desc": "AI 结对编程"},
|
||
{"name": "阿里云", "url": "https://www.aliyun.com", "category": "云服务", "desc": "阿里云计算与开发者服务"},
|
||
{"name": "腾讯云", "url": "https://cloud.tencent.com", "category": "云服务", "desc": "腾讯云计算开发者工具"},
|
||
{"name": "Cloudflare", "url": "https://dash.cloudflare.com", "category": "云服务", "desc": "CDN/DNS/Workers 控制台"},
|
||
{"name": "Vercel", "url": "https://vercel.com", "category": "云服务", "desc": "前端部署与 Serverless"},
|
||
{"name": "Figma", "url": "https://www.figma.com", "category": "设计", "desc": "界面设计与协作"},
|
||
{"name": "Iconfont", "url": "https://www.iconfont.cn", "category": "设计", "desc": "阿里矢量图标库"},
|
||
{"name": "Ant Design", "url": "https://ant.design", "category": "设计", "desc": "企业级 UI 设计体系"},
|
||
{"name": "Element Plus", "url": "https://element-plus.org", "category": "设计", "desc": "Vue 3 组件库"},
|
||
{"name": "Tailwind CSS", "url": "https://tailwindcss.com", "category": "设计", "desc": "原子化 CSS 框架"},
|
||
{"name": "DeepL 翻译", "url": "https://www.deepl.com/translator", "category": "其他", "desc": "高质量机器翻译"},
|
||
{"name": "Bing", "url": "https://www.bing.com", "category": "其他", "desc": "微软搜索引擎"},
|
||
{"name": "百度", "url": "https://www.baidu.com", "category": "其他", "desc": "中文搜索引擎"},
|
||
]
|
||
|
||
|
||
def _sites_cfg_dir() -> str:
|
||
try:
|
||
with open(SITES_CFG, "r", encoding="utf-8") as fh:
|
||
d = str(json.load(fh).get("dir") or "").strip()
|
||
if d.startswith("/"):
|
||
return d
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
return SITES_DIR_DEFAULT
|
||
|
||
|
||
def _sites_file() -> str:
|
||
return os.path.join(_sites_cfg_dir(), "sites.json")
|
||
|
||
|
||
def _load_sites() -> list:
|
||
try:
|
||
with open(_sites_file(), "r", encoding="utf-8") as fh:
|
||
data = json.load(fh)
|
||
if isinstance(data, list):
|
||
return data
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
return [dict(s, id=f"seed-{i:02d}") for i, s in enumerate(SEED_SITES)]
|
||
|
||
|
||
def _save_sites(sites: list) -> None:
|
||
path = _sites_file()
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
tmp = path + ".tmp"
|
||
with open(tmp, "w", encoding="utf-8") as fh:
|
||
json.dump(sites, fh, ensure_ascii=False, indent=2)
|
||
os.replace(tmp, path)
|
||
|
||
|
||
def sites_api(method: str, path: str, payload: dict) -> tuple[int, dict]:
|
||
"""Shared bookmarks CRUD. path is after /sites."""
|
||
if method == "GET" and path == "":
|
||
sites = _load_sites()
|
||
return 200, {"code": 200, "message": "ok", "data": {"dir": _sites_file(), "sites": sites}}
|
||
|
||
if method == "POST" and path == "/config":
|
||
d = str(payload.get("dir") or "").strip()
|
||
if not d.startswith("/") or any(d.startswith(bad) for bad in ("/etc", "/usr", "/bin", "/sbin", "/boot", "/sys", "/proc", "/dev")):
|
||
return 400, {"code": 400, "message": "目录必须是绝对路径,且不能指向系统目录", "data": None}
|
||
try:
|
||
os.makedirs(d, exist_ok=True)
|
||
old = _load_sites()
|
||
cfg_tmp = SITES_CFG + ".tmp"
|
||
with open(cfg_tmp, "w", encoding="utf-8") as fh:
|
||
json.dump({"dir": d}, fh)
|
||
os.replace(cfg_tmp, SITES_CFG)
|
||
_save_sites(old) # migrate current data into new dir
|
||
except Exception as exc: # noqa: BLE001
|
||
return 400, {"code": 400, "message": f"设置失败: {exc}", "data": None}
|
||
return 200, {"code": 200, "message": "目录已更新,数据已迁移", "data": {"dir": _sites_file()}}
|
||
|
||
if method == "POST" and path == "":
|
||
name = str(payload.get("name") or "").strip()
|
||
url = str(payload.get("url") or "").strip()
|
||
if not name or not url:
|
||
return 400, {"code": 400, "message": "名称和网址不能为空", "data": None}
|
||
if not url.startswith(("http://", "https://")):
|
||
url = "https://" + url
|
||
sites = _load_sites()
|
||
item = {
|
||
"id": f"u{int(time.time() * 1000)}",
|
||
"name": name,
|
||
"url": url,
|
||
"category": str(payload.get("category") or "其他").strip() or "其他",
|
||
"desc": str(payload.get("desc") or "").strip(),
|
||
}
|
||
sites.append(item)
|
||
_save_sites(sites)
|
||
return 200, {"code": 200, "message": "已添加", "data": item}
|
||
|
||
sid = ""
|
||
if method in ("PUT", "DELETE") and path.startswith("/"):
|
||
sid = path[1:]
|
||
|
||
if method == "PUT" and sid:
|
||
sites = _load_sites()
|
||
for it in sites:
|
||
if it.get("id") == sid:
|
||
for k in ("name", "url", "category", "desc"):
|
||
if k in payload:
|
||
it[k] = str(payload[k]).strip()
|
||
if it["url"] and not it["url"].startswith(("http://", "https://")):
|
||
it["url"] = "https://" + it["url"]
|
||
_save_sites(sites)
|
||
return 200, {"code": 200, "message": "已更新", "data": it}
|
||
return 404, {"code": 404, "message": "条目不存在", "data": None}
|
||
|
||
if method == "DELETE" and sid:
|
||
sites = _load_sites()
|
||
keep = [it for it in sites if it.get("id") != sid]
|
||
if len(keep) == len(sites):
|
||
return 404, {"code": 404, "message": "条目不存在", "data": None}
|
||
_save_sites(keep)
|
||
return 200, {"code": 200, "message": "已删除", "data": None}
|
||
|
||
return 404, {"code": 404, "message": "not found", "data": None}
|
||
|
||
|
||
def check(machine: str, tool: str) -> int:
|
||
if not machine or not MACHINE_RE.match(machine):
|
||
return 403
|
||
if tool not in PROTECTED_TOOLS:
|
||
return 403
|
||
if machine in _load_revoked():
|
||
# user revoked on this client -> authorization ignored, trial applies
|
||
return 200 if trial_allowed(machine, tool) else 403
|
||
if query_authorized(machine):
|
||
return 200
|
||
return 200 if trial_allowed(machine, tool) else 403
|
||
|
||
|
||
# ---- card activation (server-side key) ----
|
||
_auth_state: dict = {"token": None}
|
||
|
||
|
||
def _admin_token(force: bool = False) -> str | None:
|
||
"""Login to CardAuth as admin and cache the access token."""
|
||
if not (AUTH_USER and AUTH_PASS):
|
||
return None
|
||
if _auth_state["token"] and not force:
|
||
return _auth_state["token"]
|
||
try:
|
||
res = _post_json("/auth/admin-login", {"username": AUTH_USER, "password": AUTH_PASS}, {}, timeout=15)
|
||
tok = (((res or {}).get("data") or {}).get("token") or {}).get("access_token")
|
||
if tok:
|
||
_auth_state["token"] = tok
|
||
return tok
|
||
print(f"[login] no token in response: {res}", flush=True)
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f"[login] failed ({exc})", flush=True)
|
||
return None
|
||
|
||
|
||
def _get_json(path: str, headers: dict, timeout: int = 15) -> dict:
|
||
req = request.Request(f"{AUTH_BASE}{path}", headers=headers, method="GET")
|
||
with OPENER_DIRECT.open(req, timeout=timeout) as resp:
|
||
return json.loads(resp.read().decode("utf-8"))
|
||
|
||
|
||
def _put_json(path: str, payload: dict, headers: dict, timeout: int = 15) -> dict:
|
||
data = json.dumps(payload).encode("utf-8")
|
||
hdrs = {"Content-Type": "application/json", **headers}
|
||
req = request.Request(f"{AUTH_BASE}{path}", data=data, headers=hdrs, method="PUT")
|
||
with OPENER_DIRECT.open(req, timeout=timeout) as resp:
|
||
return json.loads(resp.read().decode("utf-8"))
|
||
|
||
|
||
def _post_json(path: str, payload: dict, headers: dict, timeout: int = 15) -> dict:
|
||
data = json.dumps(payload).encode("utf-8")
|
||
hdrs = {"Content-Type": "application/json", **headers}
|
||
req = request.Request(f"{AUTH_BASE}{path}", data=data, headers=hdrs, method="POST")
|
||
with OPENER_DIRECT.open(req, timeout=timeout) as resp:
|
||
return json.loads(resp.read().decode("utf-8"))
|
||
|
||
|
||
def activate_card(card_key: str, machine_id: str, contact_qq: str, replace: bool = False) -> tuple[int, dict]:
|
||
"""Pre-check with /public/verify (CARD_AUTH_KEY), then activate.
|
||
|
||
Returns (http_status, body_dict).
|
||
"""
|
||
tok = _admin_token()
|
||
auth_hdr = {"Authorization": f"Bearer {tok}"} if tok else {}
|
||
|
||
# replace: revoke this machine's existing authorizations first (user is
|
||
# swapping to a new card; confirmed on the client side)
|
||
if replace:
|
||
try:
|
||
deactivate_card(machine_id)
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f"[activate] replace revoke failed ({exc}) -> continue", flush=True)
|
||
|
||
# NOTE: do NOT call /public/verify with an unused card here - in this
|
||
# CardAuth version the first verify call binds & consumes the card.
|
||
|
||
# activate (web channel, with admin session if configured)
|
||
payload = {
|
||
"card_key": card_key,
|
||
"bot_qq": machine_id,
|
||
"contact_qq": contact_qq or machine_id,
|
||
"device_info": "IT-Tools Web",
|
||
}
|
||
# Retry ONLY on explicit 401 (stale token). Any other failure is returned
|
||
# as-is: re-sending an activate that already consumed the card would burn it.
|
||
try:
|
||
ares = _post_json("/public/authorizations/activate", payload, auth_hdr)
|
||
except Exception as exc: # noqa: BLE001
|
||
return 502, {"code": 502, "message": f"授权服务器连接失败: {exc}", "data": None}
|
||
if (ares or {}).get("code") == 401 and (AUTH_USER and AUTH_PASS):
|
||
tok = _admin_token(force=True)
|
||
auth_hdr = {"Authorization": f"Bearer {tok}"} if tok else {}
|
||
try:
|
||
ares = _post_json("/public/authorizations/activate", payload, auth_hdr)
|
||
except Exception as exc: # noqa: BLE001
|
||
return 502, {"code": 502, "message": f"授权服务器连接失败: {exc}", "data": None}
|
||
|
||
code = 200 if (ares or {}).get("code") == 200 else 400
|
||
if code == 200:
|
||
_auth_cache.pop(machine_id, None) # invalidate cache -> fresh query
|
||
rev = _load_revoked()
|
||
if machine_id in rev:
|
||
rev.discard(machine_id)
|
||
_save_revoked(rev) # new activation lifts the local revocation
|
||
return code, ares
|
||
|
||
|
||
class Handler(BaseHTTPRequestHandler):
|
||
protocol_version = "HTTP/1.1"
|
||
|
||
def log_message(self, fmt, *args): # quiet
|
||
pass
|
||
|
||
def _reply(self, status: int, body: bytes = b"", ctype="text/plain"):
|
||
self.send_response(status)
|
||
self.send_header("Content-Type", ctype)
|
||
self.send_header("Content-Length", str(len(body)))
|
||
self.end_headers()
|
||
if body:
|
||
self.wfile.write(body)
|
||
|
||
# ---------- GET ----------
|
||
def do_GET(self):
|
||
parsed = parse.urlparse(self.path)
|
||
if parsed.path == "/auth-status":
|
||
qs = parse.parse_qs(parsed.query)
|
||
machine = (qs.get("machine_id") or [""])[0]
|
||
if not MACHINE_RE.match(machine):
|
||
self._reply(400, json.dumps({"code": 400, "message": "机器码格式错误"}, ensure_ascii=False).encode("application/json"), "application/json")
|
||
return
|
||
authorized = False
|
||
if machine not in _load_revoked():
|
||
authorized = query_authorized(machine)
|
||
body = {"code": 200, "message": "ok", "data": {"authorized": authorized}}
|
||
self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
|
||
if parsed.path == "/sites":
|
||
status, body = sites_api("GET", "", {})
|
||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
|
||
if parsed.path == "/check":
|
||
machine = self.headers.get("X-Machine-Id", "")
|
||
tool = self.headers.get("X-Tool", "")
|
||
status = check(machine, tool)
|
||
self._reply(status, b"ok" if status == 200 else b"forbidden")
|
||
return
|
||
|
||
if parsed.path == "/translate":
|
||
target = f"{UPSTREAM}?{parsed.query}"
|
||
try:
|
||
with OPENER_PROXY.open(target, timeout=TIMEOUT) as resp:
|
||
body = resp.read()
|
||
ctype = resp.headers.get("Content-Type", "application/json; charset=utf-8")
|
||
self._reply(200, body, ctype)
|
||
except Exception as exc: # noqa: BLE001
|
||
payload = f'{{"error":"relay error: {exc}"}}'.encode()
|
||
self._reply(502, payload, "application/json")
|
||
return
|
||
|
||
self._reply(404, b"not found")
|
||
|
||
# ---------- POST ----------
|
||
def _read_payload(self) -> dict:
|
||
try:
|
||
length = int(self.headers.get("Content-Length") or 0)
|
||
raw = self.rfile.read(length) if length else b"{}"
|
||
return json.loads(raw.decode("utf-8") or "{}")
|
||
except Exception: # noqa: BLE001
|
||
return {}
|
||
|
||
def do_POST(self):
|
||
parsed = parse.urlparse(self.path)
|
||
if parsed.path == "/convert":
|
||
self._handle_convert()
|
||
return
|
||
|
||
if parsed.path == "/sites" or parsed.path == "/sites/config":
|
||
sub = parsed.path[len("/sites"):]
|
||
status, body = sites_api("POST", sub, self._read_payload())
|
||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
|
||
if parsed.path == "/deactivate":
|
||
try:
|
||
length = int(self.headers.get("Content-Length") or 0)
|
||
raw = self.rfile.read(length) if length else b"{}"
|
||
payload = json.loads(raw.decode("utf-8") or "{}")
|
||
except Exception: # noqa: BLE001
|
||
self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json")
|
||
return
|
||
machine_id = str(payload.get("machine_id") or "").strip()
|
||
if not MACHINE_RE.match(machine_id):
|
||
self._reply(400, json.dumps({"code": 400, "message": "机器码格式错误"}, ensure_ascii=False).encode(), "application/json")
|
||
return
|
||
status, body = deactivate_card(machine_id)
|
||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
|
||
if parsed.path == "/activate":
|
||
try:
|
||
length = int(self.headers.get("Content-Length") or 0)
|
||
raw = self.rfile.read(length) if length else b"{}"
|
||
payload = json.loads(raw.decode("utf-8") or "{}")
|
||
except Exception: # noqa: BLE001
|
||
self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json")
|
||
return
|
||
|
||
card_key = str(payload.get("card_key") or "").strip()
|
||
machine_id = str(payload.get("machine_id") or "").strip()
|
||
contact_qq = str(payload.get("contact_qq") or "").strip()
|
||
replace = bool(payload.get("replace"))
|
||
if not card_key:
|
||
self._reply(400, json.dumps({"code": 400, "message": "请输入卡密"}, ensure_ascii=False).encode(), "application/json")
|
||
return
|
||
if not MACHINE_RE.match(machine_id):
|
||
self._reply(400, json.dumps({"code": 400, "message": "机器码格式错误"}, ensure_ascii=False).encode(), "application/json")
|
||
return
|
||
|
||
status, body = activate_card(card_key, machine_id, contact_qq, replace=replace)
|
||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
|
||
self._reply(404, b"not found")
|
||
|
||
# ---------- conversion ----------
|
||
def _handle_convert(self):
|
||
try:
|
||
machine = self.headers.get("X-Machine-Id", "")
|
||
tool = self.headers.get("X-Tool", "")
|
||
if check(machine, tool) != 200:
|
||
self._reply(403, json.dumps({"code": 403, "message": "授权校验未通过或试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
ctype = self.headers.get("Content-Type", "")
|
||
if "multipart/form-data" not in ctype:
|
||
self._reply(400, json.dumps({"code": 400, "message": "需要 multipart 上传"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype})
|
||
fmt = (form.getvalue("format") or "").lower()
|
||
if fmt not in CONVERT_FMTS:
|
||
self._reply(400, json.dumps({"code": 400, "message": f"不支持的目标格式:{fmt}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
items = form["files"] if "files" in form else []
|
||
if not isinstance(items, list):
|
||
items = [items]
|
||
items = [it for it in items if getattr(it, "filename", None)]
|
||
if not items:
|
||
self._reply(400, json.dumps({"code": 400, "message": "请选择要转换的文件"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
|
||
tmpdir = tempfile.mkdtemp(prefix="convert-")
|
||
try:
|
||
src_names = []
|
||
for it in items:
|
||
safe = os.path.basename(it.filename).replace("\\", "_")
|
||
safe = re.sub(r"[^\w.\-()\u4e00-\u9fa5]+", "_", safe) or "file"
|
||
with open(os.path.join(tmpdir, safe), "wb") as fh:
|
||
shutil.copyfileobj(it.file, fh)
|
||
src_names.append(safe)
|
||
|
||
outs = _convert_files(tmpdir, src_names, fmt)
|
||
|
||
if len(outs) == 1:
|
||
data = open(outs[0], "rb").read()
|
||
fname = os.path.basename(outs[0])
|
||
self.send_response(200)
|
||
self.send_header("Content-Type", "application/octet-stream")
|
||
self.send_header("Content-Disposition", f"attachment; filename*=UTF-8''{parse.quote(fname)}")
|
||
self.send_header("Content-Length", str(len(data)))
|
||
self.end_headers()
|
||
self.wfile.write(data)
|
||
else:
|
||
buf = io.BytesIO()
|
||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||
for o in outs:
|
||
zf.write(o, os.path.basename(o))
|
||
data = buf.getvalue()
|
||
self.send_response(200)
|
||
self.send_header("Content-Type", "application/zip")
|
||
self.send_header("Content-Disposition", "attachment; filename=converted.zip")
|
||
self.send_header("Content-Length", str(len(data)))
|
||
self.end_headers()
|
||
self.wfile.write(data)
|
||
finally:
|
||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||
except RuntimeError as exc:
|
||
self._reply(400, json.dumps({"code": 400, "message": str(exc)}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
except Exception as exc: # noqa: BLE001
|
||
self._reply(500, json.dumps({"code": 500, "message": f"转换服务错误:{exc}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
|
||
# ---------- PUT / DELETE ----------
|
||
def do_PUT(self):
|
||
parsed = parse.urlparse(self.path)
|
||
if parsed.path.startswith("/sites/"):
|
||
sub = parsed.path[len("/sites"):]
|
||
status, body = sites_api("PUT", sub, self._read_payload())
|
||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
self._reply(404, b"not found")
|
||
|
||
def do_DELETE(self):
|
||
parsed = parse.urlparse(self.path)
|
||
if parsed.path.startswith("/sites/"):
|
||
sub = parsed.path[len("/sites"):]
|
||
status, body = sites_api("DELETE", sub, {})
|
||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||
return
|
||
self._reply(404, b"not found")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
ThreadingHTTPServer(("0.0.0.0", 8091), Handler).serve_forever()
|