feat(license): 支持授权文件导入并固定生产公钥指纹校验
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user