# -*- 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 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 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:门禁自愈触发节流 # ---------------------------------------------------------------- 初始化 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: _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 path.startswith("/api/license/"): return _license_api(method, path, body) 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 _blocked(reason): return {"kind": "json", "code": 403, "obj": {"error": {"code": "LICENSE_REQUIRED", "message": reason}}} def status_view(): c = _client_for_request() if c is None: return {"enforce": _cfg.get("enforce", True), "configured": False, "activated": False, "can_run": False, "reason": "授权子系统未初始化", "api_base": _cfg.get("api_base")} return c.status(enforce=bool(_cfg.get("enforce", True)), heartbeat_running=heartbeat_running()) def _license_api(method, path, body): if method == "GET" and path == "/api/license/status": out = status_view() _selfheal_maybe(out) # 授权不可运行 → 借轮询节流自愈(后台线程) return {"kind": "json", "code": 200, "obj": {"ok": True, "data": out}} if method == "POST" and path == "/api/license/activate": b = body if isinstance(body, dict) else {} iid, lk, sec = (b.get("instance_id") or "").strip(), \ (b.get("license_key") or "").strip(), \ (b.get("secret") or "").strip() if not (iid and lk and sec): return {"kind": "json", "code": 400, "obj": {"error": {"code": "BAD_REQUEST", "message": "instance_id / license_key / secret 都必填"}}} c = _client_for_request() if c is None: return _blocked("授权子系统未初始化") try: c.configure(iid, lk, sec) r = c.activate() except (StorageError, VerifyError) as e: r = {"ok": False, "code": "CONFIG_FAILED", "message": str(e)} if r.get("ok"): _restart_heartbeat() # 激活成功:新循环(旧循环可能停在人工处理态) out = status_view() out["result"] = r return {"kind": "json", "code": 200, "obj": {"ok": bool(r.get("ok")), "data": out}} if method == "POST" and path == "/api/license/refresh": c = _client_for_request() if c is None: return _blocked("授权子系统未初始化") try: r = c.heartbeat() except (StorageError, VerifyError) as e: r = {"ok": False, "code": "ERROR", "message": str(e)} if r.get("ok"): _restart_heartbeat() # 手动续上 → 恢复自动心跳调度 out = status_view() out["result"] = r return {"kind": "json", "code": 200, "obj": {"ok": bool(r.get("ok")), "data": out}} return {"kind": "json", "code": 404, "obj": {"error": {"code": "NOT_FOUND", "message": "未知授权接口"}}} # ---------------------------------------------------------------- 授权页 _PAGE = None def gate_page(reason): """未授权时替代正常页面的自包含页面:状态 + 激活表单,激活成功自动进系统。""" global _PAGE if _PAGE is None: _PAGE = (""" 软件授权
造价审核 · 软件授权正在连接授权状态…
加载中…
本页面由本机服务(127.0.0.1)提供;激活凭据只保存在本机,不会上传到别处。 激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。
""") return _PAGE