# -*- 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, 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:门禁自愈触发节流 # ---------------------------------------------------------------- 初始化 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 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 _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}} if method == "POST" and path == "/api/license/import": return _license_import(body) return {"kind": "json", "code": 404, "obj": {"error": {"code": "NOT_FOUND", "message": "未知授权接口"}}} # ------------------------------------------------- 授权文件导入(.license.json) # # 协议口径(接入包「授权文件导入(交付格式 v1)」):文件未签名、不是离线授权, # 只是一份凭据载体——导入=严格校验后写入受保护存储,仍必须走在线激活+验签。 # 红线:拒绝未知版本/额外字段;api_base_url 只允许 HTTPS 根地址且必须命中预置 # 允许地址;不得覆盖已有不同实例身份(须显式确认);导入错误不得回显文件内容。 IMPORT_FIELDS = {"format", "version", "api_base_url", "instance_id", "license_key", "secret"} def _import_invalid(msg): """固定话术,绝不回显文件内容/secret。""" return {"ok": False, "code": "IMPORT_INVALID", "message": msg} def _import_check_url(url): """HTTPS 根地址校验 → (规范化地址, None) | (None, 错误话术)。""" if not isinstance(url, str) or not url or len(url) > 2048: return None, "授权文件 api_base_url 非法" try: from urllib.parse import urlsplit u = urlsplit(url) port = u.port # 非法端口在这里抛 ValueError except ValueError: return None, "授权文件 api_base_url 非法" if u.scheme == "http": # 本机回环 HTTP 仅限开发版(交付版烧根,一律 HTTPS) if BUILD is not None or u.hostname not in ("127.0.0.1", "localhost", "::1"): return None, "授权文件 api_base_url 必须 HTTPS" elif u.scheme != "https": return None, "授权文件 api_base_url 必须 HTTPS" if (u.username or u.password or u.query or u.fragment or not u.hostname or u.path not in ("", "/")): return None, "授权文件 api_base_url 只允许根地址(不得带路径/参数/账号信息)" return url.rstrip("/"), None def _import_validate(f): if not isinstance(f, dict) or set(f.keys()) != IMPORT_FIELDS: return _import_invalid("授权文件格式不符(应为 yhy-license-activation v1," "字段缺/多不予接受)") if f.get("format") != "yhy-license-activation": return _import_invalid("授权文件 format 不符(需要 yhy-license-activation)") v = f.get("version") if isinstance(v, bool) or not isinstance(v, int) or v != 1: return _import_invalid("授权文件版本不支持(只接受 version=1)") iid, lk, sec = f.get("instance_id"), f.get("license_key"), f.get("secret") for name, val in (("instance_id", iid), ("license_key", lk), ("secret", sec)): if not isinstance(val, str) or not val or len(val) > 512: return _import_invalid("授权文件 %s 字段非法" % name) if any(ch in val for ch in ("\r", "\n", "\x00")): return _import_invalid("授权文件 %s 字段含非法字符" % name) if not UUID_RE.match(iid): return _import_invalid("授权文件 instance_id 不是 UUID") url, err = _import_check_url(f.get("api_base_url")) if err: return _import_invalid(err) allowed = str(_cfg.get("api_base") or "").rstrip("/") if url.lower() != allowed.lower(): return _import_invalid("授权文件指向的授权中心不在本软件预置允许列表" "(固定为 %s)" % allowed) return {"ok": True, "instance_id": iid, "license_key": lk, "secret": sec} def _license_import(body): b = body if isinstance(body, dict) else {} c = _client_for_request() if c is None: return _blocked("授权子系统未初始化") r = _import_validate(b.get("file")) if not r.get("ok"): return {"kind": "json", "code": 200, "obj": {"ok": False, "data": {"result": r}}} iid = r["instance_id"] cur = status_view().get("instance_id") if cur and cur.lower() != iid.lower() and not b.get("replace_confirmed"): return {"kind": "json", "code": 200, "obj": {"ok": False, "data": {"result": { "ok": False, "code": "INSTANCE_CONFLICT", "message": "本机已配置其他实例(%s…),更换凭据需界面显式确认" % cur[:8]}}}} try: c.configure(iid, r["license_key"], r["secret"]) act = c.activate() # 导入≠激活:仍走在线激活+公钥验签 except (StorageError, VerifyError) as e: act = {"ok": False, "code": "IMPORT_FAILED", "message": str(e)} if act.get("ok"): _restart_heartbeat() out = status_view() out["result"] = act return {"kind": "json", "code": 200, "obj": {"ok": bool(act.get("ok")), "data": out}} # ---------------------------------------------------------------- 授权页 _PAGE = None def gate_page(reason): """未授权时替代正常页面的自包含页面:状态 + 激活表单,激活成功自动进系统。""" global _PAGE if _PAGE is None: _PAGE = ("""