Files
37duAutomation/webhost/backend/core/licensing.py
T
puddy cb04790d28 refactor: 重构项目目录结构与代码组织
1.  重构controlplane与webhost后端的包结构,按领域拆分模块到core/apis子包
2.  移动并整理工具脚本到tools子目录,统一管理运维脚本
3.  重构插件运行时、调度、作业管理等核心模块到core子包
4.  更新AGENTS.md文档,明确各代码形态的组织规范
5.  清理重复的旧文件与冗余代码
2026-09-14 12:34:54 +08:00

283 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
职责(对应架构设计七、八节):
- 以 %LOCALAPPDATA%\\37duAutomation 为根,缓存:
license.json (离线授权票据,Ed25519 签名,离线一直有效)
control.json (管控清单缓存:revoked/disabled/forcedUpdates + updatedAt)
keys\\pub.pem (中心机公钥,首次联网拉取缓存,供离线验签)
- is_online() —— 收敛的单一联网判定:最近一次成功拉取/心跳时间戳 + 失败二次确认。
离线只豁免「强制更新 deadline」,票据验签/授权/下架禁用离线仍生效。
- verify_license() / verify_control() —— 用缓存公钥离线验签。
- report() —— 运行上报到中心机(联网时实时上报;离线记录暂存,重连后补报)。
"""
from __future__ import annotations
import base64
import json
import logging
import os
import time
from datetime import datetime
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
_LOGGER = logging.getLogger(__name__)
# 数据根目录:与影刀版共享 %LOCALAPPDATA%\37duAutomation
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
or Path.home(), "37duAutomation")
KEYS_DIR = _APP_DATA / "keys"
license_path = _APP_DATA / "license.json"
control_path = _APP_DATA / "control.json"
reports_path = _APP_DATA / "offline_reports.jsonl" # 离线上报暂存,重连后补报
# 联网判定阈值:超过此秒数未成功拉取/心跳即视为离线
_ONLINE_TTL = 180
_last_sync = 0.0
_sync_lock = None # 由 import 后注入 threading.Lock(避免循环依赖按模块初始化)
_CONTROLPLANE_URL = "" # 由 main.py 注入
def init(controlplane_url: str, sync_lock) -> None:
"""注入控制面地址与同步锁(main.py 启动时调用)。"""
global _CONTROLPLANE_URL, _sync_lock
_CONTROLPLANE_URL = (controlplane_url or "").rstrip("/")
_sync_lock = sync_lock
_APP_DATA.mkdir(exist_ok=True)
KEYS_DIR.mkdir(exist_ok=True)
# ==================== 联网判定 ====================
def touch_sync() -> None:
"""标记最近一次与控制面成功同步的时点(拉票/清单/心跳成功后调用)。"""
global _last_sync
with _sync_lock:
_last_sync = time.time()
def is_online() -> bool:
"""收敛的单一联网判定:默认联网(无缓存/从未同步视联网),最大 _ONLINE_TTL 未同步判离线。"""
with _sync_lock:
return (time.time() - _last_sync) <= _ONLINE_TTL
# ==================== 公钥缓存与验签 ====================
def _pub_pem_path() -> Path:
return KEYS_DIR / "pub.pem"
def cache_public_key(pem_text: str) -> None:
"""缓存中心机公钥(首次联网拉取)。用于后续离线验签。"""
pem_text = (pem_text or "").strip()
if not pem_text:
return
_pub_pem_path().write_text(pem_text, encoding="ascii")
touch_sync()
def _load_public_key() -> Ed25519PublicKey | None:
try:
return serialization.load_pem_public_key(_pub_pem_path().read_bytes())
except Exception: # noqa: BLE001 无缓存/损坏视为无公钥
return None
def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
"""验签返回 payload;签名非法抛 ValueError。"""
if "." not in blob:
raise ValueError("bad blob")
b64, sig64 = blob.rsplit(".", 1)
canon = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
sig = base64.urlsafe_b64decode(sig64 + "=" * (-len(sig64) % 4))
if len(sig) != 64:
raise ValueError("bad signature len")
pub.verify(sig, canon)
return json.loads(canon)
def verify_license() -> dict:
"""验签本地缓存授权票据,返回 payload;无缓存/验签失败抛异常。"""
if not license_path.is_file():
raise ValueError("无本地授权票据(license.json)")
pub = _load_public_key()
if pub is None:
raise ValueError("缺少中心机公钥,无法验签授权票据")
data = json.loads(license_path.read_text(encoding="utf-8"))
return _verify_blob(data["ticket"], pub)
def verify_control() -> dict:
"""验签本地缓存管控清单,返回 payload;无缓存时返回空管控(不禁止任何插件)。"""
if not control_path.is_file():
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
pub = _load_public_key()
if pub is None:
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
try:
data = json.loads(control_path.read_text(encoding="utf-8"))
payload = _verify_blob(data["ticket"], pub)
return payload if isinstance(payload, dict) else {}
except Exception: # noqa: BLE001 缓存损坏按"不禁止"兜底,联网后会重新拉取
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
# ==================== 缓存写读 ====================
def save_license(ticket_json: dict | str) -> None:
"""持久化授权票据。ticket 可为 {ticket,...} 或原始签名串。"""
if isinstance(ticket_json, dict):
text = json.dumps(ticket_json, ensure_ascii=False)
else:
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
license_path.write_text(text, encoding="utf-8")
touch_sync()
def save_control(ticket_json: dict | str) -> None:
"""持久化管控清单缓存。"""
if isinstance(ticket_json, dict):
text = json.dumps(ticket_json, ensure_ascii=False)
else:
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
control_path.write_text(text, encoding="utf-8")
touch_sync()
def run_check_allowed(plugin_id: str, account: str, online: bool) -> str | None:
"""启动前校验链(离线/联网通用骨架),返回 None=可运行,否则返回拒绝原因字符串。
- 验签授权票据,校验该插件 canRun。
- 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。
- 离线:跳过强制更新 deadline 检查(不联网一直能用)。
- 联网:额外校验强制更新 deadline 已过则拒启旧版本。
"""
control = verify_control()
if plugin_id in control.get("revokedPlugins", []):
return "插件已被下架(revoked),禁止运行"
if plugin_id in control.get("disabledPlugins", []):
return "插件已被禁用(disabled),禁止运行"
# 授权:先验签本地授权票据(离线可用)
try:
lic = verify_license()
except Exception as _exc: # noqa: BLE001 授权票据不可用
return f"本地授权票据校验失败:{_exc}" if online else "本地授权票据校验失败"
lic_plugins = {p.get("pluginId"): p for p in lic.get("plugins", [])}
grant = lic_plugins.get(plugin_id)
if not grant:
return f"账号 {account} 无插件「{plugin_id}」的授权"
if not grant.get("canRun"):
return f"账号 {account} 无「{plugin_id}」的运行授权"
# 强制更新:仅联网时严格校验 deadline;离线跳过(核心规则)
if online:
forced = next((f for f in control.get("forcedUpdates", [])
if f.get("pluginId") == plugin_id), None)
if forced:
min_ver = forced.get("minVersion", "")
deadline = forced.get("deadline", "")
if min_ver and deadline and _deadline_passed(deadline):
installed = _installed_version(plugin_id)
if installed and _version_lt(installed, min_ver):
return (f"插件需强制升级到 v{min_ver} 以上(deadline 已过),"
f"当前 v{installed} 已禁止启动,请先更新")
return None
def _installed_version(plugin_id: str) -> str:
"""读取本机当前已装版本(active.json 或插件目录)。有则不返回最新,供强制更新判断。"""
act = _APP_DATA / "active.json"
try:
d = json.loads(act.read_text(encoding="utf-8")) if act.is_file() else {}
return d.get("version", "") if d.get("pluginId") == plugin_id else ""
except Exception: # noqa: BLE001
return ""
def _deadline_passed(deadline: str) -> bool:
try:
dt = datetime.fromisoformat(deadline.replace("Z", "+00:00"))
return datetime.now(dt.tzinfo) > dt
except Exception: # noqa: BLE001
# 解析失败时按未过期兜底(不误伤在线用户)
return False
def _version_lt(a: str, b: str) -> bool:
"""版本比较:数字段按 int,非数字段按 str 小写。"""
def _k(s):
try:
return (1, int(s))
except ValueError:
return (0, str(s).lower())
return tuple(_k(x) for x in str(a).split(".")) < tuple(_k(x) for x in str(b).split("."))
# ==================== 运行上报 ====================
def report(account: str, device_id: str, plugin_id: str, version: str,
status: str, msg: str = "", duration_sec: int = 0) -> None:
"""运行上报:联网实时 POST;离线暂存 jsonl,重连后补报。失败不阻断主流程。"""
rec = {"account": account, "device_id": device_id, "plugin_id": plugin_id,
"version": version, "status": status, "msg": msg,
"duration_sec": int(duration_sec),
"at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
if not _CONTROLPLANE_URL:
return
if _push_report(rec):
touch_sync()
return
# 离线:暂存待补报
try:
with open(reports_path, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
except OSError:
pass
def _push_report(rec: dict) -> bool:
"""同步上报一条到中心机;成功返回 True。"""
try:
_push_via_tempfile(rec) # 用 go-offset 方式直连
return True
except Exception: # noqa: BLE001
return False
def _push_via_tempfile(rec: dict) -> None:
"""向 /api/runtime/report 的同步 POST(requests)。"""
import requests
r = requests.post(f"{_CONTROLPLANE_URL}/api/runtime/report",
json=rec, timeout=5)
r.raise_for_status()
def flush_offline_reports() -> int:
"""重连后补报此前暂存的离线记录;返回补报条数。"""
if not reports_path.is_file():
return 0
sent = 0
pending = []
try:
lines = [l for l in reports_path.read_text(encoding="utf-8").splitlines() if l.strip()]
for ln in lines:
try:
rec = json.loads(ln)
except ValueError:
continue
try:
_push_via_tempfile(rec)
sent += 1
except Exception: # noqa: BLE001
pending.append(ln) # 仍失败则保留下次再补
if not pending:
reports_path.unlink(missing_ok=True) # 全部成功则清空
else:
reports_path.write_text("\n".join(pending) + "\n", encoding="utf-8")
except OSError:
pass
return sent