# -*- coding: utf-8 -*- """业务门禁:api_server 唯一挂接点。 run() 时调 init(data_dir):读 data/license/config.json + 随软件分发的 pinned_keys.json + 已存授权状态;配置了凭据且信任根就绪则起心跳线程。 任何初始化异常都不打断服务启动,但门禁 fail closed: - /api/license/* 永远放行(激活入口本身不能被锁死); - 其余请求:enforce 且 can_run()=False → GET 一律回授权页(自包含 HTML, 内嵌激活表单),POST/业务 API 回 403 {"error":{"code":"LICENSE_REQUIRED"}}。 本地开发豁免:data/license/config.json 写 "enforce": false(交付/发布环境 不带该文件或 enforce=true,代码默认 true)。 """ import hashlib import json import os import threading import time from .client import LicenseClient, DEFAULT_API_BASE from .store import JsonFileStore, DpapiSecretStore, StorageError from .verify import VerifyError, load_keyring_file, build_keyring, UUID_RE try: # 构建时生成(仅交付版有) from . import license_build_config as BUILD except ImportError: BUILD = None _lock = threading.Lock() _client = None _cfg = {"enforce": True, "api_base": DEFAULT_API_BASE, "selfheal_seconds": 300} _hb_thread = None _hb_stop = None _last_selfheal = 0.0 # monotonic:门禁自愈触发节流 _INTEGRITY_FAIL = "" # N1 源码保护(2026-10-27):非空 = 交付包文件被改,全线拦截 def _check_build_integrity(): """N1 源码保护:交付包启动时校验 .py 哈希清单(build 期烧入 BUILD.INTEGRITY, 覆盖 server/core 全部 .py)。被改 = fail closed 全线拦截(含授权口——防的是 「改掉本文件/门禁调用后再激活」的绕过路径)。开发版(BUILD=None)不校验。 INTEGRITY 键相对 app 根(server/...、core/...、shell.py)。""" global _INTEGRITY_FAIL if BUILD is None: return manifest = getattr(BUILD, "INTEGRITY", None) if not isinstance(manifest, dict) or not manifest: return app_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) for rel, want in sorted(manifest.items()): p = os.path.join(app_root, rel.replace("/", os.sep)) try: with open(p, "rb") as f: got = hashlib.sha256(f.read()).hexdigest() except OSError: _INTEGRITY_FAIL = rel + "(缺失)" print("⚠ 完整性校验失败:%s" % _INTEGRITY_FAIL) return if got != str(want).lower(): _INTEGRITY_FAIL = rel print("⚠ 完整性校验失败:%s 哈希不符(文件被改动?)" % rel) return # ---------------------------------------------------------------- 初始化 def _load_cfg(lic_dir): cfg = {"enforce": True, "api_base": os.environ.get("LICENSE_API_BASE_URL") or DEFAULT_API_BASE} p = os.path.join(lic_dir, "config.json") try: if os.path.exists(p): with open(p, encoding="utf-8") as f: user = json.load(f) if isinstance(user, dict): if "api_base" in user and not os.environ.get("LICENSE_API_BASE_URL"): cfg["api_base"] = str(user["api_base"]).rstrip("/") cfg["enforce"] = bool(user.get("enforce", True)) if user.get("pinned_keys"): cfg["pinned_keys"] = user["pinned_keys"] except Exception as e: print("⚠ license 配置读取失败(按默认 enforce 处理):%s" % e) return cfg def init(data_dir): """服务启动时调用一次。永不抛异常(授权子系统坏了也不许拖死服务)。 信任根优先级:交付版(license_build_config.py 存在)→ 只信烧进包里的公钥/ 平台地址/强制开关,本地 config.json、环境变量、pinned_keys.json 一律不参与 (P0-1:客户改文件/环境变量无法自建信任根)。开发版(无该文件)→ 走 data/license/config.json + pinned_keys.json 的老路径,便于联调。 """ global _client, _cfg, _hb_thread, _hb_stop with _lock: if _client is not None: return _client lic_dir = os.environ.get("LICENSE_DATA_DIR") or os.path.join(data_dir, "license") try: os.makedirs(lic_dir, exist_ok=True) expected_product = None selfheal = 300 if BUILD is not None: _check_build_integrity() # N1:烧入清单校验,被改 → 全线拦截 _cfg = {"enforce": bool(BUILD.ENFORCE), "api_base": str(BUILD.API_BASE).rstrip("/"), "selfheal_seconds": getattr(BUILD, "SELFHEAL_SECONDS", 300)} keyring = build_keyring(BUILD.PINNED_KEYS) expected_product = getattr(BUILD, "PRODUCT_ID", None) else: _cfg = _load_cfg(lic_dir) _cfg.setdefault("selfheal_seconds", 300) expected_product = _cfg.get("expected_product_id") keys_path = _cfg.get("pinned_keys") or os.path.join( os.path.dirname(os.path.abspath(__file__)), "pinned_keys.json") keyring = load_keyring_file(keys_path) if not keyring: print("⚠ license:可信公钥清单为空(%s)——激活/心跳将无法通过验签" % keys_path) selfheal = max(5, int(_cfg.get("selfheal_seconds") or 300)) _cfg["selfheal_seconds"] = selfheal client = LicenseClient( api_base=_cfg["api_base"], state_store=JsonFileStore(os.path.join(lic_dir, "state.json")), secret_store=DpapiSecretStore(os.path.join(lic_dir, "secret.bin")), keyring=keyring, expected_product_id=expected_product) _client = client if client.has_credentials() and keyring: _start_heartbeat() elif client.has_credentials(): print("⚠ license:已配置实例凭据但无可信公钥,心跳未启动(补齐 pinned_keys 后重启)") except Exception as e: print("⚠ license 子系统初始化失败(门禁按未授权处理):%s" % e) return _client def _client_for_request(): """请求期取客户端;未初始化(如直连 Handler 单测)时懒初始化失败 → None。""" return _client def _start_heartbeat(): global _hb_thread, _hb_stop if _hb_thread and _hb_thread.is_alive(): return _hb_stop = threading.Event() _hb_thread = threading.Thread(target=_client.run_forever, args=(_hb_stop,), name="license-heartbeat", daemon=True) _hb_thread.start() def _restart_heartbeat(): """心跳循环在 403/409 后按协议停在人工处理状态;用户侧动作(手动刷新/ 门禁自愈)成功续上租约时,把循环拉起来恢复自动调度。""" global _hb_thread, _hb_stop with _lock: old = _hb_thread if _hb_stop: _hb_stop.set() if old and old is not threading.current_thread(): old.join(timeout=2) _hb_thread = None _start_heartbeat() def _selfheal_maybe(status): """授权不可运行时借 /api/license/status 的轮询做后台自愈: 节流期内至多试一次心跳;成功(含从 403 停摆状态救回)即重启心跳循环。""" global _last_selfheal if not _cfg.get("enforce", True) or not status.get("configured"): return if status.get("can_run"): return now = time.monotonic() if now - _last_selfheal < _cfg.get("selfheal_seconds", 300): return _last_selfheal = now threading.Thread(target=_selfheal_run, name="license-selfheal", daemon=True).start() def _selfheal_run(): try: r = _client.heartbeat() except Exception: return if r.get("ok"): _restart_heartbeat() def heartbeat_running(): return bool(_hb_thread and _hb_thread.is_alive()) # ---------------------------------------------------------------- 请求拦截 def intercept(method, path, body=None): """None = 放行;否则返回 {"kind":"json"|"html","code":int,...} 由 Handler 发送。""" if _INTEGRITY_FAIL: # N1:文件被改 = 无任何放行(含授权口) if method == "GET" and not path.startswith("/api/"): return {"kind": "html", "code": 200, "text": _integrity_page()} return {"kind": "json", "code": 403, "obj": {"error": {"code": "INTEGRITY_FAILED", "message": "软件文件完整性校验失败,请重新安装或联系软件提供方"}}} if path.startswith("/api/license/"): return _license_api(method, path, body) if path.startswith("/api/version"): # 版本状态口(/api/version、/api/version_info)在锁定态也放行: # 排障要看版本;强制更新页要轮询它(2026-10-27 5.9)。 return None if not _cfg.get("enforce", True): return None c = _client_for_request() if c is None: return _blocked("授权子系统未初始化") ok, reason = c.can_run_safe() if ok: return None if method == "GET" and not path.startswith("/api/"): # 页面/静态资源 → 授权页;/api/* 一律 403 JSON(前端 fetch 不能收到 HTML) return {"kind": "html", "code": 200, "text": gate_page(reason)} return _blocked(reason) def can_run_now(): """给集成层(MCP 等)用:enforce 开启时必须授权有效。返回 (ok, reason)。 与 intercept 同一口径,但不关心路由形态(2026-10-15 收费挂钩 MCP)。""" if not _cfg.get("enforce", True): return True, "" c = _client_for_request() if c is None: return False, "授权子系统未初始化" return c.can_run_safe() def _integrity_page(): """N1 完整性拦截页(自包含):文件被改时的唯一可见页面。""" return """
检测到程序文件被改动,为保障授权与数据安全,软件已停止服务。
请重新安装官方软件包,或联系软件提供方处理。您的数据不受影响。