feat: 落实决策216/219/227取价锚点与公式口径,增加商业版权益和源码完整性校验
This commit is contained in:
@@ -23,7 +23,7 @@ from datetime import timedelta
|
||||
|
||||
try:
|
||||
from .verify import (VerifyError, verify_certificate, verify_lease,
|
||||
parse_rfc3339, rfc3339)
|
||||
parse_rfc3339, rfc3339, entitlements)
|
||||
from .store import StorageError
|
||||
except ImportError as _e:
|
||||
# 只对"相对导入不可用"退裸导入;包内真实依赖缺失(如 cryptography)必须原样抛出,
|
||||
@@ -31,7 +31,7 @@ except ImportError as _e:
|
||||
if "attempted relative import" not in str(_e):
|
||||
raise
|
||||
from verify import (VerifyError, verify_certificate, verify_lease,
|
||||
parse_rfc3339, rfc3339)
|
||||
parse_rfc3339, rfc3339, entitlements)
|
||||
from store import StorageError
|
||||
|
||||
DEFAULT_API_BASE = "https://license.yihuiyong.cn"
|
||||
@@ -333,6 +333,7 @@ class LicenseClient:
|
||||
return out
|
||||
lease = st.get("lease") or {}
|
||||
cert = st.get("certificate") or {}
|
||||
ent = entitlements(cert) if cert else {"edition": None, "max_seats": None}
|
||||
ok, reason = self.can_run_safe()
|
||||
days_left = None
|
||||
try:
|
||||
@@ -348,6 +349,8 @@ class LicenseClient:
|
||||
"license_id": cert.get("license_id"),
|
||||
"product_id": cert.get("product_id"),
|
||||
"expected_product_id": self.expected_product_id,
|
||||
"edition": ent["edition"], # 商业版权益(未激活为 None;证书缺省=personal)
|
||||
"max_seats": ent["max_seats"],
|
||||
"days_left": days_left,
|
||||
"starts_at": cert.get("starts_at"),
|
||||
"entitlement_expires_at": cert.get("expires_at") or lease.get("entitlement_expires_at"),
|
||||
|
||||
@@ -12,6 +12,7 @@ pinned_keys.json + 已存授权状态;配置了凭据且信任根就绪则起
|
||||
本地开发豁免:data/license/config.json 写 "enforce": false(交付/发布环境
|
||||
不带该文件或 enforce=true,代码默认 true)。
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
@@ -32,6 +33,34 @@ _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
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 初始化
|
||||
@@ -73,6 +102,7 @@ def init(data_dir):
|
||||
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)}
|
||||
@@ -167,6 +197,12 @@ def heartbeat_running():
|
||||
|
||||
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 not _cfg.get("enforce", True):
|
||||
@@ -194,6 +230,23 @@ def can_run_now():
|
||||
return c.can_run_safe()
|
||||
|
||||
|
||||
def _integrity_page():
|
||||
"""N1 完整性拦截页(自包含):文件被改时的唯一可见页面。"""
|
||||
return """<!DOCTYPE html>
|
||||
<html lang="zh"><head><meta charset="utf-8"><title>软件文件校验失败</title>
|
||||
<style>body{font-family:"Microsoft YaHei",sans-serif;background:#f0f2f5;display:flex;
|
||||
align-items:center;justify-content:center;min-height:100vh;margin:0}
|
||||
.c{background:#fff;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,.08);
|
||||
max-width:520px;padding:32px 36px}h1{font-size:19px;color:#b02a2a;margin:0 0 12px}
|
||||
p{color:#33475b;line-height:1.8;font-size:14px;margin:8px 0}
|
||||
.k{color:#8a97a5;font-size:12px;margin-top:16px}</style></head><body><div class="c">
|
||||
<h1>⚠ 软件文件完整性校验失败</h1>
|
||||
<p>检测到程序文件被改动,为保障授权与数据安全,软件已停止服务。</p>
|
||||
<p>请重新安装官方软件包,或联系软件提供方处理。您的数据不受影响。</p>
|
||||
<div class="k">涉及文件见服务日志「完整性校验失败」行。</div>
|
||||
</div></body></html>"""
|
||||
|
||||
|
||||
def _blocked(reason):
|
||||
return {"kind": "json", "code": 403,
|
||||
"obj": {"error": {"code": "LICENSE_REQUIRED", "message": reason}}}
|
||||
@@ -406,7 +459,8 @@ button:disabled{opacity:.5;cursor:default}
|
||||
<div class="st" id="impPv" style="display:none;margin-top:12px;margin-bottom:0"></div>
|
||||
<div class="msg" id="msg"></div>
|
||||
<div class="tip">本页面由本机服务(127.0.0.1)提供;激活凭据只保存在本机,不会上传到别处。
|
||||
激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。</div>
|
||||
激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。
|
||||
授权到期或被冻结时会停在本页(到期即锁):联系软件提供方续费/解冻并重新激活即可恢复使用,本机数据不受任何影响。</div>
|
||||
</div></div>
|
||||
<script>
|
||||
var TIMER=null;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
- canonical_sha256 是规范化字节的 SHA-256 十六进制,仅辅助校验,不能代替公钥验签。
|
||||
- 拒绝:未知版本、缺字段/多字段、非法类型、含 CR/LF/NUL 的字段、未知或已撤销
|
||||
key_id、非 P-256 公钥、绑定到其他实例的信封、legacy v1。
|
||||
(证书例外:OPTIONAL_CERT_FIELDS 两个可选权益字段可缺省,见下方注释。)
|
||||
|
||||
信任根:只信随软件/受控渠道固定分发的公钥(pinned_keys.json),绝不在线发现。
|
||||
"""
|
||||
@@ -33,6 +34,20 @@ FIELDSETS = {
|
||||
LEASE_V2: ("version", "instance_id", "state", "server_time",
|
||||
"entitlement_expires_at", "lease_expires_at", "key_id"),
|
||||
}
|
||||
|
||||
# 商业版权益字段(2026-10-27,《企业和个人版.md》5.1):仅证书载荷**可选**携带;
|
||||
# 出现 → 纳入 canonical(按本元组顺序追加在必填之后)并校验取值;
|
||||
# 缺省 → edition=personal、max_seats=1(fail-closed 不放大权益;平台未升级协议仍能签发)。
|
||||
OPTIONAL_CERT_FIELDS = ("edition", "max_seats")
|
||||
EDITIONS = ("personal", "enterprise", "trial")
|
||||
|
||||
|
||||
def entitlements(cert):
|
||||
"""从证书载荷取商业版权益(规范化缺省)。门禁与状态视图共用唯一口径。"""
|
||||
if not isinstance(cert, dict):
|
||||
return {"edition": "personal", "max_seats": 1}
|
||||
return {"edition": cert.get("edition") or "personal",
|
||||
"max_seats": cert.get("max_seats") or 1}
|
||||
UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
||||
re.IGNORECASE)
|
||||
RFC3339_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
|
||||
@@ -145,6 +160,12 @@ def canonical_bytes(payload, version):
|
||||
if name not in payload:
|
||||
raise VerifyError("payload 缺字段 %s" % name)
|
||||
out.append("%s=%s" % (name, _field_value(payload, name)))
|
||||
if version == LICENSE_V2:
|
||||
# 可选权益字段:签发方带了才进 canonical(顺序固定);取值合法性由 _check_payload 管
|
||||
for name in OPTIONAL_CERT_FIELDS:
|
||||
if name in payload:
|
||||
v = payload[name]
|
||||
out.append("%s=%s" % (name, str(v) if isinstance(v, int) else v))
|
||||
return "\n".join(out).encode("utf-8")
|
||||
|
||||
|
||||
@@ -153,7 +174,20 @@ def canonical_bytes(payload, version):
|
||||
def _check_payload(payload, version, expected_instance):
|
||||
if not isinstance(payload, dict):
|
||||
raise VerifyError("payload 不是对象")
|
||||
if set(payload.keys()) != set(FIELDSETS[version]):
|
||||
keys = set(payload.keys())
|
||||
required = set(FIELDSETS[version])
|
||||
if version == LICENSE_V2:
|
||||
# 必填全在;多出的键只能是可选权益字段(edition/max_seats),其余多字段仍拒
|
||||
if (keys - required) - set(OPTIONAL_CERT_FIELDS) or required - keys:
|
||||
raise VerifyError("payload 字段集不符(缺/多字段)")
|
||||
ed = payload.get("edition")
|
||||
if ed is not None and (not isinstance(ed, str) or ed not in EDITIONS
|
||||
or any(c in ed for c in ("\r", "\n", "\x00"))):
|
||||
raise VerifyError("edition 取值非法")
|
||||
ms = payload.get("max_seats")
|
||||
if ms is not None and (isinstance(ms, bool) or not isinstance(ms, int) or ms < 1):
|
||||
raise VerifyError("max_seats 必须是正整数")
|
||||
elif keys != required:
|
||||
raise VerifyError("payload 字段集不符(缺/多字段)")
|
||||
if payload["version"] != version:
|
||||
raise VerifyError("payload.version=%r 不是 %s" % (payload["version"], version))
|
||||
|
||||
Reference in New Issue
Block a user