# -*- 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": []} # ==================== 授权周期(离线最多 LICENSE_TTL_DAYS 天) ==================== def license_status() -> tuple[str, dict | None]: """本地授权票据状态:("ok", payload) / ("missing", None) / ("invalid", None) / ("expired", payload)。 过期判定以票据内 expiresAt(控制面签发,issuedAt + 7 天)为基准;缺该字段一律视为过期 (fail-safe,触发联网刷新,不因旧票据而永久放行)。 """ if not license_path.is_file(): return ("missing", None) try: lic = verify_license() except ValueError: return ("invalid", None) exp = lic.get("expiresAt") if not exp or time.time() > int(exp): return ("expired", lic) return ("ok", lic) def ensure_license(account: str) -> tuple[bool, dict | None]: """确保本地授权票据可用且属于当前账号:ok → (True, payload);否则联网刷新一次后复查。 票据必须与登录账号一致:票据只按 expiresAt 判过期,换账号登录后旧票仍在有效期内, 沿用旧票会让「个人中心可见插件」与「运行门禁」停留在上一账号的授权快照 (表现为换账号后显示"暂无可用插件"),故账号不匹配一律视为不可用并强制刷新。 刷新失败(离线/控制面不可达)→ (False, None)。这是「可见性/运行/平台登录」的统一授权门禁, 过期且实际在线时会自动刷新恢复(用户无感),离线则拒绝并提示联网刷新。 """ status, payload = license_status() if status == "ok" and (payload or {}).get("userId") == account: return True, payload try: from webhost.backend.core.cpapi import _sync_licensing # 延迟导入,避免模块环 _sync_licensing(account) except Exception as _exc: # noqa: BLE001 联网刷新失败(离线/控制面不可达) _LOGGER.warning("授权票据联网刷新失败(离线或控制面不可达):%s", _exc) status, payload = license_status() return (status == "ok" and (payload or {}).get("userId") == account), payload # ==================== 缓存写读 ==================== 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=可运行,否则返回拒绝原因字符串。 - 授权周期:本地票据须有效(7 天窗口,见 ensure_license);缺失/过期先联网刷新一次, 仍不可用则拒绝(离线超期必须联网更新票据)。 - 验签授权票据,校验该插件 canRun。 - 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。 - 离线:跳过强制更新 deadline 检查(不联网一直能用)。 - 联网:额外校验强制更新 deadline 已过则拒启旧版本。 """ ok, lic = ensure_license(account) if not ok: return "授权已过期(最长离线 7 天),请联网刷新后重试" control = verify_control() if plugin_id in control.get("revokedPlugins", []): return "插件已被下架(revoked),禁止运行" if plugin_id in control.get("disabledPlugins", []): return "插件已被禁用(disabled),禁止运行" lic_plugins = {p.get("pluginId"): p for p in (lic or {}).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)。 必须带 X-API-Token 内部凭证:中心机 CONTROLPLANE_TOKEN 非空时该接口强制校验, 无头 POST 一律 401(此前运行上报全部静默失败落离线暂存、补报同样无头永远补不上), 与 cpapi.py 各接口的头注入保持一致。""" import requests from webhost.backend.core import config headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {} r = requests.post(f"{_CONTROLPLANE_URL}/api/runtime/report", json=rec, headers=headers, 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