feat(license): 支持授权文件导入并固定生产公钥指纹校验

This commit is contained in:
lianjianwei2024
2026-10-12 17:23:40 +08:00
parent fb1875e8b2
commit 7fb7969a2f
9 changed files with 498 additions and 12 deletions

View File

@@ -19,7 +19,7 @@ import time
from .client import LicenseClient, DEFAULT_API_BASE
from .store import JsonFileStore, DpapiSecretStore, StorageError
from .verify import VerifyError, load_keyring_file, build_keyring
from .verify import VerifyError, load_keyring_file, build_keyring, UUID_RE
try: # 构建时生成(仅交付版有)
from . import license_build_config as BUILD
@@ -238,10 +238,103 @@ def _license_api(method, path, body):
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
@@ -281,6 +374,10 @@ button:disabled{opacity:.5;cursor:default}
.msg.err{display:block;background:#fdf0f0;color:#b02a2a;border:1px solid #f3c8c8}
.msg.ok{display:block;background:#effaf3;color:#1c7c44;border:1px solid #c4e8d0}
.tip{margin-top:16px;font-size:12px;color:#8a97a5;line-height:1.7}
.imp{margin-top:14px;font-size:13px}
.imp label{color:#1f4e79;text-decoration:underline;cursor:pointer}
.imp input{display:none}
#impPv button{flex:none;padding:7px 18px;margin-top:8px;font-size:13px}
</style></head><body><div class="card">
<div class="hd">造价审核 · 软件授权<small id="sub">正在连接授权状态…</small></div>
<div class="bd">
@@ -293,6 +390,9 @@ button:disabled{opacity:.5;cursor:default}
<input id="sec" type="password" placeholder="交付单上提供的一次性 secret"></div>
<div class="btns"><button id="go" onclick="doAct()">激活</button>
<button class="ghost" onclick="load()">刷新状态</button></div>
<div class="imp"><label for="impFile">或导入授权文件(.license.json,由软件提供方交付)— 点击选择</label>
<input type="file" id="impFile" accept=".json,application/json" onchange="impPick(this)"></div>
<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>
@@ -342,6 +442,37 @@ function doAct(){
document.getElementById("st").innerHTML=fmtSt(d);
}).catch(function(){btn.disabled=false;
m.className="msg err";m.textContent="网络错误:无法连接本机服务。";});}
function impErr(m){var p=document.getElementById("impPv");p.style.display="";
p.innerHTML="<b>"+esc(m)+"</b>";}
function impPick(inp){var f=inp.files&&inp.files[0];if(!f)return;
if(f.size>16384)return impErr("文件超过 16KiB,不是有效授权文件。");
var r=new FileReader();
r.onload=function(){try{impPreview(JSON.parse(r.value))}catch(e){impErr("文件不是有效 JSON。")}};
r.readAsText(f,"utf-8");
inp.value="";}
function impPreview(o){
if(!o||typeof o!="object"||Array.isArray(o)||o.format!="yhy-license-activation"||
o.version!=1||!o.instance_id||!o.license_key||!o.secret||!o.api_base_url)
return impErr("格式不符:需要 yhy-license-activation v1 授权文件。");
window._imp=o;
fetch("/api/license/status").then(function(r){return r.json()}).then(function(j){
var d=j.data||{},p=document.getElementById("impPv");
var warn=(d.instance_id&&String(d.instance_id).toLowerCase()!=String(o.instance_id).toLowerCase())
?"<b>⚠ 本机已配置其他实例,导入将更换凭据(历史时间记录保留)。</b><br>":"";
p.style.display="";
p.innerHTML=warn+"实例:"+esc(o.instance_id)+"<br>授权中心:"+esc(o.api_base_url)+
"<br><button onclick='impGo()'>确认导入并激活</button>";});}
function impGo(){
var m=document.getElementById("msg");m.className="msg";m.style.display="none";
fetch("/api/license/import",{method:"POST",headers:{"Content-Type":"application/json"},
body:JSON.stringify({file:window._imp,replace_confirmed:true})})
.then(function(r){return r.json()}).then(function(j){
var res=((j.data||{}).result||{});
if(j.ok){m.className="msg ok";m.textContent="导入激活成功,正在进入系统…";
document.getElementById("impPv").style.display="none";setTimeout(load,600);return;}
impErr(res.message||"导入失败,请核对授权文件。");
document.getElementById("st").innerHTML=fmtSt(j.data||{});})
.catch(function(){impErr("网络错误:无法连接本机服务。")});}
load();
</script></body></html>""")
return _PAGE

View File

@@ -1,10 +1,19 @@
{
"_说明": [
"可信公钥清单(信任根):只随软件/受控部署渠道固定分发,绝不在线发现。",
"上线前由运维(部署环境)交付生产 key_id + 公钥 PEM(SubjectPublicKeyInfo),",
"按 {\"key_id\":..., \"public_key_pem\":\"-----BEGIN PUBLIC KEY-----...\", \"revoked\":false} 追加进 pinned_keys。",
"2026-10-12 经接入包(license-platform-python-service-integration (2).md)交付生产公钥:",
"key_id=prod-22056bfacc8fe8a2,SPKI SHA-256 已本地实算比对一致后录入(防拷贝损坏自校验)。",
"交付版构建时烧进 license_build_config.py,本文件在交付环境不参与;开发环境直接读本文件。",
"轮换时由运维经受控渠道交付新公钥,按 {\"key_id\":..., \"public_key_pem\":..., \"spki_sha256\":..., \"revoked\":false} 追加。",
"接入包 test-vectors.json 里的 integration-test-only 测试公钥绝不能加进生产配置。",
"清空 = fail closed:激活/心跳验签一律失败。"
],
"pinned_keys": []
"pinned_keys": [
{
"key_id": "prod-22056bfacc8fe8a2",
"public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESr8/VFFwt70o7fwa8HiRNyxWtZEu\nUqzCBfYRG72DazEgeOaSVAdlTv49OujtggXSJzFLOluMENJzaRmp9+iJ0Q==\n-----END PUBLIC KEY-----",
"spki_sha256": "22056bfacc8fe8a240dd2125b629e60ba9f4a5ea0041a1efe034f376a258d562",
"revoked": false
}
]
}

View File

@@ -74,9 +74,11 @@ def rfc3339(dt):
# ------------------------------------------------------------- keyring 管理
def build_keyring(entries):
"""[{key_id, public_key_pem, revoked}] → {key_id: {"key": pub, "revoked": bool}}。
"""[{key_id, public_key_pem, revoked, spki_sha256?}] → {key_id: {"key": pub, "revoked": bool}}。
pinned 文件本身配置错(非 P-256 / 解不开)要立刻暴露,不能静默当不可信。
pinned 文件本身配置错(非 P-256 / 解不开 / 指纹不符)要立刻暴露,不能静默当不可信。
spki_sha256(受控交付时随公钥附来的 SPKI DER SHA-256 十六进制)选填:
给了就实算比对,防 PEM 在拷贝/转存中被损坏(yhy-license-trust v1 口径)。
"""
ring = {}
for e in entries or []:
@@ -86,6 +88,14 @@ def build_keyring(entries):
key = serialization.load_pem_public_key(pem.encode("utf-8"))
if not isinstance(key, ec.EllipticCurvePublicKey) or not isinstance(key.curve, ec.SECP256R1):
raise VerifyError("key_id=%s 的公钥不是 EC P-256" % kid)
want = e.get("spki_sha256")
if want:
der = key.public_bytes(serialization.Encoding.DER,
serialization.PublicFormat.SubjectPublicKeyInfo)
got = hashlib.sha256(der).hexdigest()
if got != str(want).strip().lower():
raise VerifyError("key_id=%s 公钥指纹不符(spki_sha256 与 PEM 不匹配,"
"疑似拷贝损坏或调包)" % kid)
ring[kid] = {"key": key, "revoked": bool(e.get("revoked", False))}
return ring

View File

@@ -0,0 +1,189 @@
# -*- coding: utf-8 -*-
"""决策 43:生产公钥落库(spki_sha256 自校验防拷贝损坏)+ .license.json 授权文件导入。
协议红线回归:字段集精确匹配、HTTPS 根地址+允许列表、换实例须显式确认、
导入≠激活(仍走在线激活+公钥验签)、错误话术不回显文件内容。
"""
import hashlib
import json
import os
import pytest
from cryptography.hazmat.primitives import serialization
import license_client.gate as gate
from license_client.verify import VerifyError, build_keyring
from lic_helpers import IID, IID2, cert_payload, envelope, make_client # noqa: F401
_HERE = os.path.dirname(os.path.abspath(__file__))
PINNED = os.path.join(os.path.dirname(_HERE), "server", "license_client",
"pinned_keys.json")
# ---------------------------------------------------------------- spki 指纹
def _pem(priv_key):
return priv_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo).decode("ascii")
def _spki(priv_key):
der = priv_key.public_key().public_bytes(
serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
return hashlib.sha256(der).hexdigest()
def test_keyring_spki_match_ok(priv_key):
ring = build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key),
"spki_sha256": _spki(priv_key), "revoked": False}])
assert "k1" in ring and not ring["k1"]["revoked"]
def test_keyring_spki_case_space_tolerant(priv_key):
ring = build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key),
"spki_sha256": " " + _spki(priv_key).upper() + " "}])
assert "k1" in ring
def test_keyring_spki_mismatch_rejected(priv_key):
with pytest.raises(VerifyError, match="指纹不符"):
build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key),
"spki_sha256": "0" * 64}])
def test_keyring_without_spki_still_ok(priv_key):
"""旧格式(无指纹)向后兼容。"""
assert build_keyring([{"key_id": "k1", "public_key_pem": _pem(priv_key)}])
def test_repo_pinned_keys_prod_key_self_consistent():
"""仓库信任根:生产公钥可解析、指纹与 PEM 自洽(拷贝损坏在这里炸)。"""
with open(PINNED, encoding="utf-8") as f:
keys = json.load(f).get("pinned_keys")
assert keys and keys[0]["key_id"] == "prod-22056bfacc8fe8a2"
ring = build_keyring(keys)
assert ring["prod-22056bfacc8fe8a2"]["revoked"] is False
# ---------------------------------------------------------------- 导入校验
GOOD = {"format": "yhy-license-activation", "version": 1,
"api_base_url": "https://license.yihuiyong.cn",
"instance_id": IID2, "license_key": "LK-1", "secret": "SEC-1"}
@pytest.fixture
def gate_env(monkeypatch, tmp_path, keyring):
assert gate.BUILD is None # 开发库无烧根文件,导入才允许回环 HTTP
c = make_client(tmp_path, keyring) # 已配置 IID
monkeypatch.setattr(gate, "_client", c)
monkeypatch.setattr(gate, "_cfg", {"enforce": True,
"api_base": "https://license.yihuiyong.cn"})
return c
def _resp(r):
assert r["kind"] == "json" and r["code"] == 200
return r["obj"]
def test_import_validate_matrix(gate_env):
from license_client.gate import _import_validate
bad = [
None, # 非对象
{}, # 空对象=缺字段
{**GOOD, "extra": 1}, # 多字段
{k: v for k, v in GOOD.items() if k != "secret"}, # 缺字段
{**GOOD, "format": "yhy-license-activation2"},
{**GOOD, "version": "1"},
{**GOOD, "version": True},
{**GOOD, "instance_id": "not-a-uuid"},
{**GOOD, "secret": "a\r\nb"},
{**GOOD, "license_key": ""},
{**GOOD, "secret": 123},
{**GOOD, "api_base_url": "http://license.yihuiyong.cn"}, # 非回环 http
{**GOOD, "api_base_url": "https://evil.example.com"}, # 不在允许列表
{**GOOD, "api_base_url": "https://license.yihuiyong.cn/api/v1"}, # 带路径
{**GOOD, "api_base_url": "https://u:p@license.yihuiyong.cn"}, # 账号信息
{**GOOD, "api_base_url": "https://license.yihuiyong.cn/?x=1"}, # 查询串
{**GOOD, "api_base_url": "ftp://license.yihuiyong.cn"},
]
for b in bad:
r = _import_validate(b)
assert r["ok"] is False and r["code"] == "IMPORT_INVALID", b
assert _import_validate(GOOD)["ok"] is True
def test_import_error_never_echoes_content(gate_env):
"""错误话术不得包含文件内容/secret(协议红线)。"""
from license_client.gate import _import_validate
leaky = {**GOOD, "secret": "SUPER-SECRET-VALUE", "instance_id": "nope"}
for _ in range(1):
r = _import_validate(leaky)
assert r["ok"] is False
assert "SUPER-SECRET-VALUE" not in r["message"]
assert "nope" not in r["message"]
def test_import_loopback_http_dev_only(monkeypatch):
monkeypatch.setattr(gate, "_cfg", {"enforce": True,
"api_base": "http://127.0.0.1:8398"})
ok = gate._import_validate({**GOOD, "instance_id": IID,
"api_base_url": "http://127.0.0.1:8398"})
assert ok["ok"] is True
bad = gate._import_validate({**GOOD, "api_base_url": "http://192.168.1.5:8398"})
assert bad["ok"] is False
def test_import_happy_path(priv_key, gate_env):
c = gate_env
c._tp.script.append((200, {}, {"data": {"instance_id": IID2, "status": "activated",
"certificate": envelope(
cert_payload(iid=IID2), priv_key, "cert")}}))
r = _resp(gate._license_import({"file": GOOD, "replace_confirmed": True}))
assert r["ok"] is True and r["data"]["result"]["ok"] is True
st = c.state_store.load()
assert st["instance_id"] == IID2 and st["status"] == "activated"
# 激活请求必须打到文件声明的实例,且带 Idempotency-Key
call = c._tp.calls[-1]
assert IID2 in call["url"] and call["headers"].get("Idempotency-Key")
def test_import_conflict_needs_explicit_confirm(gate_env):
c = gate_env
r = _resp(gate._license_import({"file": GOOD}))
assert r["ok"] is False
assert r["data"]["result"]["code"] == "INSTANCE_CONFLICT"
assert c.state_store.load()["instance_id"] == IID # 未被动过
# 显式确认后放行(脚本无响应 → 激活 TRANSIENT,但凭据已换写)
r2 = _resp(gate._license_import({"file": GOOD, "replace_confirmed": True}))
assert r2["data"]["result"]["code"] == "TRANSIENT"
assert c.state_store.load()["instance_id"] == IID2
def test_import_same_instance_no_confirm_needed(priv_key, gate_env):
c = gate_env
same = {**GOOD, "instance_id": IID}
c._tp.script.append((200, {}, {"data": {"instance_id": IID, "status": "activated",
"certificate": envelope(
cert_payload(iid=IID), priv_key, "cert")}}))
r = _resp(gate._license_import({"file": same}))
assert r["ok"] is True
def test_import_high_water_preserved(priv_key, gate_env):
"""换实例导入不清高水位(协议:切换身份保留时间记录)。"""
c = gate_env
st = c.state_store.load()
st["local_high_water"] = "2026-10-01T00:00:00Z"
st["server_high_water"] = "2026-10-01T00:00:00Z"
c.state_store.update(lambda s: s.update({"local_high_water": st["local_high_water"],
"server_high_water": st["server_high_water"]}))
c._tp.script.append((200, {}, {"data": {"instance_id": IID2, "status": "activated",
"certificate": envelope(
cert_payload(iid=IID2), priv_key, "cert")}}))
_resp(gate._license_import({"file": GOOD, "replace_confirmed": True}))
st2 = c.state_store.load()
assert st2["local_high_water"] == "2026-10-01T00:00:00Z"
assert st2["server_high_water"] == "2026-10-01T00:00:00Z"

View File

@@ -475,7 +475,7 @@ a:hover{text-decoration:underline}
</div>
</div>
<script src="common.js?v=20261011f"></script>
<script src="common.js?v=20261012a"></script>
<script src="period.js"></script>
<script>
const $=id=>document.getElementById(id);

View File

@@ -2001,7 +2001,8 @@ function licDlg() {
'<div id="licSt" class="lic-st">加载中…</div>' +
'<div class="lic-btns">' +
'<button class="btn" id="licRf" onclick="licRefresh()">立即刷新授权(联网续租)</button>' +
'<button class="btn" id="licFb" onclick="licToggleForm()">重新激活 / 更换凭据</button></div>' +
'<button class="btn" id="licFb" onclick="licToggleForm()">重新激活 / 更换凭据</button>' +
'<button class="btn" id="licImpB" onclick="licImpToggle()">导入授权文件(.license.json)</button></div>' +
'<div id="licForm" style="display:none">' +
'<div class="lic-row"><label>实例 ID(instance_id)</label>' +
'<input id="licIid" spellcheck="false" placeholder="形如 11111111-2222-…"></div>' +
@@ -2011,6 +2012,11 @@ function licDlg() {
'<input id="licSec" type="password"></div>' +
'<div class="lic-btns"><button class="btn pri" id="licGo" onclick="licActivate()">激活</button></div>' +
'</div>' +
'<div id="licImp" style="display:none">' +
'<div class="lic-row"><label>选择软件提供方交付的授权文件(≤16KiB,导入后仍需在线激活)</label>' +
'<input type="file" id="licImpFile" accept=".json,application/json" onchange="licImpPick(this)"></div>' +
'<div id="licImpPv" class="lic-st" style="display:none"></div>' +
'</div>' +
'<div class="lic-tip">续费由软件提供方在授权平台操作,在线状态下一分钟内自动生效,无需重装;' +
'「立即刷新授权」可手动联网续租。激活密钥只保存在本机(Windows 加密存储),不会上传到别处。</div>' +
'</div></div>';
@@ -2021,6 +2027,10 @@ function licDlg() {
mask.classList.add('on');
const f = document.getElementById('licForm'); // 重开时表单复位收起(上轮未关的残留)
if (f) f.style.display = 'none';
const im = document.getElementById('licImp'); // 导入区同样复位
if (im) im.style.display = 'none';
const ipv = document.getElementById('licImpPv');
if (ipv) { ipv.style.display = 'none'; ipv.innerHTML = ''; }
licLoad();
clearInterval(_licPoll);
_licPoll = setInterval(licLoad, 15000);
@@ -2074,6 +2084,58 @@ function licToggleForm() {
const f = document.getElementById('licForm');
f.style.display = f.style.display === 'none' ? '' : 'none';
}
function licImpToggle() {
const d = document.getElementById('licImp');
d.style.display = d.style.display === 'none' ? '' : 'none';
}
function licImpErr(m) {
const p = document.getElementById('licImpPv');
p.style.display = '';
p.innerHTML = '<b class="bad">' + esc(m) + '</b>';
}
function licImpPick(inp) {
const file = inp.files && inp.files[0];
if (!file) return;
if (file.size > 16384) { licImpErr('文件超过 16KiB,不是有效授权文件。'); return; }
const r = new FileReader();
r.onload = () => { try { licImpPreview(JSON.parse(r.value)); }
catch (e) { licImpErr('文件不是有效 JSON。'); } };
r.readAsText(file, 'utf-8');
inp.value = '';
}
function licImpPreview(o) {
if (!o || typeof o !== 'object' || Array.isArray(o) ||
o.format !== 'yhy-license-activation' || o.version !== 1 ||
!o.instance_id || !o.license_key || !o.secret || !o.api_base_url) {
licImpErr('格式不符:需要 yhy-license-activation v1 授权文件。'); return;
}
window._licImpFile = o;
fetch('/api/license/status').then(r => r.json()).then(j => {
const d = j.data || {}, p = document.getElementById('licImpPv');
const warn = (d.instance_id && String(d.instance_id).toLowerCase() !== String(o.instance_id).toLowerCase())
? '<b class="bad">⚠ 本机已配置其他实例,导入将更换凭据(历史时间记录保留)。</b><br>' : '';
p.style.display = '';
p.innerHTML = warn + '实例:' + esc(o.instance_id) + '<br>授权中心:' + esc(o.api_base_url) +
'<div class="lic-btns" style="margin-bottom:0"><button class="btn pri" onclick="licImpGo()">确认导入并激活</button></div>';
}).catch(() => licImpErr('无法读取授权状态(本机服务异常?)'));
}
function licImpGo() {
fetch('/api/license/import', { method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file: window._licImpFile, replace_confirmed: true }) })
.then(r => r.json()).then(j => {
const res = ((j.data || {}).result) || {};
if (j.ok) {
const p = document.getElementById('licImpPv');
p.style.display = 'none'; p.innerHTML = '';
document.getElementById('licImp').style.display = 'none';
toast('导入激活成功', '');
} else {
licImpErr(res.message || '导入失败,请核对授权文件。');
}
licLoad();
}).catch(() => licImpErr('网络错误:无法连接本机服务'));
}
function licActivate() {
const b = { instance_id: document.getElementById('licIid').value.trim(),
license_key: document.getElementById('licLk').value.trim(),

View File

@@ -464,7 +464,7 @@ body.grptree-dragging{cursor:col-resize !important;user-select:none}
</div>
</div>
<script src="common.js?v=20261011f"></script>
<script src="common.js?v=20261012a"></script>
<script src="period.js"></script>
<script>
let SID=0, CUR=null, CURTYPE='lme', HROWS=[];
@@ -1424,6 +1424,26 @@ function setStop(){
if(kwActive()) return;
clearTimeout(_stopT); _stopT=setTimeout(search, 250);
}
/* 筛选栏输入框右缘小叉(2026-10-12 主人定):有值才显示,点一下清空并触发该框自己的联动;
视觉复用 comboFree 的 .combo/.combo-x(common.css 统一样式)。仅历史对比筛选栏用。 */
function filterInputX(inp, onClear){
if (inp._fx) return;
const wrap = document.createElement('span');
wrap.className = 'combo'; wrap.dataset.for = inp.id || '';
inp.parentNode.insertBefore(wrap, inp);
wrap.append(inp);
wrap.style.width = getComputedStyle(inp).width; // 包裹层占位原宽(工具条上的固定宽框)
inp.style.width = '100%';
const clr = document.createElement('span');
clr.className = 'combo-x'; clr.textContent = '×'; clr.title = '清空';
clr.style.display = 'none';
wrap.append(clr);
const sync = () => { clr.style.display = inp.value ? 'block' : 'none'; };
inp.addEventListener('input', sync);
clr.onclick = () => { inp.value = ''; sync(); onClear(); inp.focus(); };
inp._fx = true;
sync();
}
/* 分页(2026-10-08 主人定):检索每次 500 条,下一页=再取后 500;上一页/下一页在工具条最右,
仅检索模式显示。HPAGE 跨页保持,重新「查询」/清空关键词/重置都回第 1 页。 */
let HPAGE=1;
@@ -1474,6 +1494,11 @@ comboFree($('funit'), ()=> (curTab()==='p0' ? window.__ORG_OPTS : window.__BU_OP
$('funit').style.padding='3px 22px 3px 8px'; // 工具条控件更矮(盖掉 comboFree 默认内边距)
$('fpmin').addEventListener('input', setPrc); // 价格范围:输入即查(防抖在 setPrc)
$('fpmax').addEventListener('input', setPrc);
// 筛选栏输入框右缘小叉(2026-10-12 主人定):搜索/屏蔽词/价格范围四框;单位框 comboFree 自带
filterInputX($('hkw'), () => setKw($('hkw').value));
filterInputX($('fstop'), () => setStop());
filterInputX($('fpmin'), () => setPrc());
filterInputX($('fpmax'), () => setPrc());
$('hatt').addEventListener('change', setAtt); // 附件 全部/有/无
mkPeriod($('hperBtn'), ()=>{ updPerBtn(); if(!kwActive()) search(); }); // 期次:选完更新按钮文案;无关键字即查
mkPeriod($('oper')); // 打开工程:基准期次(起~止,同月填一样)

View File

@@ -28,7 +28,26 @@ APP = ROOT / "CostReview" / "app"
# 与开发环境同大版本的 embeddable 包(多备几个补丁号,第一个能下载的胜出)
EMBED_VERSIONS = ["3.13.9", "3.13.11", "3.13.12", "3.13.14", "3.13.5", "3.13.2"]
DEPS = ["pywebview==6.2.1", "openpyxl==3.1.5", "xlrd==2.0.1"]
def _deps_from_requirements():
"""包内依赖唯一来源 = 仓库根 requirements.txt(决策 43)。
曾因这里另维护一份硬编码清单漏掉 cryptography/httpx,导致交付包顶层 import
api_server 即崩(授权门禁依赖 cryptography)。单源化后 requirements.txt 缺失
或为空直接构建失败,宁可不出包也不出残包。
"""
req = ROOT / "requirements.txt"
if not req.is_file():
raise RuntimeError("找不到 %s——包内依赖清单只有这一份来源" % req)
deps = [ln.strip() for ln in req.read_text(encoding="utf-8").splitlines()
if ln.strip() and not ln.strip().startswith("#")]
if not deps:
raise RuntimeError("requirements.txt 为空,拒绝构建")
return deps
DEPS = _deps_from_requirements()
BAT_GUI = (
"@echo off\r\n"
@@ -133,8 +152,7 @@ def write_license_build_config(app_target):
"ENFORCE = True\n"
"PRODUCT_ID = %r\n"
"SELFHEAL_SECONDS = 300\n"
"PINNED_KEYS = %s\n" % (RELEASE_API_BASE, RELEASE_PRODUCT_ID,
json.dumps(keys, ensure_ascii=False, indent=4)),
"PINNED_KEYS = %r\n" % (RELEASE_API_BASE, RELEASE_PRODUCT_ID, keys),
encoding="utf-8")
log("授权信任根已烧入 → server/license_client/license_build_config.py(公钥 %d 把)" % len(keys))

View File

@@ -1351,3 +1351,45 @@ common.css 不动):后端 hist_search/hist_search_lme 的严格档 CASE 同
- 删除路径四方对齐:升级重写表组/删批次级联/清 mock 分块删除都加 lme_uw(wipe 动态发现 s_ 表自动覆盖 s_lme_uw)。
**实测**:82 项 pytest 全绿(新增 test_lme_uw_card.py:summary 优先/agg 回退);横琴源文件只读解析探针:lme_uw **2073 行**=s_lmes 全量、20 个单位工程归属分布正确;浏览器:项目级卡「总数量」✓、单位工程级卡(已重解析)「总数量」+本单位工程数字(履带式推土机台班 10.687 vs 项目级 40.317,人工费 230.5 万 vs 534.4 万——**数字确实换了**)✓。老会话/老批次在重新解析/升级前保持归集口径(不错、只是旧算法)。
## 决策 42(2026-10-12):历史对比筛选栏输入框右缘加小叉清除按钮
**主人指令**:类似清单/项目工料机的历史对比框筛选栏,所有输入框右边增加贴边线的小叉清除按钮。
**实现**:workbench.html 新增 `filterInputX(inp, onClear)` helper——复用 comboFree 的 `.combo`/`.combo-x` 视觉(common.css 统一样式:有值才显示、×、悬停变色);包裹层占原宽(wrap.style.width=计算宽,input 100%),点击清空+触发该框自己的联动(搜索框 setKw→查询按钮置灰/清空即回比对、屏蔽词 setStop→比对方式即重查、价格范围 setPrc→防抖重查)。「单位」框 comboFree 自带小叉,不动。
**范围**:#hkw 搜索、#fstop 屏蔽词、#fpmin/#fpmax 价格范围,共四框(两个标签共用同一筛选栏,一处生效两侧)。
**实测**(8366+IAB):有值四框叉全显示(display=block)、空框隐藏;点搜索框叉→框清+FLT.kw 清+查询按钮置灰;点屏蔽词叉→FLT.stop 清+重查;价格范围双叉→FLT 值清;叉贴框内右缘(xRight 1044 ≤ inpRight 1051)、框宽 200 不变、工具条无横向溢出(68px 高=flex-wrap 正常换行)。IAB screenshot 超时(渲染冻结怪癖)→ 改 DOM 断言完成视觉要素验证。
## 决策 43(2026-10-12):生产公钥落库 + 授权文件导入(.license.json)+ 出包链路两断点修复
**背景**:主人交付新版接入包 `license-platform-python-service-integration (2).md`(较旧版增量:①生产公钥交付;②`.license.json` 凭据导入 / `yhy-license-trust v1` 信任导入两种文件化交付格式;③upgrade.md 升级方案)。经对账评估:协议核心决策 30/31 已全覆盖且被新文档反向验证;主人拍板"按附件做"。**不做**:trust v1 运行时导入(烧根更强,轮换=重新出包)、升级下载器(平台第二阶段未实现+64MiB 上限待量体积),维持决策 31 暂缓口径。
### ① 生产公钥落库(决策 30 遗留待办 1 闭环)
- `pinned_keys.json` 录入 `prod-22056bfacc8fe8a2`(接入包交付);**本地实算** SHA-256(SPKI DER) 与文档指纹及 key_id 前缀三方自洽后才落库。
- `verify.build_keyring` 新增 `spki_sha256` 选填自校验:给了指纹就实算比对,不符=配置错立即暴露(防 PEM 拷贝损坏/调包);大小写容差、旧格式(无指纹)兼容。指纹算法同 yhy-license-trust v1 口径。
### ② 授权文件导入(POST /api/license/import)
- 协议口径:文件未签名、**导入≠激活**——严格校验后写入受保护存储,仍走在线激活+公钥验签。
- 后端 `gate._import_validate`:字段集精确匹配(format=yhy-license-activation / version=1 / 三凭据 / api_base_url,缺一多一都拒);凭据字段长度≤512+拒 CR/LF/NUL;instance_id UUID;api_base_url 只允许 HTTPS 根地址(无路径/查询/账号信息/端口合法性),**回环 HTTP 仅限开发版**(BUILD 存在即一律 HTTPS);且必须命中预置允许地址(=烧根/config 的 api_base,防 secret 发往任意地址)。**错误话术全固定串,不回显文件内容**。
- 换实例防呆:本机已配置其他实例时,不带 `replace_confirmed:true` 拒绝(INSTANCE_CONFLICT);高水位永不清理(configure 本就不动)。前端预览卡展示实例+授权中心+换实例红字警示,**两段式确认(不用原生 confirm)**。
- 入口两处:授权页(gate_page 内嵌 file input+预览+确认按钮)、设置窗(licDlg「导入授权文件」折叠区);前端 16KiB 文件上限+格式预检,后端重校验(不信任客户端)。
### ③ 出包链路两断点(构建冒烟当场抓住,台账记载与实物曾不符)
- **DEPS 缺依赖(P0)**:`build_portable.py` 自维护硬编码清单漏 cryptography/httpx(决策 30 台账称"装进包内"但从未落地 git),交付包顶层 import api_server 即崩。改**单源读仓库根 requirements.txt**,缺失/为空拒绝构建。
- **烧根 json→py 字面量**:`write_license_build_config` 用 json.dumps 写 PINNED_KEYS,公钥条目含 `false` 非 Python 字面量(清单为空时代未暴露)。改 `%r`。
### 测试与验收
- pytest 新增 `test_license_import.py` 12 项(指纹三态/仓库信任根自洽/导入校验 17 反例矩阵/错误不回显/回环仅开发版/happy path 打对实例+幂等键/换实例冲突与显式确认/同实例免确认/高水位保留),**全量 94 项绿**。
- 真包构建(决策 43 修复后):冒烟 `SMOKE-SERVER-OK enforce=True locked=True keyring=True` 全过(结果见当日会话记录)。
- common.js 版本 20261012a(两页同步)。
### 待主人
- `RELEASE_PRODUCT_ID` 仍 None(=不校验产品线);要绑定就填平台产品 ID 再出包。
- 平台建**测试**客户/授权/实例做真机全链路演练(激活→心跳→续费→冻结恢复→导入文件激活)——本机冒烟只验门禁行为,未打真平台(纪律:勿用正式客户授权演练)。