refactor(cost): 优化LME成员去重与措施清单标签还原,清理临时核查脚本
This commit is contained in:
9246
_analysis/定额单价专题/iab_env3/CostReview/app/server/api_server.py
Normal file
9246
_analysis/定额单价专题/iab_env3/CostReview/app/server/api_server.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""授权平台客户端(license-v2 / lease-v2)。
|
||||
|
||||
api_server 只 import license_client.gate 这一个入口:
|
||||
import license_client.gate as license_gate
|
||||
license_gate.init(DATA_DIR) # run() 启动时
|
||||
license_gate.intercept(method, path, body) # do_GET / do_POST 顶部
|
||||
业务侧判定用 client.can_run_safe()(门禁内部已用,业务代码一般不必再调)。
|
||||
"""
|
||||
from .client import LicenseClient, DEFAULT_API_BASE # noqa: F401
|
||||
@@ -0,0 +1,475 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""LicenseClient:激活 + 心跳租约 + 本地 can_run 状态机。
|
||||
|
||||
协议硬性口径(protocol.md / prompt.md):
|
||||
- 激活、心跳都必须带 Idempotency-Key;同一次操作的网络重试复用同一键与同一
|
||||
请求体(心跳复用原 client_time,不得改时间续用原键);新业务操作才换新键。
|
||||
→ 在途操作键先落盘再发请求,进程重启也能复用。
|
||||
- 403/409 等确定性拒绝:停止自动重试,转入人工处理(needs_attention)。
|
||||
- 429:至少等 Retry-After;超时/连接错误/5xx:有界退避,键与请求体不变。
|
||||
- 仅 active 且授权到期、租约到期都严格晚于 now 才允许业务;租约结束不得晚于
|
||||
授权结束、不得晚于 server_time + 14 天;本机与服务端时差 ≤ 5 分钟;
|
||||
本地/服务端两个时间高水位只进不退,落盘原子更新,失败即 fail closed。
|
||||
- secret 不进 URL、日志、异常文本。网络失败不得延长已接受的租约(can_run
|
||||
纯本地判定,心跳失败只会让租约自然到期)。
|
||||
|
||||
httpx 为可选依赖:只在真正发请求时导入;无网络库时 can_run/状态读取照常工作。
|
||||
"""
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
import uuid as uuid_mod
|
||||
from datetime import timedelta
|
||||
|
||||
try:
|
||||
from .verify import (VerifyError, verify_certificate, verify_lease,
|
||||
parse_rfc3339, rfc3339, entitlements)
|
||||
from .store import StorageError
|
||||
except ImportError as _e:
|
||||
# 只对"相对导入不可用"退裸导入;包内真实依赖缺失(如 cryptography)必须原样抛出,
|
||||
# 否则真实病因会被掩盖成 "No module named 'verify'" 指错排查方向(2026-10-11 实证踩坑)
|
||||
if "attempted relative import" not in str(_e):
|
||||
raise
|
||||
from verify import (VerifyError, verify_certificate, verify_lease,
|
||||
parse_rfc3339, rfc3339, entitlements)
|
||||
from store import StorageError
|
||||
|
||||
DEFAULT_API_BASE = "https://license.yihuiyong.cn"
|
||||
MIN_HEARTBEAT_SECONDS = 60 # 协议:成功 active 心跳最短间隔 60 秒
|
||||
MAX_LEASE_DAYS = 14 # 协议:租约最长 14 天
|
||||
MAX_CLOCK_SKEW = timedelta(minutes=5)
|
||||
|
||||
NEED_ATTENTION = ("HTTP_400", "HTTP_401", "HTTP_403", "HTTP_409")
|
||||
|
||||
|
||||
class TransientError(Exception):
|
||||
"""暂时性网络失败(重试额度用尽)。在途操作键保留,稍后可继续。"""
|
||||
|
||||
|
||||
class LeaseInvalid(VerifyError):
|
||||
"""租约通过验签但范围非法(租约窗/14 天上限)。"""
|
||||
|
||||
|
||||
class LicenseClient:
|
||||
def __init__(self, api_base, state_store, secret_store, keyring,
|
||||
now_fn=None, sleep_fn=time.sleep, transport=None,
|
||||
max_attempts=4, timeout=15,
|
||||
expected_product_id=None, cache_ttl=10.0, mono_fn=None):
|
||||
self.api_base = (api_base or DEFAULT_API_BASE).rstrip("/")
|
||||
self.state_store = state_store
|
||||
self.secret_store = secret_store
|
||||
self.keyring = keyring or {}
|
||||
self.expected_product_id = expected_product_id # None = 不校验产品线
|
||||
self.now_fn = now_fn or (lambda: __import__("datetime").datetime.now(
|
||||
__import__("datetime").timezone.utc))
|
||||
self.mono_fn = mono_fn or time.monotonic
|
||||
self.cache_ttl = cache_ttl # can_run 结果缓存(0=关)
|
||||
self.sleep_fn = sleep_fn
|
||||
self.max_attempts = max(1, max_attempts)
|
||||
self.timeout = timeout
|
||||
self._send_fn = transport or self._httpx_send
|
||||
self._http = None
|
||||
self._op_lock = threading.RLock() # 状态读改写串行(心跳线程 × 请求线程)
|
||||
self._hb_lock = threading.Lock() # 心跳整体串行(循环/自愈/手动 refresh 并发)
|
||||
self._cr_cache = None # (ok, reason, 过期时刻)——门禁每请求一调,省验签+写盘
|
||||
|
||||
# ------------------------------------------------------------ 凭据
|
||||
|
||||
def has_credentials(self):
|
||||
try:
|
||||
st = self.state_store.load()
|
||||
return bool(st.get("instance_id") and st.get("license_key")
|
||||
and self.secret_store.get())
|
||||
except StorageError:
|
||||
return False
|
||||
|
||||
def configure(self, instance_id, license_key, secret):
|
||||
"""写入交付凭据:secret → 受保护密钥库;其余 → 状态文件。先密钥库后状态。"""
|
||||
instance_id = (instance_id or "").strip()
|
||||
license_key = (license_key or "").strip()
|
||||
secret = (secret or "").strip()
|
||||
if not (instance_id and license_key and secret):
|
||||
raise VerifyError("instance_id / license_key / secret 都必填")
|
||||
self.secret_store.set(secret)
|
||||
def mut(st):
|
||||
st["instance_id"] = instance_id
|
||||
st["license_key"] = license_key
|
||||
st.setdefault("status", "unactivated")
|
||||
st["last_error"] = ""
|
||||
with self._op_lock:
|
||||
self.state_store.update(mut)
|
||||
|
||||
def _creds(self):
|
||||
st = self.state_store.load()
|
||||
iid = st.get("instance_id")
|
||||
lk = st.get("license_key")
|
||||
sec = self.secret_store.get() if iid else None
|
||||
if not (iid and lk and sec):
|
||||
raise VerifyError("缺少实例凭据(instance_id / license_key / secret)")
|
||||
return st, iid, lk, sec
|
||||
|
||||
# ------------------------------------------------------------ 激活
|
||||
|
||||
def activate(self):
|
||||
"""首次激活。返回 {"ok": bool, ...};网络暂时失败时幂等键已保留,重试复用。"""
|
||||
st, iid, lk, sec = self._creds()
|
||||
with self._op_lock:
|
||||
st = self.state_store.load()
|
||||
op = st.get("activation_op")
|
||||
if not op:
|
||||
op = {"key": str(uuid_mod.uuid4())}
|
||||
self.state_store.update(lambda s: s.update({"activation_op": op}))
|
||||
body = {"license_key": lk, "secret": sec}
|
||||
try:
|
||||
status, headers, data = self._send_with_retry(
|
||||
"/api/v1/activation/instances/%s" % iid, body, op["key"])
|
||||
except TransientError as e:
|
||||
return {"ok": False, "code": "TRANSIENT",
|
||||
"message": "网络暂时不可用(激活幂等键已保留,重试会复用同一键):%s" % e}
|
||||
if status != 200:
|
||||
self._clear_op("activation_op")
|
||||
code, msg = _err_body(data)
|
||||
human = {400: "激活参数被拒绝(%s)" % (msg or code),
|
||||
401: "license_key 或 secret 不正确,请核对交付凭据",
|
||||
403: "实例不允许激活(%s)" % (msg or code),
|
||||
409: "实例状态冲突,不能重复激活(%s),请核对实例状态或联系管理员"
|
||||
% (msg or code)}.get(status, "激活被拒绝(HTTP %s %s)" % (status, msg or code))
|
||||
self._set_last_error(human)
|
||||
return {"ok": False, "code": code or ("HTTP_%d" % status), "message": human}
|
||||
cert = (data.get("data") or {}).get("certificate")
|
||||
try:
|
||||
payload = verify_certificate(cert, iid, self.keyring)
|
||||
except VerifyError as e:
|
||||
self._clear_op("activation_op")
|
||||
human = "激活证书验签失败:%s(请核对 pinned_keys.json 是否为部署环境交付的生产公钥)" % e
|
||||
self._set_last_error(human)
|
||||
return {"ok": False, "code": "VERIFY_FAILED", "message": human}
|
||||
if self.expected_product_id is not None and \
|
||||
payload.get("product_id") != self.expected_product_id:
|
||||
self._clear_op("activation_op")
|
||||
human = ("证书产品线不符(证书 product_id=%s,本软件要求 %s)——"
|
||||
"多半是凭据发错了产品,请核对交付" % (payload.get("product_id"),
|
||||
self.expected_product_id))
|
||||
self._set_last_error(human)
|
||||
return {"ok": False, "code": "PRODUCT_MISMATCH", "message": human}
|
||||
def mut(s):
|
||||
s["certificate"] = payload
|
||||
s["certificate_envelope"] = cert
|
||||
s["status"] = "activated"
|
||||
s.pop("activation_op", None)
|
||||
s["last_error"] = ""
|
||||
with self._op_lock:
|
||||
self.state_store.update(mut)
|
||||
self._cr_cache = None # 新证书 → 门禁缓存作废
|
||||
return {"ok": True}
|
||||
|
||||
# ------------------------------------------------------------ 心跳
|
||||
|
||||
def heartbeat(self):
|
||||
"""刷新运行租约。成功返回 {"ok":True,"state":...,"next":秒}。
|
||||
整体串行:心跳循环 / 门禁自愈 / 手动刷新 三方并发时排队,杜绝两个在途操作
|
||||
互相覆盖 heartbeat_op(幂等键错乱)。"""
|
||||
with self._hb_lock:
|
||||
return self._heartbeat_locked()
|
||||
|
||||
def _heartbeat_locked(self):
|
||||
st, iid, _lk, sec = self._creds()
|
||||
with self._op_lock:
|
||||
st = self.state_store.load()
|
||||
op = st.get("heartbeat_op")
|
||||
if not op:
|
||||
op = {"key": str(uuid_mod.uuid4()), "client_time": rfc3339(self.now_fn())}
|
||||
self.state_store.update(lambda s: s.update({"heartbeat_op": op}))
|
||||
body = {"secret": sec, "client_time": op["client_time"]}
|
||||
try:
|
||||
status, headers, data = self._send_with_retry(
|
||||
"/api/v1/instances/%s/heartbeat" % iid, body, op["key"])
|
||||
except TransientError as e:
|
||||
return {"ok": False, "code": "TRANSIENT",
|
||||
"message": "网络暂时不可用(键与 client_time 已保留,重试复用):%s" % e}
|
||||
if status != 200:
|
||||
self._clear_op("heartbeat_op")
|
||||
code, msg = _err_body(data)
|
||||
human = {400: "心跳参数被拒绝(%s)" % (msg or code),
|
||||
401: "实例凭据已被拒(secret 不正确或已重置),需重新交付凭据",
|
||||
403: "实例被禁止心跳(%s)" % (msg or code),
|
||||
409: "实例状态冲突(%s),需人工处理" % (msg or code)}.get(
|
||||
status, "心跳被拒绝(HTTP %s %s)" % (status, msg or code))
|
||||
if status in (400, 401, 403, 409):
|
||||
self.state_store.update(lambda s: s.update(
|
||||
{"status": "needs_attention", "last_error": human}))
|
||||
return {"ok": False, "code": code or ("HTTP_%d" % status), "message": human}
|
||||
env = data.get("data")
|
||||
try:
|
||||
payload = verify_lease(env, iid, self.keyring)
|
||||
except VerifyError as e:
|
||||
self._clear_op("heartbeat_op")
|
||||
human = "租约验签失败:%s(请核对 pinned_keys.json)" % e
|
||||
self._set_last_error(human)
|
||||
return {"ok": False, "code": "VERIFY_FAILED", "message": human}
|
||||
try:
|
||||
nxt = self._accept_lease(payload, env)
|
||||
except VerifyError as e:
|
||||
self._clear_op("heartbeat_op")
|
||||
self._set_last_error("租约范围非法:%s" % e)
|
||||
return {"ok": False, "code": "LEASE_INVALID",
|
||||
"message": "租约范围非法:%s" % e}
|
||||
return {"ok": True, "state": payload["state"], "next": nxt}
|
||||
|
||||
def _accept_lease(self, payload, envelope):
|
||||
"""验签通过后先做范围检查,再原子落盘(enabled 随租约状态翻转)。"""
|
||||
server = parse_rfc3339(payload["server_time"])
|
||||
ent = parse_rfc3339(payload["entitlement_expires_at"])
|
||||
le = parse_rfc3339(payload["lease_expires_at"])
|
||||
if le > ent:
|
||||
raise LeaseInvalid("租约结束晚于授权结束")
|
||||
if le > server + timedelta(days=MAX_LEASE_DAYS):
|
||||
raise LeaseInvalid("租约超过服务端签发时间 + %d 天" % MAX_LEASE_DAYS)
|
||||
def mut(s):
|
||||
# 服务端时间高水位:只进不退。回退 = 可疑(重放/旧信封),整体拒绝
|
||||
hw = s.get("server_high_water")
|
||||
if hw and server < parse_rfc3339(hw):
|
||||
raise LeaseInvalid("服务端时间早于已记录的高水位")
|
||||
s["server_high_water"] = payload["server_time"] if (
|
||||
not hw or server > parse_rfc3339(hw)) else hw
|
||||
s["lease"] = payload
|
||||
s["lease_envelope"] = envelope
|
||||
s["enabled"] = (payload["state"] == "active")
|
||||
s["status"] = "activated"
|
||||
s.pop("heartbeat_op", None)
|
||||
s["last_heartbeat_at"] = rfc3339(self.now_fn())
|
||||
s["next_heartbeat_seconds"] = max(MIN_HEARTBEAT_SECONDS,
|
||||
envelope.get("next_heartbeat_seconds",
|
||||
MIN_HEARTBEAT_SECONDS))
|
||||
s["last_error"] = ""
|
||||
with self._op_lock:
|
||||
self.state_store.update(mut)
|
||||
self._cr_cache = None # 新租约 → 门禁缓存作废
|
||||
return max(MIN_HEARTBEAT_SECONDS, envelope.get("next_heartbeat_seconds",
|
||||
MIN_HEARTBEAT_SECONDS))
|
||||
|
||||
# ------------------------------------------------------------ can_run
|
||||
|
||||
def can_run(self, now=None):
|
||||
"""(True, None) | (False, 原因)。纯本地判定,不发网络请求。
|
||||
结果缓存 cache_ttl 秒:门禁每个请求都调这里,省掉每次的 ECDSA 验签 +
|
||||
高水位落盘(约 10 秒粒度的回拨检测延迟,换来磁盘只在一分钟一次量级写)。"""
|
||||
now = now or self.now_fn()
|
||||
c = self._cr_cache
|
||||
if c and self.mono_fn() < c[2]:
|
||||
return c[0], c[1]
|
||||
ok, reason = self._can_run_uncached(now)
|
||||
if self.cache_ttl > 0:
|
||||
self._cr_cache = (ok, reason, self.mono_fn() + self.cache_ttl)
|
||||
return ok, reason
|
||||
|
||||
def _can_run_uncached(self, now):
|
||||
now = now or self.now_fn()
|
||||
st = self.state_store.load()
|
||||
env = st.get("lease_envelope")
|
||||
if not env:
|
||||
if st.get("certificate_envelope"):
|
||||
return False, "已激活,正在获取运行租约(首次心跳)…"
|
||||
return False, "尚未激活:请在授权页面完成激活"
|
||||
try:
|
||||
payload = verify_lease(env, st.get("instance_id"), self.keyring)
|
||||
except VerifyError as e:
|
||||
return False, "本地租约校验失败:%s" % e
|
||||
try:
|
||||
lhw = st.get("local_high_water")
|
||||
if lhw and now < parse_rfc3339(lhw):
|
||||
return False, ("检测到本机时钟回拨(已记录 %s),为防止绕过授权已锁定,"
|
||||
"请恢复系统时间后重启软件" % lhw)
|
||||
shw = st.get("server_high_water")
|
||||
if shw and parse_rfc3339(payload["server_time"]) < parse_rfc3339(shw):
|
||||
return False, "服务端时间早于已记录的高水位"
|
||||
skew = abs(now - parse_rfc3339(payload["server_time"]))
|
||||
if skew > MAX_CLOCK_SKEW:
|
||||
return False, "本机时间与服务端时间相差超过 5 分钟,请校准系统时间"
|
||||
if payload["state"] != "active":
|
||||
return False, "授权已被服务端置为「%s」,请联系软件提供方" % payload["state"]
|
||||
ent = parse_rfc3339(payload["entitlement_expires_at"])
|
||||
le = parse_rfc3339(payload["lease_expires_at"])
|
||||
if ent <= now:
|
||||
return False, "授权已于 %s 过期" % payload["entitlement_expires_at"]
|
||||
if le <= now:
|
||||
return False, "运行租约已过期(离线过久),请联网后重启软件自动续租"
|
||||
if le > ent or le > parse_rfc3339(payload["server_time"]) + timedelta(days=MAX_LEASE_DAYS):
|
||||
return False, "租约时间窗非法"
|
||||
except VerifyError as e:
|
||||
return False, str(e)
|
||||
try:
|
||||
def mut(s):
|
||||
# 高水位节流写:只在首记或前进超过 55 秒时落盘(配合 can_run 缓存,
|
||||
# 磁盘写入降到分钟级;高水位只进不退的语义不变)
|
||||
w = s.get("local_high_water")
|
||||
if not w or now > parse_rfc3339(w) + timedelta(seconds=55):
|
||||
s["local_high_water"] = rfc3339(now)
|
||||
with self._op_lock:
|
||||
self.state_store.update(mut)
|
||||
except StorageError as e:
|
||||
return False, "授权状态保存失败(fail closed):%s" % e
|
||||
return True, None
|
||||
|
||||
def can_run_safe(self):
|
||||
"""门禁专用:任何内部异常都折算成 (False, 原因),绝不让门禁 fail open。"""
|
||||
try:
|
||||
return self.can_run()
|
||||
except Exception as e: # 存储损坏等一切意外
|
||||
return False, "授权子系统异常(fail closed):%s" % e
|
||||
|
||||
# ------------------------------------------------------------ 状态视图
|
||||
|
||||
def status(self, enforce=True, heartbeat_running=False):
|
||||
out = {"enforce": enforce, "api_base": self.api_base,
|
||||
"keyring_ready": bool(self.keyring),
|
||||
"heartbeat_running": heartbeat_running}
|
||||
try:
|
||||
st = self.state_store.load()
|
||||
except StorageError as e:
|
||||
out.update({"configured": False, "activated": False, "enabled": False,
|
||||
"can_run": False, "reason": "授权状态不可读(fail closed):%s" % e,
|
||||
"status": "error"})
|
||||
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:
|
||||
if cert.get("expires_at"):
|
||||
days_left = (parse_rfc3339(cert["expires_at"]) - self.now_fn()).days
|
||||
except VerifyError:
|
||||
pass
|
||||
out.update({
|
||||
"configured": bool(st.get("instance_id") and st.get("license_key")),
|
||||
"instance_id": st.get("instance_id"),
|
||||
"status": st.get("status") or "unactivated",
|
||||
"activated": bool(st.get("certificate_envelope")),
|
||||
"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"),
|
||||
"lease_state": lease.get("state"),
|
||||
"lease_expires_at": lease.get("lease_expires_at"),
|
||||
"server_time": lease.get("server_time"),
|
||||
"last_heartbeat_at": st.get("last_heartbeat_at"),
|
||||
"next_heartbeat_seconds": st.get("next_heartbeat_seconds"),
|
||||
"last_error": st.get("last_error") or "",
|
||||
"can_run": ok,
|
||||
"reason": reason or "授权有效,运行中",
|
||||
})
|
||||
return out
|
||||
|
||||
# ------------------------------------------------------------ 心跳循环
|
||||
|
||||
def run_forever(self, stop_event, log_fn=None):
|
||||
"""心跳线程:开机立即跳一次,随后按 next_heartbeat_seconds + 正向抖动调度。
|
||||
403/409/400/401 → 停止自动重试(长休眠直到重启/重新激活);暂时性失败退避。"""
|
||||
log = log_fn or (lambda *a: None)
|
||||
backoff = 0
|
||||
first = True
|
||||
while not stop_event.wait(0 if first else self._next_wait(backoff, True)):
|
||||
first = False
|
||||
try:
|
||||
r = self.heartbeat()
|
||||
except (StorageError, VerifyError) as e:
|
||||
log("license 心跳异常:%s" % e)
|
||||
r = {"ok": False, "code": "TRANSIENT", "message": str(e)}
|
||||
if r.get("ok"):
|
||||
if backoff:
|
||||
log("license 心跳恢复(state=%s)" % r.get("state"))
|
||||
backoff = 0
|
||||
continue
|
||||
if r.get("code") in NEED_ATTENTION or r.get("code") == "VERIFY_FAILED" \
|
||||
or r.get("code") == "LEASE_INVALID":
|
||||
log("license 心跳进入人工处理状态(%s),停止自动重试:%s"
|
||||
% (r.get("code"), r.get("message")))
|
||||
while not stop_event.wait(3600):
|
||||
pass # 停在人工处理状态:不再自动心跳,等重启/重新激活
|
||||
break
|
||||
else:
|
||||
backoff = min(backoff + 1, 6)
|
||||
log("license 心跳暂时失败(第 %d 次):%s" % (backoff, r.get("message")))
|
||||
return
|
||||
|
||||
def _next_wait(self, backoff, is_loop):
|
||||
st = self.state_store.load()
|
||||
base = max(MIN_HEARTBEAT_SECONDS, st.get("next_heartbeat_seconds") or MIN_HEARTBEAT_SECONDS)
|
||||
if backoff:
|
||||
base = min(60 * (2 ** backoff), 300)
|
||||
return base * (1.0 + random.uniform(0, 0.1)) # 少量正向抖动
|
||||
|
||||
# ------------------------------------------------------------ HTTP
|
||||
|
||||
def _httpx_send(self, method, url, body, headers):
|
||||
try:
|
||||
import httpx
|
||||
except ImportError:
|
||||
raise TransientError("缺少 httpx 库(pip install httpx),无法联网刷新授权")
|
||||
if self._http is None:
|
||||
self._http = httpx.Client(base_url=self.api_base, timeout=self.timeout)
|
||||
try:
|
||||
r = self._http.post(url, json=body, headers=headers)
|
||||
except Exception as e: # 超时/连接错误/重置等一律暂时性
|
||||
raise TransientError("%s: %s" % (type(e).__name__, e))
|
||||
return r.status_code, dict(r.headers), _safe_json(r)
|
||||
|
||||
def _send_with_retry(self, path, body, idem_key):
|
||||
"""同一操作:同一请求体 + 同一幂等键,有界重试(429/5xx/网络错误)。
|
||||
⚠ 请求头不能用返回值覆盖(曾因此重试丢 Idempotency-Key——协议红线)。"""
|
||||
url = self.api_base + path
|
||||
req_headers = {"Content-Type": "application/json", "Idempotency-Key": idem_key}
|
||||
delay = 1.0
|
||||
last = None
|
||||
for _ in range(self.max_attempts):
|
||||
try:
|
||||
status, resp_headers, data = self._send_fn("POST", url, body, req_headers)
|
||||
except (TransientError, OSError) as e:
|
||||
# OSError:ConnectionError/TimeoutError 等原生网络异常(测试/极简传输层)
|
||||
last = e
|
||||
self.sleep_fn(delay)
|
||||
delay = min(delay * 2, 30)
|
||||
continue
|
||||
if status < 500 and status != 429:
|
||||
return status, resp_headers, data
|
||||
wait = delay
|
||||
if status == 429:
|
||||
ra = resp_headers.get("Retry-After") or resp_headers.get("retry-after")
|
||||
try:
|
||||
wait = max(float(ra), delay) if ra else delay
|
||||
except (TypeError, ValueError):
|
||||
wait = delay
|
||||
last = TransientError("HTTP %s" % status)
|
||||
self.sleep_fn(min(wait, 120))
|
||||
delay = min(delay * 2, 30)
|
||||
raise TransientError(str(last) if last else "重试额度用尽")
|
||||
|
||||
# ------------------------------------------------------------ 小工具
|
||||
|
||||
def _clear_op(self, name):
|
||||
with self._op_lock:
|
||||
self.state_store.update(lambda s: s.pop(name, None))
|
||||
|
||||
def _set_last_error(self, msg):
|
||||
with self._op_lock:
|
||||
self.state_store.update(lambda s: s.update({"last_error": msg}))
|
||||
|
||||
|
||||
def _err_body(data):
|
||||
"""错误响应 → (code, message)。不回显请求内容。"""
|
||||
err = (data or {}).get("error") if isinstance(data, dict) else None
|
||||
if isinstance(err, dict):
|
||||
return str(err.get("code") or ""), str(err.get("message") or "")
|
||||
return "", ""
|
||||
|
||||
|
||||
def _safe_json(r):
|
||||
try:
|
||||
return r.json()
|
||||
except Exception:
|
||||
return {}
|
||||
@@ -0,0 +1,547 @@
|
||||
# -*- 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 hashlib
|
||||
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:门禁自愈触发节流
|
||||
_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
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 初始化
|
||||
|
||||
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:
|
||||
_check_build_integrity() # N1:烧入清单校验,被改 → 全线拦截
|
||||
_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 _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 path.startswith("/api/version"):
|
||||
# 版本状态口(/api/version、/api/version_info)在锁定态也放行:
|
||||
# 排障要看版本;强制更新页要轮询它(2026-10-27 5.9)。
|
||||
return None
|
||||
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 _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}}}
|
||||
|
||||
|
||||
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 = ("""<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>软件授权</title><style>
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{font-family:"Microsoft YaHei",system-ui,sans-serif;background:#f2f4f8;
|
||||
min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;color:#1c2733}
|
||||
.card{background:#fff;border-radius:10px;box-shadow:0 6px 24px rgba(16,35,61,.10);
|
||||
width:520px;max-width:100%;overflow:hidden}
|
||||
.hd{background:#1f4e79;color:#fff;padding:18px 28px;font-size:19px;font-weight:600}
|
||||
.hd small{display:block;font-weight:400;font-size:12px;opacity:.75;margin-top:4px}
|
||||
.bd{padding:24px 28px 28px}
|
||||
.st{border:1px solid #e3e8ef;border-radius:8px;padding:12px 16px;margin-bottom:20px;
|
||||
background:#fafbfd;font-size:13px;line-height:1.9}
|
||||
.st b{color:#b02a2a}
|
||||
.st .ok{color:#1c7c44}
|
||||
.row{margin-bottom:14px}
|
||||
.row label{display:block;font-size:13px;color:#51606f;margin-bottom:5px}
|
||||
.row input{width:100%;padding:9px 11px;border:1px solid #c8d2dd;border-radius:6px;
|
||||
font-size:13px;font-family:inherit}
|
||||
.row input:focus{outline:none;border-color:#1f4e79;box-shadow:0 0 0 2px rgba(31,78,121,.15)}
|
||||
.btns{display:flex;gap:10px;margin-top:18px}
|
||||
button{flex:1;padding:10px 0;border:0;border-radius:6px;font-size:14px;cursor:pointer;
|
||||
font-family:inherit;background:#1f4e79;color:#fff}
|
||||
button.ghost{background:#fff;color:#1f4e79;border:1px solid #1f4e79}
|
||||
button:disabled{opacity:.5;cursor:default}
|
||||
.msg{margin-top:14px;font-size:13px;line-height:1.7;display:none;
|
||||
padding:10px 12px;border-radius:6px}
|
||||
.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">
|
||||
<div class="st" id="st">加载中…</div>
|
||||
<div class="row"><label>实例 ID(instance_id)</label>
|
||||
<input id="iid" placeholder="形如 11111111-2222-3333-4444-555555555555" spellcheck="false"></div>
|
||||
<div class="row"><label>授权码(license_key)</label>
|
||||
<input id="lk" placeholder="交付单上提供的授权码" spellcheck="false"></div>
|
||||
<div class="row"><label>激活密钥(secret,仅输入一次,本机加密保存)</label>
|
||||
<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>
|
||||
</div></div>
|
||||
<script>
|
||||
var TIMER=null;
|
||||
function esc(s){return String(s==null?"":s).replace(/[&<>"]/g,function(c){
|
||||
return {"&":"&","<":"<",">":">",'"':"""}[c];});}
|
||||
function fmtSt(d){
|
||||
var h="";
|
||||
h+="状态:"+(d.can_run?'<span class="ok">已授权,运行中</span>':"<b>"+esc(d.reason||"不可用")+"</b>")+"<br>";
|
||||
if(d.instance_id)h+="实例:"+esc(d.instance_id)+"<br>";
|
||||
if(d.entitlement_expires_at)h+="授权到期:"+esc(d.entitlement_expires_at)+"<br>";
|
||||
if(d.lease_expires_at)h+="租约到期:"+esc(d.lease_expires_at)+"<br>";
|
||||
if(d.last_heartbeat_at)h+="最后心跳:"+esc(d.last_heartbeat_at)+"<br>";
|
||||
if(!d.keyring_ready)h+="<b>⚠ 信任根未配置(pinned_keys.json 为空),激活将无法通过验签——请联系软件提供方。</b><br>";
|
||||
if(d.last_error)h+="最近错误:"+esc(d.last_error);
|
||||
return h;}
|
||||
function load(){
|
||||
fetch("/api/license/status").then(function(r){return r.json()}).then(function(j){
|
||||
var d=j.data||{};
|
||||
document.getElementById("st").innerHTML=fmtSt(d);
|
||||
document.getElementById("sub").textContent="授权服务器:"+(d.api_base||"")+
|
||||
(d.enforce?"":"(当前为开发模式,未强制校验)");
|
||||
if(d.can_run&&d.enforce){location.reload();return;}
|
||||
if(TIMER)clearTimeout(TIMER);
|
||||
TIMER=setTimeout(load,15000);
|
||||
}).catch(function(){
|
||||
document.getElementById("st").innerHTML="<b>无法读取授权状态(本机服务异常?)</b>";
|
||||
});}
|
||||
function doAct(){
|
||||
var b={instance_id:document.getElementById("iid").value.trim(),
|
||||
license_key:document.getElementById("lk").value.trim(),
|
||||
secret:document.getElementById("sec").value};
|
||||
var m=document.getElementById("msg");
|
||||
if(!b.instance_id||!b.license_key||!b.secret){
|
||||
m.className="msg err";m.textContent="三项都要填写(见交付单)。";return;}
|
||||
var btn=document.getElementById("go");btn.disabled=true;
|
||||
m.className="msg";m.style.display="none";
|
||||
fetch("/api/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},
|
||||
body:JSON.stringify(b)}).then(function(r){return r.json()}).then(function(j){
|
||||
btn.disabled=false;
|
||||
var d=j.data||{},res=d.result||{};
|
||||
if(res.ok){document.getElementById("sec").value="";
|
||||
m.className="msg ok";m.textContent="激活成功,正在进入系统…";setTimeout(load,600);return;}
|
||||
m.className="msg err";m.textContent=res.message||"激活失败,请核对凭据。";
|
||||
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
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"_说明": [
|
||||
"可信公钥清单(信任根):只随软件/受控部署渠道固定分发,绝不在线发现。",
|
||||
"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": [
|
||||
{
|
||||
"key_id": "prod-22056bfacc8fe8a2",
|
||||
"public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESr8/VFFwt70o7fwa8HiRNyxWtZEu\nUqzCBfYRG72DazEgeOaSVAdlTv49OujtggXSJzFLOluMENJzaRmp9+iJ0Q==\n-----END PUBLIC KEY-----",
|
||||
"spki_sha256": "22056bfacc8fe8a240dd2125b629e60ba9f4a5ea0041a1efe034f376a258d562",
|
||||
"revoked": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""授权状态受保护存储。
|
||||
|
||||
- LicenseStateStore:激活证书 / 运行租约 / enabled / 本地与服务端时间高水位的
|
||||
原子落盘(tmp + fsync + os.replace)。协议要求"先原子保存再启用业务",
|
||||
保存失败必须让调用方走 fail closed。
|
||||
- SecretStore 接口 + Windows DPAPI 实现:实例 secret 只进系统级保护存储
|
||||
(DPAPI CurrentUser),绝不写入源码/日志/普通明文文件;非 Windows 退化为
|
||||
仅当前用户可读的明文文件(开发环境兜底,交付环境只支持 Windows)。
|
||||
|
||||
协议自带声明:一般受控存储不能抵抗完全控制主机的攻击者和磁盘快照回滚,
|
||||
本模块不宣称硬件绑定或防克隆。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
"""状态读写失败(磁盘满/权限等)。调用方必须 fail closed。"""
|
||||
|
||||
|
||||
class LicenseStateStore:
|
||||
"""接口:load() → dict;save(state) 原子写。"""
|
||||
|
||||
def load(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def save(self, state):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class JsonFileStore(LicenseStateStore):
|
||||
"""JSON 文件原子存储。进程内加锁;跨进程不做(本应用本就不支持双实例共库)。"""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
|
||||
def load(self):
|
||||
with self._lock:
|
||||
return self._load_unlocked()
|
||||
|
||||
def _load_unlocked(self):
|
||||
try:
|
||||
with open(self.path, encoding="utf-8") as f:
|
||||
st = json.load(f)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except Exception as e:
|
||||
raise StorageError("授权状态读取失败:%s" % e)
|
||||
return st if isinstance(st, dict) else {}
|
||||
|
||||
def save(self, state):
|
||||
with self._lock:
|
||||
tmp = self.path + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(state, f, ensure_ascii=False, indent=1)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, self.path)
|
||||
except Exception as e:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise StorageError("授权状态保存失败:%s" % e)
|
||||
|
||||
def update(self, fn):
|
||||
"""原子读改写:fn(state) → state'(原地改传入 dict 即可),返回新状态。"""
|
||||
with self._lock:
|
||||
st = self._load_unlocked()
|
||||
fn(st)
|
||||
self._save_unlocked(st)
|
||||
return st
|
||||
|
||||
def _save_unlocked(self, state):
|
||||
tmp = self.path + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(state, f, ensure_ascii=False, indent=1)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, self.path)
|
||||
except Exception as e:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise StorageError("授权状态保存失败:%s" % e)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- secret
|
||||
|
||||
class SecretStore:
|
||||
"""接口:get() → str|None;set(secret);clear()。"""
|
||||
|
||||
def get(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def set(self, secret):
|
||||
raise NotImplementedError
|
||||
|
||||
def clear(self):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
if os.name == "nt":
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
class _DATA_BLOB(ctypes.Structure):
|
||||
_fields_ = [("cbData", wintypes.DWORD),
|
||||
("pbData", ctypes.POINTER(ctypes.c_char))]
|
||||
|
||||
_CRYPTPROTECT_UI_FORBIDDEN = 0x1
|
||||
|
||||
def _dpapi(data, protect):
|
||||
crypt32 = ctypes.windll.crypt32
|
||||
k32 = ctypes.windll.kernel32
|
||||
buf = ctypes.create_string_buffer(data, len(data))
|
||||
inb = _DATA_BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
|
||||
out = _DATA_BLOB()
|
||||
if protect:
|
||||
ok = crypt32.CryptProtectData(
|
||||
ctypes.byref(inb), "pricing-review-license", None, None, None,
|
||||
_CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
|
||||
else:
|
||||
ok = crypt32.CryptUnprotectData(
|
||||
ctypes.byref(inb), None, None, None, None,
|
||||
_CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
|
||||
if not ok:
|
||||
raise StorageError("DPAPI %s 失败(错误码 %s)"
|
||||
% ("加密" if protect else "解密", ctypes.GetLastError()))
|
||||
try:
|
||||
return ctypes.string_at(out.pbData, out.cbData)
|
||||
finally:
|
||||
k32.LocalFree(out.pbData)
|
||||
|
||||
class DpapiSecretStore(SecretStore):
|
||||
"""Windows DPAPI(CurrentUser)加密落盘:换用户/拷走文件都解不开,
|
||||
源码里没有也不需要任何硬编码密钥。"""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
|
||||
def get(self):
|
||||
try:
|
||||
with open(self.path, "rb") as f:
|
||||
raw = f.read()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except OSError as e:
|
||||
raise StorageError("secret 读取失败:%s" % e)
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return _dpapi(base64.b64decode(raw), False).decode("utf-8")
|
||||
except Exception as e:
|
||||
raise StorageError("secret 解密失败(可能换了系统用户):%s" % e)
|
||||
|
||||
def set(self, secret):
|
||||
enc = _dpapi(secret.encode("utf-8"), True)
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(base64.b64encode(enc))
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, self.path)
|
||||
|
||||
def clear(self):
|
||||
try:
|
||||
os.unlink(self.path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
else: # 非 Windows 兜底(开发环境)
|
||||
|
||||
class DpapiSecretStore(SecretStore):
|
||||
"""占位实现:明文落盘(权限收窄到当前用户)。交付环境不支持。"""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
|
||||
def get(self):
|
||||
try:
|
||||
with open(self.path, encoding="utf-8") as f:
|
||||
v = f.read().strip()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
return base64.b64decode(v).decode("utf-8") if v else None
|
||||
|
||||
def set(self, secret):
|
||||
with open(self.path, "w", encoding="utf-8") as f:
|
||||
f.write(base64.b64encode(secret.encode("utf-8")).decode("ascii"))
|
||||
try:
|
||||
os.chmod(self.path, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def clear(self):
|
||||
try:
|
||||
os.unlink(self.path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
@@ -0,0 +1,267 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""license-v2 / lease-v2 信封验签(ECDSA P-256 + SHA-256)。
|
||||
|
||||
规范要点(license-platform 接入包 protocol.md):
|
||||
- 规范化串不是 JSON:固定顺序 key=value、单个 LF 连接、无末尾 LF、UTF-8 编码;
|
||||
整数字段输出正十进制;时间字段用收到的原始字符串(验签前不得格式化/重序列化)。
|
||||
- signature 是 ASN.1 DER ECDSA 的标准 Base64,不带 = 填充(不是 Base64URL,
|
||||
也不是固定 64 字节 r||s)。
|
||||
- canonical_sha256 是规范化字节的 SHA-256 十六进制,仅辅助校验,不能代替公钥验签。
|
||||
- 拒绝:未知版本、缺字段/多字段、非法类型、含 CR/LF/NUL 的字段、未知或已撤销
|
||||
key_id、非 P-256 公钥、绑定到其他实例的信封、legacy v1。
|
||||
(证书例外:OPTIONAL_CERT_FIELDS 两个可选权益字段可缺省,见下方注释。)
|
||||
|
||||
信任根:只信随软件/受控渠道固定分发的公钥(pinned_keys.json),绝不在线发现。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
|
||||
LICENSE_V2 = "license-v2"
|
||||
LEASE_V2 = "lease-v2"
|
||||
ALGORITHM = "ECDSA-P256-SHA256"
|
||||
|
||||
# 固定字段顺序 = canonical 顺序;payload 必须恰好等于这些键,缺一个多一个都拒
|
||||
FIELDSETS = {
|
||||
LICENSE_V2: ("version", "instance_id", "license_id", "customer_id",
|
||||
"product_id", "starts_at", "expires_at", "key_id"),
|
||||
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})$")
|
||||
LEASE_STATES = ("active", "frozen", "revoked", "expired", "not_started", "not_activated")
|
||||
|
||||
# 两种信封的固定键集合(缺一个多一个都拒)
|
||||
CERT_ENVELOPE_KEYS = {"version", "payload", "signature", "canonical_sha256"}
|
||||
LEASE_ENVELOPE_KEYS = {"payload", "signature", "canonical_sha256", "algorithm",
|
||||
"next_heartbeat_seconds"}
|
||||
|
||||
|
||||
class VerifyError(Exception):
|
||||
"""验签/结构校验失败。消息只写原因,不含任何凭据。"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 时间工具
|
||||
|
||||
def parse_rfc3339(s):
|
||||
"""RFC3339 → UTC aware datetime。形状不对抛 VerifyError。"""
|
||||
if not isinstance(s, str) or not RFC3339_RE.match(s):
|
||||
raise VerifyError("时间格式不是 RFC3339:%r" % (s,))
|
||||
from datetime import datetime, timezone
|
||||
v = s.strip()
|
||||
if v.endswith(("Z", "z")):
|
||||
v = v[:-1] + "+00:00"
|
||||
dt = datetime.fromisoformat(v)
|
||||
if dt.tzinfo is None:
|
||||
raise VerifyError("时间缺时区:%r" % (s,))
|
||||
return dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def rfc3339(dt):
|
||||
"""aware datetime → RFC3339 UTC(Z 后缀,秒精度)。"""
|
||||
from datetime import timezone
|
||||
dt = dt.astimezone(timezone.utc).replace(microsecond=0)
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
# ------------------------------------------------------------- keyring 管理
|
||||
|
||||
def build_keyring(entries):
|
||||
"""[{key_id, public_key_pem, revoked, spki_sha256?}] → {key_id: {"key": pub, "revoked": bool}}。
|
||||
|
||||
pinned 文件本身配置错(非 P-256 / 解不开 / 指纹不符)要立刻暴露,不能静默当不可信。
|
||||
spki_sha256(受控交付时随公钥附来的 SPKI DER SHA-256 十六进制)选填:
|
||||
给了就实算比对,防 PEM 在拷贝/转存中被损坏(yhy-license-trust v1 口径)。
|
||||
"""
|
||||
ring = {}
|
||||
for e in entries or []:
|
||||
kid, pem = e.get("key_id"), e.get("public_key_pem")
|
||||
if not kid or not pem:
|
||||
raise VerifyError("pinned_keys 条目缺 key_id/public_key_pem")
|
||||
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
|
||||
|
||||
|
||||
def load_keyring_file(path):
|
||||
"""读取随软件分发的 pinned_keys.json(不存在/为空 = 未配置信任根,fail closed)。"""
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return build_keyring(data.get("pinned_keys"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 规范化
|
||||
|
||||
# 字段类型白名单:ID 三兄弟必须真整数(bool 也拒);时间字段必须合法 RFC3339
|
||||
_INT_FIELDS = {"license_id", "customer_id", "product_id"}
|
||||
_TIME_FIELDS = {"starts_at", "expires_at", "server_time",
|
||||
"entitlement_expires_at", "lease_expires_at"}
|
||||
|
||||
|
||||
def _field_value(payload, name):
|
||||
v = payload[name]
|
||||
if isinstance(v, bool) or v is None or isinstance(v, (list, dict, float)):
|
||||
raise VerifyError("字段 %s 类型非法" % name)
|
||||
if isinstance(v, int) or name in _INT_FIELDS:
|
||||
if not isinstance(v, int) or v <= 0:
|
||||
raise VerifyError("字段 %s 必须是正整数" % name)
|
||||
return str(v) # ID:正十进制整数
|
||||
if not isinstance(v, str):
|
||||
raise VerifyError("字段 %s 类型非法" % name)
|
||||
if any(c in v for c in ("\r", "\n", "\x00")):
|
||||
raise VerifyError("字段 %s 含 CR/LF/NUL" % name)
|
||||
if name in _TIME_FIELDS:
|
||||
parse_rfc3339(v) # 时间字段必须是合法 RFC3339
|
||||
elif not v:
|
||||
raise VerifyError("字段 %s 不能为空" % name)
|
||||
return v
|
||||
|
||||
|
||||
def canonical_bytes(payload, version):
|
||||
"""规范化字节串:固定顺序 key=value、LF 连接、无末尾 LF、UTF-8。"""
|
||||
if version not in FIELDSETS:
|
||||
raise VerifyError("未知信封版本:%r" % (version,))
|
||||
out = []
|
||||
for name in FIELDSETS[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")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 结构校验
|
||||
|
||||
def _check_payload(payload, version, expected_instance):
|
||||
if not isinstance(payload, dict):
|
||||
raise VerifyError("payload 不是对象")
|
||||
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))
|
||||
for name in FIELDSETS[version]:
|
||||
_field_value(payload, name) # 类型/字符白名单
|
||||
if not UUID_RE.match(str(payload["instance_id"])):
|
||||
raise VerifyError("instance_id 不是 UUID")
|
||||
if expected_instance and str(payload["instance_id"]).lower() != str(expected_instance).lower():
|
||||
raise VerifyError("信封绑定到其他实例")
|
||||
if version == LICENSE_V2:
|
||||
parse_rfc3339(payload["starts_at"])
|
||||
parse_rfc3339(payload["expires_at"])
|
||||
else:
|
||||
if payload["state"] not in LEASE_STATES:
|
||||
raise VerifyError("租约状态非法:%r" % (payload["state"],))
|
||||
parse_rfc3339(payload["server_time"])
|
||||
parse_rfc3339(payload["entitlement_expires_at"])
|
||||
parse_rfc3339(payload["lease_expires_at"])
|
||||
|
||||
|
||||
def _decode_signature(sig):
|
||||
if not isinstance(sig, str) or not sig:
|
||||
raise VerifyError("signature 缺失或非法")
|
||||
if "-" in sig or "_" in sig: # Base64URL 字母表 → 拒
|
||||
raise VerifyError("signature 疑似 Base64URL 编码")
|
||||
pad = "=" * (-len(sig) % 4)
|
||||
try:
|
||||
return base64.b64decode(sig + pad, validate=True)
|
||||
except Exception:
|
||||
raise VerifyError("signature 不是标准 Base64")
|
||||
|
||||
|
||||
def _check_aux_sha(envelope, canonical):
|
||||
want = envelope.get("canonical_sha256")
|
||||
if not isinstance(want, str):
|
||||
raise VerifyError("canonical_sha256 缺失或非法")
|
||||
got = hashlib.sha256(canonical).hexdigest()
|
||||
if want.lower() != got:
|
||||
raise VerifyError("canonical_sha256 不符(载荷与规范化串不一致)")
|
||||
|
||||
|
||||
def _verify_with_keyring(envelope_keys, envelope, version, expected_instance, keyring):
|
||||
if not isinstance(envelope, dict) or set(envelope.keys()) != envelope_keys:
|
||||
raise VerifyError("信封字段集不符(缺/多字段)")
|
||||
payload = envelope.get("payload")
|
||||
_check_payload(payload, version, expected_instance)
|
||||
kid = payload["key_id"]
|
||||
ent = keyring.get(kid) if isinstance(keyring, dict) else None
|
||||
if ent is None:
|
||||
raise VerifyError("未知 key_id:%r(不在可信公钥清单)" % (kid,))
|
||||
if ent["revoked"]:
|
||||
raise VerifyError("key_id=%s 已撤销" % kid)
|
||||
canonical = canonical_bytes(payload, version)
|
||||
_check_aux_sha(envelope, canonical)
|
||||
der = _decode_signature(envelope.get("signature"))
|
||||
try:
|
||||
ent["key"].verify(der, canonical, ec.ECDSA(hashes.SHA256()))
|
||||
except InvalidSignature:
|
||||
raise VerifyError("签名无效")
|
||||
return payload
|
||||
|
||||
|
||||
def verify_certificate(envelope, expected_instance, keyring):
|
||||
"""激活证书(license-v2):信封含 version 字段。"""
|
||||
return _verify_with_keyring(CERT_ENVELOPE_KEYS, envelope, LICENSE_V2,
|
||||
expected_instance, keyring)
|
||||
|
||||
|
||||
def verify_lease(envelope, expected_instance, keyring):
|
||||
"""运行租约(lease-v2):信封含 algorithm / next_heartbeat_seconds。"""
|
||||
if envelope.get("algorithm") != ALGORITHM:
|
||||
raise VerifyError("algorithm=%r 不是 %s" % (envelope.get("algorithm"), ALGORITHM))
|
||||
nhs = envelope.get("next_heartbeat_seconds")
|
||||
if isinstance(nhs, bool) or not isinstance(nhs, int) or nhs < 60:
|
||||
raise VerifyError("next_heartbeat_seconds 必须是 ≥60 的整数")
|
||||
return _verify_with_keyring(LEASE_ENVELOPE_KEYS, envelope, LEASE_V2,
|
||||
expected_instance, keyring)
|
||||
800
_analysis/定额单价专题/iab_env3/CostReview/app/server/mcp_server.py
Normal file
800
_analysis/定额单价专题/iab_env3/CostReview/app/server/mcp_server.py
Normal file
@@ -0,0 +1,800 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""MCP 接入层(2026-10-15 上线;2026-10-27 主人重定义:**只读**)。
|
||||
|
||||
- 传输:Streamable HTTP(POST /mcp,JSON-RPC 2.0,单响应 JSON;无 SSE/无会话态,stateless)
|
||||
- 开关:全局设置 mcp_enabled(**默认关**——断开就是连不上,403);令牌 mcp_token
|
||||
(首次开启自动生成,调用必须带 Authorization: Bearer <令牌>,/api/mcp/status 可查)
|
||||
- 收费挂钩:license enforce 时未激活/过期(套餐范围外且临时卡失效)→ 整个端点
|
||||
403 LICENSE_REQUIRED(开关开了也断)
|
||||
- 工具(2026-10-29 决策 238/239 起 9 个;①~⑤⑧ 只读,⑥⑦⑨ 写入为**主人拍板新增**,
|
||||
取代 2026-10-27「只读、无任何增删改」旧口径):
|
||||
① bills_query 入库项目清单:编号/名称/项目特征/单价
|
||||
② lme_prices 工料机单价
|
||||
③ market_info_prices 市场价/信息价数据
|
||||
④ recent_review_query 工作台最近审核(口径同 ①②)
|
||||
⑤ attachment_download 下载绑定附件——**仅在用户明确要求附件时调用**;查询响应一律
|
||||
不含附件信息;id 必须来自 ①~④ 的查询结果;三类:bill / lme(行绑定)+ batch
|
||||
(价格批次原件);不支持枚举、不支持全量下载
|
||||
⑥ project_import 整项目导入(写入):整项目模板 xlsx(项目目录+多对 Sheet)→ 建手工工程
|
||||
⑦ bill_adopt 清单采纳(写入):走软件采纳同一条 API,整套术语表口径,可取消可追溯;
|
||||
仅在用户明确要求采纳时调用
|
||||
⑧ match_hist 历史价匹配 top-N:对会话一行找最像的历史价(match.py 同一管线),
|
||||
行带 ref 票据供 ⑦⑨ 采纳
|
||||
⑨ lme_adopt 工料机价格采纳(写入):采纳即改价(页面同一条通道),价格数字来自
|
||||
⑧ 的服务端快照,不接受调用方传数字;仅在用户明确要求采纳时调用
|
||||
- 零新增依赖:JSON-RPC 手写,只依赖标准库
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
import uuid
|
||||
|
||||
PROTO_VERSION = "2025-06-18"
|
||||
_API = None # api_server 模块(bind 注入,避免循环导入)
|
||||
ATT_MAX_DL = 20 * 1024 * 1024 # 单附件下载上限:超过请走软件界面下载
|
||||
|
||||
|
||||
def bind(api_module):
|
||||
global _API
|
||||
_API = api_module
|
||||
|
||||
|
||||
def _api():
|
||||
if _API is None:
|
||||
raise RuntimeError("mcp_server 未 bind")
|
||||
return _API
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 开关 / 令牌 / 门禁
|
||||
|
||||
def enabled():
|
||||
a = _api()
|
||||
return (a._setting_get("global", "mcp_enabled") or "") == "1"
|
||||
|
||||
|
||||
def token():
|
||||
a = _api()
|
||||
return a._setting_get("global", "mcp_token") or ""
|
||||
|
||||
|
||||
def set_enabled(on):
|
||||
"""开关(持久化,重启保持)。打开时没有令牌就生成一个。返回 (enabled, token)。"""
|
||||
a = _api()
|
||||
tok = token()
|
||||
if on and not tok:
|
||||
tok = secrets.token_hex(16)
|
||||
a._setting_set("global", "mcp_token", tok)
|
||||
a._setting_set("global", "mcp_enabled", "1" if on else "0")
|
||||
return on, tok
|
||||
|
||||
|
||||
def status():
|
||||
a = _api()
|
||||
return {"enabled": enabled(), "token": token(), "tools": len(TOOLS()),
|
||||
"endpoint": "/mcp", "port": a.PORT, "license_enforced": bool(a.license_gate._cfg.get("enforce", True))}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具实现(只读)
|
||||
|
||||
def _hist(fn):
|
||||
"""历史库只读查询(入库项目 / 市场价信息价 / 附件绑定)。"""
|
||||
a = _api()
|
||||
con = a.conn()
|
||||
try:
|
||||
return fn(con)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _sess(fn):
|
||||
"""会话库只读查询(工作台最近审核)。"""
|
||||
a = _api()
|
||||
sc = a.sess.connect()
|
||||
try:
|
||||
return fn(sc)
|
||||
finally:
|
||||
sc.close()
|
||||
|
||||
|
||||
def _paging(args):
|
||||
"""limit 归一:默认 10,1~100。
|
||||
2026-11-02 主人定:智能体命令没说条数=只给匹配前 10 条;说了最多给到 100。"""
|
||||
try:
|
||||
return min(max(int(args.get("limit") or 10), 1), 100)
|
||||
except (TypeError, ValueError):
|
||||
return 10
|
||||
|
||||
|
||||
def _need_scope(args):
|
||||
"""查询范围守卫:keyword 或 batch_id 至少给一个(防空量拖库)。"""
|
||||
kw = (args.get("keyword") or "").strip()
|
||||
try:
|
||||
bid = int(args.get("batch_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
bid = 0
|
||||
return kw, bid
|
||||
|
||||
|
||||
def _rows(con, sql, params):
|
||||
cur = con.execute(sql, params)
|
||||
cols = [d[0] for d in cur.description]
|
||||
return [dict(zip(cols, r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _t_bills_query(args):
|
||||
"""① 入库项目清单:Number(编号)/Name(名称)/Attr(项目特征)/Price(单价)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(清单编号/名称关键词)或 batch_id 之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT b.id, b.batch_id, t.Name AS batch_name, b.Number, b.Name, b.Attr, b.Price "
|
||||
"FROM bills b JOIN batches t ON t.id = b.batch_id "
|
||||
"WHERE t.kind='project'")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND b.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (b.Number LIKE ? OR b.Name LIKE ?)"
|
||||
params += ["%%%s%%" % kw, "%%%s%%" % kw]
|
||||
sql += " ORDER BY b.batch_id, b.x_seq LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_lme_prices(args):
|
||||
"""② 工料机单价:NoTaxPrice(除税)/TaxRate(税率)/TaxPrice(含税)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(工料机编号/名称/规格关键词)或 batch_id 之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT l.id, l.batch_id, t.Name AS batch_name, l.Number, l.Name, "
|
||||
"l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice "
|
||||
"FROM lmes l JOIN batches t ON t.id = l.batch_id "
|
||||
"WHERE t.kind='project'")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND l.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (l.Number LIKE ? OR l.Name LIKE ? OR l.Specification LIKE ?)"
|
||||
params += ["%%%s%%" % kw] * 3
|
||||
sql += " ORDER BY l.batch_id, l.id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_market_info_prices(args):
|
||||
"""③ 市场价/信息价数据(价格批次明细)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(编号/名称关键词)或 batch_id(价格批次 id)之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT p.id, p.batch_id, t.Name AS batch_name, t.x_publisher, p.Code, p.Name, "
|
||||
"p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Class "
|
||||
"FROM prices p JOIN batches t ON t.id = p.batch_id "
|
||||
"WHERE t.kind IN ('info', 'market')")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND p.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (p.Code LIKE ? OR p.Name LIKE ?)"
|
||||
params += ["%%%s%%" % kw, "%%%s%%" % kw]
|
||||
sql += " ORDER BY p.batch_id, p.id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_recent_review_query(args):
|
||||
"""④ 工作台最近审核:不带 session_id → 最近会话列表;带 session_id+type → 行数据
|
||||
(type=bills 口径同 ①,type=lmes 口径同 ②)。"""
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
sid = 0
|
||||
typ = (args.get("type") or "").strip().lower()
|
||||
kw = (args.get("keyword") or "").strip()
|
||||
lim = _paging(args)
|
||||
if not sid:
|
||||
rows = _sess(lambda sc: _rows(
|
||||
sc, "SELECT id, name, period_from, period_to, imported_at, x_total "
|
||||
"FROM sessions ORDER BY imported_at DESC LIMIT ?", (lim,)))
|
||||
return {"ok": True, "total": len(rows), "rows": rows,
|
||||
"hint": "带 session_id + type(bills/lmes)查行数据"}
|
||||
if typ not in ("bills", "lmes"):
|
||||
return {"ok": False, "msg": "type 必须是 bills 或 lmes(不带 type 时返回会话列表)"}
|
||||
if typ == "bills":
|
||||
sql = ("SELECT id, Number, Name, Attr, Price, Unit, Quantity "
|
||||
"FROM s_bills WHERE session_id=?")
|
||||
else:
|
||||
sql = ("SELECT id, Number, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice "
|
||||
"FROM s_lmes WHERE session_id=?")
|
||||
params = [sid]
|
||||
if kw:
|
||||
if typ == "bills":
|
||||
sql += " AND (Number LIKE ? OR Name LIKE ?)"
|
||||
else:
|
||||
sql += " AND (Number LIKE ? OR Name LIKE ? OR Specification LIKE ?)"
|
||||
params += ["%%%s%%" % kw] * (2 if typ == "bills" else 3)
|
||||
sql += " ORDER BY id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _sess(lambda sc: _rows(sc, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具实现(写入,决策 238)
|
||||
|
||||
def _period_to_m(v):
|
||||
"""'YYYY-MM' 或 'YYYY/MM' 或 月序号 → 月序号(年*12+月);非法返回 None。"""
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip()
|
||||
m = re.match(r"^(\d{4})[-/年](\d{1,2})", s)
|
||||
if m:
|
||||
return int(m.group(1)) * 12 + int(m.group(2))
|
||||
try:
|
||||
n = int(float(s))
|
||||
return n if n > 0 else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _t_project_import(args):
|
||||
"""⑥ 整项目导入(决策 238,写入):整项目模板 xlsx(项目目录+多对 Sheet,每对=1 个单位工程)
|
||||
→ 建手工工程(目录树+清单一次到位)。file_b64=xlsx 内容(base64)。同名手工工程再次导入=整项目覆盖。
|
||||
导入后可用 recent_review_query 查该工程(session_id),再用 bill_adopt 采纳。"""
|
||||
a = _api()
|
||||
name = (args.get("name") or "").strip()
|
||||
if not name:
|
||||
return {"ok": False, "msg": "name(工程名称)必填"}
|
||||
pf = _period_to_m(args.get("period_from"))
|
||||
pt = _period_to_m(args.get("period_to") or args.get("period_from"))
|
||||
if pf is None or pt is None:
|
||||
return {"ok": False, "msg": "period_from(YYYY-MM)必填;period_to 缺省=同 period_from"}
|
||||
b64 = (args.get("file_b64") or "").strip()
|
||||
if not b64:
|
||||
return {"ok": False, "msg": "file_b64(整项目模板 xlsx 的 base64 内容)必填——先向用户要 Excel 或按 template 说明生成"}
|
||||
import base64 as _b64
|
||||
try:
|
||||
raw = _b64.b64decode(b64, validate=True)
|
||||
except Exception:
|
||||
return {"ok": False, "msg": "file_b64 不是合法 base64"}
|
||||
d = os.path.join(a.DATA_DIR, "manual_projects")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
path = os.path.join(d, "mcp_%s.xlsx" % time.strftime("%Y%m%d_%H%M%S"))
|
||||
with open(path, "wb") as f:
|
||||
f.write(raw)
|
||||
body = {"name": name, "period_from": pf, "period_to": pt, "path": path,
|
||||
"province": (args.get("province") or "").strip(),
|
||||
"city": (args.get("city") or "").strip(),
|
||||
"district": (args.get("district") or "").strip(),
|
||||
"bulid_unit": (args.get("bulid_unit") or "").strip()}
|
||||
with a.WRITE_LOCK:
|
||||
con = a.sess.connect()
|
||||
try:
|
||||
r = a.mimp.import_project(con, body)
|
||||
con.commit()
|
||||
except Exception as e:
|
||||
r = {"ok": False, "msg": "导入异常:%s" % e}
|
||||
finally:
|
||||
con.close()
|
||||
if r.get("ok"):
|
||||
r["next"] = "recent_review_query(session_id=%s) 查清单;bill_adopt(session_id, bill_id, src_bill_id) 采纳" % r.get("sid")
|
||||
return r
|
||||
|
||||
|
||||
def _t_bill_adopt(args):
|
||||
"""⑦ 清单采纳(决策 238,写入):把入库项目清单的定额+消耗量落到工作台会话。
|
||||
bill_id=会话清单 id、src_bill_id=入库项目清单 id(都来自查询结果);走软件采纳同一条
|
||||
API(术语表整套口径:新行覆盖/已有行追加、取价锚、可取消可追溯)。仅在用户明确要求
|
||||
采纳时调用;每次一条,采纳后把结果如实告诉用户。"""
|
||||
a = _api()
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
bid = int(args.get("bill_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "msg": "session_id / bill_id 都必须是整数 id"}
|
||||
src = 0
|
||||
snap = None
|
||||
if args.get("ref"):
|
||||
snap = _MATCH_CACHE.get((args.get("ref") or "").strip())
|
||||
if not snap or snap.get("type") != "bill":
|
||||
return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist(type=bill)重新匹配"}
|
||||
try:
|
||||
src = int(snap.get("bill_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
src = 0
|
||||
if not src:
|
||||
return {"ok": False, "msg": "该匹配行缺少来源清单 id,无法采纳"}
|
||||
else:
|
||||
try:
|
||||
src = int(args.get("src_bill_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "msg": "src_bill_id 必须是整数 id(或改传 ref 票据)"}
|
||||
if not sid or not bid or not src:
|
||||
return {"ok": False, "msg": "参数:session_id(工作台会话)+ bill_id(会话清单)+ src_bill_id(或 ref 票据)"}
|
||||
with a.WRITE_LOCK: # 会话写库统一串行;采纳后分组缓存必撤(与页面路由同口径)
|
||||
sc = a.sess.connect()
|
||||
hc = a.conn()
|
||||
try:
|
||||
r = a.api_bill_adopt(sc, hc, {"session_id": sid, "bill_id": bid, "src_bill_id": src})
|
||||
sc.commit()
|
||||
if r.get("ok"):
|
||||
try:
|
||||
a._grp_cache_drop("session", sid)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
sc.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
r = {"ok": False, "msg": "采纳失败:%s" % e}
|
||||
finally:
|
||||
sc.close()
|
||||
hc.close()
|
||||
return r
|
||||
|
||||
|
||||
# ---- 决策 239(2026-10-29 主人定):历史价匹配 top-N + 工料机价格采纳 ----
|
||||
# match_hist 返回行带 ref 票据:行数据快照(三价/名称/项目名)存本进程缓存,lme_adopt 只传
|
||||
# ref——被采纳的数字全部由服务端快照取,智能体零转录、改不了价。缓存仅进程内,超限整体清空
|
||||
#(语义=ref 失效请重新 match),不落盘、无泄漏面。
|
||||
_MATCH_CACHE = {}
|
||||
_MATCH_CACHE_MAX = 2000
|
||||
|
||||
|
||||
def _match_ref(row):
|
||||
if len(_MATCH_CACHE) >= _MATCH_CACHE_MAX:
|
||||
_MATCH_CACHE.clear()
|
||||
ref = uuid.uuid4().hex[:12]
|
||||
_MATCH_CACHE[ref] = row
|
||||
return ref
|
||||
|
||||
|
||||
def _sess_row_ctx(sc, sid):
|
||||
"""会话元信息 + 匹配停用词(与工作台比对路由同口径)。"""
|
||||
a = _api()
|
||||
s = sc.execute("SELECT name, src_name, base_period_m, period_from, period_to FROM sessions WHERE id=?",
|
||||
(sid,)).fetchone()
|
||||
if not s:
|
||||
return None
|
||||
pf = (s["period_from"] if "period_from" in s.keys() else None) or s["base_period_m"] or 0
|
||||
pt = (s["period_to"] if "period_to" in s.keys() else None) or pf
|
||||
sw = a._setting_get("global", "match_stopwords")
|
||||
try:
|
||||
a.match.set_stopwords(json.loads(sw)) if sw else a.match.set_stopwords([])
|
||||
except Exception:
|
||||
a.match.set_stopwords([])
|
||||
return {"base": (pf, pt),
|
||||
"self_name": (s["name"] or "").strip(),
|
||||
"self_src": (s["src_name"] or "").split(";")[0].strip()}
|
||||
|
||||
|
||||
def _t_match_hist(args):
|
||||
"""⑧ 历史价匹配 top-N(决策 239,只读):对工作台的一行(清单或工料机)在全部入库项目/
|
||||
信息价/市场价里找最像的历史价,按 档位+期次距离 排序返回 top-N。每行带 ref 票据——
|
||||
bill_adopt / lme_adopt 用它采纳,不需要再传价格数字。"""
|
||||
a = _api()
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
rid = int(args.get("row_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "msg": "session_id / row_id 必须是整数 id"}
|
||||
typ = (args.get("type") or "bill").strip().lower()
|
||||
if typ not in ("bill", "lme"):
|
||||
return {"ok": False, "msg": "type 必须是 bill(清单)或 lme(工料机)"}
|
||||
if not sid or not rid:
|
||||
return {"ok": False, "msg": "参数:session_id + row_id(来自 recent_review_query 的行 id)"}
|
||||
try:
|
||||
limit = min(max(int(args.get("limit") or 5), 1), 20)
|
||||
except (TypeError, ValueError):
|
||||
limit = 5
|
||||
sc = a.sess.connect()
|
||||
hc = a.conn()
|
||||
try:
|
||||
ctx = _sess_row_ctx(sc, sid)
|
||||
if ctx is None:
|
||||
return {"ok": False, "msg": "会话不存在(%d)" % sid}
|
||||
if typ == "lme":
|
||||
row = sc.execute("SELECT * FROM s_lmes WHERE id=? AND session_id=?", (rid, sid)).fetchone()
|
||||
if not row:
|
||||
return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"}
|
||||
res = a.match.match_lme(hc, row, ctx["base"], limit=limit,
|
||||
self_name=ctx["self_name"], self_src=ctx["self_src"])
|
||||
else:
|
||||
row = sc.execute("SELECT * FROM s_bills WHERE id=? AND session_id=?", (rid, sid)).fetchone()
|
||||
if not row:
|
||||
return {"ok": False, "msg": "清单行不存在(可能已被删除,请刷新)"}
|
||||
res = a.match.match_bill(hc, row, ctx["base"], [], [], [], limit,
|
||||
self_name=ctx["self_name"], self_src=ctx["self_src"])
|
||||
finally:
|
||||
sc.close()
|
||||
hc.close()
|
||||
out = []
|
||||
for r in res:
|
||||
ref = _match_ref({"type": typ, **{k: r.get(k) for k in
|
||||
("name", "attr", "spec", "unit", "price", "tax", "price_tax", "proj", "src", "src_id", "bill_id")}})
|
||||
out.append({"ref": ref, "tier": r.get("tier"), "src": r.get("src"),
|
||||
"name": r.get("name"), "spec": r.get("spec") or r.get("attr"),
|
||||
"unit": r.get("unit"), "price": r.get("price"), "tax": r.get("tax"),
|
||||
"price_tax": r.get("price_tax"), "proj": r.get("proj"),
|
||||
"period": r.get("period"), "sim": r.get("sim")})
|
||||
return {"ok": True, "total": len(out),
|
||||
"hint": "挑最合适的一行,把它的 ref 传给 %s 采纳" % ("lme_adopt" if typ == "lme" else "bill_adopt"),
|
||||
"rows": out}
|
||||
|
||||
|
||||
def _t_lme_adopt(args):
|
||||
"""⑨ 工料机价格采纳(决策 239,写入,仅在用户明确要求采纳时调用)。
|
||||
lme_id=会话工料机行 id(recent_review_query type=lmes 的行)、ref=match_hist 返回的票据。
|
||||
与页面比对框「采纳」同一条通道:三价改价端点(三价联动/编码同步/merged_codes/旧价锚)
|
||||
+「采纳:名称+项目+旧三价」备注。被采纳的价格来自服务端快照,不接受调用方传数字。"""
|
||||
a = _api()
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
lid = int(args.get("lme_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "msg": "session_id / lme_id 必须是整数 id"}
|
||||
ref = (args.get("ref") or "").strip()
|
||||
snap = _MATCH_CACHE.get(ref)
|
||||
if not snap or snap.get("type") != "lme":
|
||||
return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist 重新匹配再采纳"}
|
||||
if not sid or not lid:
|
||||
return {"ok": False, "msg": "参数:session_id + lme_id(工作台工料机行 id,来自 recent_review_query)"}
|
||||
sc = a.sess.connect()
|
||||
try:
|
||||
sl = sc.execute("SELECT id, Number, Name FROM s_lmes WHERE id=? AND session_id=?", (lid, sid)).fetchone()
|
||||
if not sl:
|
||||
return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"}
|
||||
proj = sc.execute("""SELECT id, ntp, taxrate, taxp FROM s_lme_proj
|
||||
WHERE session_id=? AND code=? ORDER BY id LIMIT 1""",
|
||||
(sid, sl["Number"] or "")).fetchone() if sl["Number"] else None
|
||||
if not proj:
|
||||
return {"ok": False, "msg": "找不到该项目级工料机行(编码 %s)——项目级汇总未生成或编码为空" % (sl["Number"] or "空")}
|
||||
old = {"price": proj["ntp"], "tax": proj["taxrate"], "taxp": proj["taxp"]}
|
||||
with a.WRITE_LOCK: # 采纳即改价(决策 158)+ 采纳备注(决策 219 旧价锚口径)
|
||||
rp = a.api_lme_price(sc, {"session_id": sid, "id": proj["id"],
|
||||
"ntp": snap.get("price"), "taxrate": snap.get("tax"),
|
||||
"taxp": snap.get("price_tax")})
|
||||
if not rp.get("ok"):
|
||||
sc.rollback()
|
||||
return {"ok": False, "msg": "采纳改价失败:" + (rp.get("msg") or "服务未响应")}
|
||||
# 采纳备注文案与页面 adoptTxtFor 同口径:采纳:名称+项目+旧三价(0/空=「无」)
|
||||
def p(v):
|
||||
try:
|
||||
return "无" if (v is None or v == "" or float(v) == 0) else v
|
||||
except (TypeError, ValueError):
|
||||
return "无"
|
||||
txt = "采纳:%s+%s+%s|%s|%s" % (snap.get("name") or "", snap.get("proj") or "",
|
||||
p(old["price"]), p(old["tax"]), p(old["taxp"]))
|
||||
a.sess.save_lme_remark(sc, proj["id"], txt)
|
||||
sc.commit()
|
||||
finally:
|
||||
sc.close()
|
||||
return {"ok": True, "lme_id": proj["id"], "price": snap.get("price"),
|
||||
"tax": snap.get("tax"), "price_tax": snap.get("price_tax"), "old": old,
|
||||
"msg": "已采纳《%s》%s:除税 %s → %s" % (snap.get("name") or "", snap.get("proj") or "",
|
||||
old["price"], snap.get("price"))}
|
||||
|
||||
|
||||
def _t_attachment_download(args):
|
||||
"""⑤ 下载绑定附件(仅响应明确指令;id 必须来自 ①~④ 查询结果)。
|
||||
type=bill/lme → 该行绑定的询价附件(bill_attach / lme_attach);
|
||||
type=batch → 价格批次原件(batches.x_attach_sha)。"""
|
||||
a = _api()
|
||||
typ = (args.get("type") or "").strip().lower()
|
||||
try:
|
||||
rid = int(args.get("id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
rid = 0
|
||||
if typ not in ("bill", "lme", "batch") or not rid:
|
||||
return {"ok": False, "msg": "参数:type=bill|lme|batch + id(来自查询结果的行/批次 id)"}
|
||||
|
||||
def load(con):
|
||||
if typ == "bill":
|
||||
return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 "
|
||||
"FROM bill_attach a JOIN inquiry_files f ON f.id=a.file_id "
|
||||
"WHERE a.bill_id=?", (rid,)), a.INQ_DIR
|
||||
if typ == "lme":
|
||||
return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 "
|
||||
"FROM lme_attach a JOIN inquiry_files f ON f.id=a.file_id "
|
||||
"WHERE a.lme_id=?", (rid,)), a.INQ_DIR
|
||||
return _rows(con, "SELECT at.original_name, at.stored_path, at.size, at.sha256 "
|
||||
"FROM attachments at WHERE at.sha256="
|
||||
"(SELECT x_attach_sha FROM batches WHERE id=?)", (rid,)), a.ATTACH_DIR
|
||||
|
||||
files, root = _hist(load)
|
||||
if not files:
|
||||
return {"ok": False, "msg": "没有绑定附件(或 id 不存在)"}
|
||||
out = []
|
||||
for f in files:
|
||||
fp = os.path.realpath(os.path.join(a.DATA_DIR, f["stored_path"] or ""))
|
||||
if os.path.commonpath([fp, os.path.realpath(root)]) != os.path.realpath(root):
|
||||
return {"ok": False, "msg": "附件路径不合法,拒绝读取"}
|
||||
try:
|
||||
with open(fp, "rb") as fh:
|
||||
raw = fh.read()
|
||||
except OSError as e:
|
||||
return {"ok": False, "msg": "附件读取失败:%s" % e}
|
||||
if len(raw) > ATT_MAX_DL:
|
||||
return {"ok": False, "msg": "《%s》超过 %d MB 下载上限,请在软件界面下载"
|
||||
% ((f["original_name"] or "")[:40], ATT_MAX_DL // 1024 // 1024)}
|
||||
out.append({"name": f["original_name"], "size": f["size"], "sha256": f["sha256"],
|
||||
"content_base64": base64.b64encode(raw).decode("ascii")})
|
||||
return {"ok": True, "files": out}
|
||||
|
||||
|
||||
def _t_excel_bill_match(args):
|
||||
"""⑩ Excel 批量清单匹配(2026-11-02 主人定,只读):Excel **只放一列清单名称**(A 列,
|
||||
首行若是「清单名称/名称」表头自动跳过),逐行在全部入库项目清单里匹配**每条最优一条**
|
||||
——期次近优先、同批次名称相似度高优先。期次/地区筛选=对比框同款:
|
||||
period_from/period_to(YYYY-MM,可选,同时是期次距离基准)、province/city/district(可选)。
|
||||
行数不限;Excel 无编码无单位 → 走名称相似匹配(match_bill unit_free),无「精确编码」档属预期。"""
|
||||
a = _api()
|
||||
b64 = (args.get("file_b64") or "").strip()
|
||||
if not b64:
|
||||
return {"ok": False, "msg": "file_b64(Excel 的 base64 内容,A 列=清单名称)必填——先向用户要 Excel 或请用户粘贴名称清单"}
|
||||
import base64 as _b64
|
||||
try:
|
||||
raw = _b64.b64decode(b64, validate=True)
|
||||
except Exception:
|
||||
return {"ok": False, "msg": "file_b64 不是合法 base64"}
|
||||
pf = _period_to_m(args.get("period_from"))
|
||||
pt = _period_to_m(args.get("period_to") or args.get("period_from"))
|
||||
prov = (args.get("province") or "").strip()
|
||||
city = (args.get("city") or "").strip()
|
||||
dist = (args.get("district") or "").strip()
|
||||
area = [(prov, city, dist)] if (prov or city or dist) else None
|
||||
try:
|
||||
import io as _io
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(_io.BytesIO(raw), read_only=True, data_only=True)
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": "Excel 读取失败:%s" % e}
|
||||
names = []
|
||||
try:
|
||||
ws = wb.worksheets[0]
|
||||
for i, rx in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True)):
|
||||
v = rx[0] if rx else None
|
||||
v = str(v).strip() if v is not None else ""
|
||||
if not v:
|
||||
continue
|
||||
if i == 0 and v in ("清单名称", "名称", "项目名称", "清单"):
|
||||
continue # 表头行
|
||||
names.append(v)
|
||||
finally:
|
||||
wb.close()
|
||||
if not names:
|
||||
return {"ok": False, "msg": "Excel A 列没有读到任何清单名称"}
|
||||
hc = a.conn()
|
||||
rows_out = []
|
||||
try:
|
||||
base = pf if pf is not None else 0
|
||||
for nm in names:
|
||||
fake = {"Name": nm, "Unit": "", "Attr": "", "x_hash_exact": None, "x_hash_semi": None}
|
||||
try:
|
||||
res = a.match.match_bill(hc, fake, base, [], [], [], limit=8,
|
||||
pfrom=pf, pto=pt, area=area, unit_free=True)
|
||||
except Exception:
|
||||
res = []
|
||||
best = sorted(res, key=lambda r: (r.get("dist") or 0, -(r.get("sim") or 0)))[0] if res else None
|
||||
if best:
|
||||
rows_out.append({"name": nm, "hit": True, "tier": best.get("tier"),
|
||||
"match_name": best.get("name"), "unit": best.get("unit"),
|
||||
"price": best.get("price"), "proj": best.get("proj"),
|
||||
"region": best.get("region"), "period": best.get("period"),
|
||||
"sim": best.get("sim")})
|
||||
else:
|
||||
rows_out.append({"name": nm, "hit": False, "msg": "没有匹配到足够相似的历史清单"})
|
||||
finally:
|
||||
hc.close()
|
||||
return {"ok": True, "total": len(rows_out), "hit": sum(1 for r in rows_out if r["hit"]),
|
||||
"hint": "每行=Excel 一条清单的最优匹配:期次近优先、同批次名称相似度优先;price=该清单历史单价(未匹配行带 hit=false)",
|
||||
"rows": rows_out}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具清单
|
||||
|
||||
def TOOLS():
|
||||
return [
|
||||
{"name": "bills_query",
|
||||
"description": "查入库项目的清单:编号 Number、名称 Name、项目特征 Attr、单价 Price。"
|
||||
"keyword(编号/名称关键词)或 batch_id 至少给一个;limit 默认 10 上限 100(不传 limit=只返回匹配前 10 条)。"
|
||||
"响应不含附件信息。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_bills_query},
|
||||
{"name": "lme_prices",
|
||||
"description": "查入库项目的工料机单价:编号、名称、规格、单位、除税价 NoTaxPrice、"
|
||||
"税率 TaxRate、含税价 TaxPrice。keyword 或 batch_id 至少一个。响应不含附件信息。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_lme_prices},
|
||||
{"name": "market_info_prices",
|
||||
"description": "读市场价/信息价批次明细:Code、Name、Specification、Unit、三价、Class。"
|
||||
"keyword(编号/名称)或 batch_id(价格批次 id)至少一个。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_market_info_prices},
|
||||
{"name": "recent_review_query",
|
||||
"description": "读工作台最近审核:不带参数=最近会话列表;session_id + type(bills=清单"
|
||||
"编号/名称/项目特征/单价,lmes=工料机单价)查该会话行数据,口径与"
|
||||
"bills_query / lme_prices 一致。可选 keyword 过滤。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "type": {"type": "string"},
|
||||
"keyword": {"type": "string"}, "limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_recent_review_query},
|
||||
{"name": "attachment_download",
|
||||
"description": "下载绑定附件。**仅在用户明确要求下载附件时调用**(查询结果不含附件信息,"
|
||||
"不得主动调用)。id 必须来自查询结果:type=bill/lme 用 bills_query/"
|
||||
"lme_prices/recent_review_query 返回的行 id;type=batch 用价格批次 id"
|
||||
"(批次原件)。不支持枚举或全量下载。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"type": {"type": "string"}, "id": {"type": "integer"}},
|
||||
"required": ["type", "id"]},
|
||||
"run": _t_attachment_download},
|
||||
{"name": "project_import",
|
||||
"description": "整项目导入(写入)。把整项目模板 xlsx(「项目目录」Sheet 定目录树+"
|
||||
"多对数据 Sheet,每对 分部分项N/措施项目N=序号 N 的单位工程)导入建为"
|
||||
"手工工程。file_b64=xlsx 文件内容(base64);name/period_from(YYYY-MM) 必填,"
|
||||
"province/city/district/bulid_unit 可选。同名手工工程再次导入=整项目覆盖。"
|
||||
"导入成功后用 recent_review_query 查该工程清单,再按用户要求 bill_adopt。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"name": {"type": "string"}, "period_from": {"type": "string"},
|
||||
"period_to": {"type": "string"}, "file_b64": {"type": "string"},
|
||||
"province": {"type": "string"}, "city": {"type": "string"},
|
||||
"district": {"type": "string"}, "bulid_unit": {"type": "string"}},
|
||||
"required": ["name", "period_from", "file_b64"]},
|
||||
"run": _t_project_import},
|
||||
{"name": "bill_adopt",
|
||||
"description": "清单采纳(写入,仅在用户明确要求采纳时调用)。把入库项目清单的定额+消耗量"
|
||||
"落到工作台会话清单上(软件采纳同一条通道:新行=整组覆盖,已有行=单价覆盖+"
|
||||
"定额追加;可取消可追溯)。session_id=工作台会话、bill_id=会话清单 id、"
|
||||
"src_bill_id=入库项目清单 id(id 必须来自查询结果)。每次采纳一条并把结果如实告诉用户。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "bill_id": {"type": "integer"},
|
||||
"src_bill_id": {"type": "integer"}},
|
||||
"required": ["session_id", "bill_id", "src_bill_id"]},
|
||||
"run": _t_bill_adopt},
|
||||
{"name": "match_hist",
|
||||
"description": "历史价匹配 top-N(只读)。对工作台一行(清单或工料机)在全部入库项目/信息价/"
|
||||
"市场价里找最像的历史价,按档位+期次距离排序返回 top-N;每行带 ref 票据,"
|
||||
"把它传给 bill_adopt / lme_adopt 即可采纳——不需要(也不允许)自己传价格数字。"
|
||||
"session_id + row_id(来自 recent_review_query)+ type(bill/lme)+ limit(默认 5,上限 20)。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "row_id": {"type": "integer"},
|
||||
"type": {"type": "string"}, "limit": {"type": "integer"}},
|
||||
"required": ["session_id", "row_id"]},
|
||||
"run": _t_match_hist},
|
||||
{"name": "lme_adopt",
|
||||
"description": "工料机价格采纳(写入,仅在用户明确要求采纳时调用)。把匹配到的历史价"
|
||||
"(ref 票据)采纳到工作台工料机:与页面比对框「采纳」同一条通道(三价联动/"
|
||||
"编码同步/merged_codes/旧价锚+采纳备注)。lme_id=工作台工料机行 id"
|
||||
"(recent_review_query type=lmes 的行)+ ref(match_hist type=lme 返回的票据)。"
|
||||
"价格数字来自服务端快照,不接受调用方传数字;每次一条,结果如实告知用户。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "lme_id": {"type": "integer"},
|
||||
"ref": {"type": "string"}},
|
||||
"required": ["session_id", "lme_id", "ref"]},
|
||||
"run": _t_lme_adopt},
|
||||
{"name": "excel_bill_match",
|
||||
"description": "Excel 批量清单匹配(只读,数量不限)。Excel 只放一列清单名称(A 列,"
|
||||
"可有「清单名称」表头),file_b64=Excel 的 base64;逐行在全部入库项目清单里"
|
||||
"匹配每条最优一条(期次近优先、同批次名称相似度优先)。期次/地区沿用对比框"
|
||||
"筛选口径:period_from/period_to(YYYY-MM,可选)、province/city/district(可选)。"
|
||||
"适合「按某期查一批清单的历史单价」。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"file_b64": {"type": "string"}, "period_from": {"type": "string"},
|
||||
"period_to": {"type": "string"}, "province": {"type": "string"},
|
||||
"city": {"type": "string"}, "district": {"type": "string"}},
|
||||
"required": ["file_b64"]},
|
||||
"run": _t_excel_bill_match},
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- JSON-RPC 分发
|
||||
|
||||
def _rpc_error(cid, code, message, data=None):
|
||||
e = {"code": code, "message": message}
|
||||
if data is not None:
|
||||
e["data"] = data
|
||||
return {"jsonrpc": "2.0", "id": cid, "error": e}
|
||||
|
||||
|
||||
def _rpc_result(cid, result):
|
||||
return {"jsonrpc": "2.0", "id": cid, "result": result}
|
||||
|
||||
|
||||
def _dispatch(msg):
|
||||
"""单条 JSON-RPC → (is_notification, response_obj)。"""
|
||||
method = msg.get("method", "")
|
||||
cid = msg.get("id")
|
||||
if method == "initialize":
|
||||
return False, _rpc_result(cid, {
|
||||
"protocolVersion": PROTO_VERSION,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "造价审核", "version": "mcp-2.0"}})
|
||||
if method == "ping":
|
||||
return False, _rpc_result(cid, {})
|
||||
if method == "tools/list":
|
||||
tools = [{"name": t["name"], "description": t["description"],
|
||||
"inputSchema": t["inputSchema"]} for t in TOOLS()]
|
||||
return False, _rpc_result(cid, {"tools": tools})
|
||||
if method == "tools/call":
|
||||
params = msg.get("params") or {}
|
||||
name = params.get("name", "")
|
||||
args = params.get("arguments") or {}
|
||||
for t in TOOLS():
|
||||
if t["name"] == name:
|
||||
try:
|
||||
out = t["run"](args)
|
||||
text = json.dumps(out, ensure_ascii=False, default=str)
|
||||
return False, _rpc_result(cid, {"content": [{"type": "text", "text": text}],
|
||||
"isError": bool(out.get("ok") is False)})
|
||||
except Exception as e:
|
||||
return False, _rpc_result(cid, {
|
||||
"content": [{"type": "text", "text": "工具执行异常:%s" % e}], "isError": True})
|
||||
return False, _rpc_error(cid, -32602, "未知工具:%s" % name)
|
||||
if cid is None:
|
||||
return True, None # 未知通知:忽略
|
||||
return False, _rpc_error(cid, -32601, "未知方法:%s" % method)
|
||||
|
||||
|
||||
def handle_post(auth_header, body_text):
|
||||
"""POST /mcp 入口。返回 (HTTP 状态码, 响应对象或 None[202])。
|
||||
三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时套餐范围外且临时卡失效整端点断)。"""
|
||||
a = _api()
|
||||
if not enabled():
|
||||
return 403, {"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32001, "message": "MCP 未开启:请在软件「设置 → MCP 接入」打开开关",
|
||||
"data": {"switch_api": "/api/admin/mcp"}}}
|
||||
tok = token()
|
||||
given = (auth_header or "").strip()
|
||||
if given.lower().startswith("bearer "):
|
||||
given = given[7:].strip()
|
||||
if not tok or not given or not secrets.compare_digest(given, tok):
|
||||
return 401, {"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32002, "message": "令牌缺失或不正确(Authorization: Bearer <令牌>;"
|
||||
"令牌见软件「设置 → MCP 接入」或 /api/mcp/status)"}}
|
||||
ok, reason = a.license_gate.can_run_now()
|
||||
if not ok:
|
||||
return 403, {"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32003, "message": "授权不可用:%s" % reason,
|
||||
"data": {"code": "LICENSE_REQUIRED"}}}
|
||||
try:
|
||||
payload = json.loads(body_text or "null")
|
||||
except Exception:
|
||||
return 400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "JSON 解析失败"}}
|
||||
msgs = payload if isinstance(payload, list) else [payload]
|
||||
if not msgs:
|
||||
return 400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "空请求"}}
|
||||
outs, has_call = [], False
|
||||
for m in msgs:
|
||||
if not isinstance(m, dict):
|
||||
outs.append(_rpc_error(None, -32600, "请求必须是对象"))
|
||||
has_call = True
|
||||
continue
|
||||
is_note, resp = _dispatch(m)
|
||||
if not is_note:
|
||||
outs.append(resp)
|
||||
has_call = True
|
||||
if not has_call:
|
||||
return 202, None # 纯通知:202 空体
|
||||
if isinstance(payload, list):
|
||||
return 200, outs
|
||||
return 200, outs[0]
|
||||
226
_analysis/定额单价专题/iab_env3/CostReview/app/server/version_gate.py
Normal file
226
_analysis/定额单价专题/iab_env3/CostReview/app/server/version_gate.py
Normal file
@@ -0,0 +1,226 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""强制更新门禁 version_gate(2026-10-27,《企业和个人版.md》5.9,主人拍板)。
|
||||
|
||||
- 版本信息文件:软件商统一服务器静态 JSON
|
||||
{latest_version, min_required_version, release_notes, package_url, sha256}
|
||||
(URL 出包烧入 BUILD.VERSION_INFO_URL;开发态无 BUILD → 一律旁路,不拉取不拦截)。
|
||||
- 拉取:启动 + 后台低频线程(默认 30 分钟),成功后原子落盘 data/version_cache.json
|
||||
(首装包可预置一份快照,由 build_portable 负责;拉取失败静默沿用旧缓存)。
|
||||
- 判定(纯本地,只读缓存):当前 APP_VERSION < min_required_version → 全员阻断
|
||||
(页面回自包含强制更新页;API 回 403 UPDATE_REQUIRED,绝不回 HTML 给 API——
|
||||
同授权门禁纪律);否则放行,仅版本卡提示有新版。
|
||||
- fail 原则:版本检查不得比授权更硬——从未拉到且无快照 = 不拦;
|
||||
min_required_version 解析失败 = 不拦(视为 0);断网用最近缓存判定
|
||||
(与租约 7 天口径天然对齐:长期断网本来就会被授权先拦住)。
|
||||
- 升级 = 换包(B/S 只更服务器):新版 APP_VERSION ≥ min_required 自动解除拦截。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import license_build_config as BUILD # 出包生成;开发态不存在
|
||||
except Exception:
|
||||
try:
|
||||
import license_build_config as BUILD # 裸跑(server/ 直挂 sys.path)时
|
||||
except Exception:
|
||||
BUILD = None
|
||||
|
||||
CACHE_NAME = "version_cache.json"
|
||||
ALWAYS_PREFIX = ("/api/license/", "/api/version") # 授权三口 + 版本状态口:永不拦
|
||||
DEFAULT_INTERVAL = 30 * 60 # 后台拉取间隔(秒)
|
||||
FETCH_TIMEOUT = 10.0
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cache = None # 最近一次成功拉取的信息(含 fetched_at)
|
||||
_cfg = {"app_version": None, "info_url": None, "interval": DEFAULT_INTERVAL,
|
||||
"data_dir": None}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 版本比较
|
||||
|
||||
def vkey(s):
|
||||
"""'1.2.10' → (1, 2, 10);解析失败 → ()(配合调用方 fail-open,不当硬门禁)。"""
|
||||
try:
|
||||
return tuple(int(x) for x in str(s).strip().lstrip("vV").split("."))
|
||||
except Exception:
|
||||
return ()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 初始化/缓存
|
||||
|
||||
def init(data_dir, build=None, start_thread=True):
|
||||
"""run() 启动时调用。build 不传 = 读出包烧入的 license_build_config。"""
|
||||
b = build if build is not None else BUILD
|
||||
_cfg["data_dir"] = data_dir
|
||||
_cfg["app_version"] = str(getattr(b, "APP_VERSION", "") or "").strip() if b else None
|
||||
_cfg["info_url"] = str(getattr(b, "VERSION_INFO_URL", "") or "").strip() if b else None
|
||||
try:
|
||||
_cfg["interval"] = int(getattr(b, "VERSION_CHECK_INTERVAL", DEFAULT_INTERVAL)
|
||||
or DEFAULT_INTERVAL) if b else DEFAULT_INTERVAL
|
||||
except Exception:
|
||||
_cfg["interval"] = DEFAULT_INTERVAL
|
||||
load_cache()
|
||||
if start_thread and effective() and _cfg["info_url"]:
|
||||
threading.Thread(target=_loop, name="version-gate", daemon=True).start()
|
||||
|
||||
|
||||
def effective():
|
||||
"""开发态(无 BUILD / APP_VERSION 空 / 'dev')旁路:不拦截。"""
|
||||
v = _cfg.get("app_version")
|
||||
return bool(v) and v not in ("dev", "0.0.0")
|
||||
|
||||
|
||||
def _cache_path():
|
||||
dd = _cfg.get("data_dir")
|
||||
return os.path.join(dd, CACHE_NAME) if dd else None
|
||||
|
||||
|
||||
def load_cache():
|
||||
global _cache
|
||||
fp = _cache_path()
|
||||
if not fp:
|
||||
return None
|
||||
try:
|
||||
with open(fp, "r", encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
if isinstance(d, dict):
|
||||
_cache = d
|
||||
return d
|
||||
except Exception:
|
||||
pass # 快照损坏 = 当没有(fail-open)
|
||||
return None
|
||||
|
||||
|
||||
def _save_cache(info):
|
||||
global _cache
|
||||
_cache = info
|
||||
fp = _cache_path()
|
||||
if not fp:
|
||||
return
|
||||
tmp = fp + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(info, f, ensure_ascii=False, indent=1)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, fp) # 原子写:中断不留半个文件
|
||||
except Exception:
|
||||
pass # 写盘失败不致命:内存缓存仍在
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 拉取
|
||||
|
||||
def fetch_once(http_get=None):
|
||||
"""拉一次版本信息文件。成功 → 落缓存返回 True;失败静默返回 False(用旧缓存)。"""
|
||||
url = _cfg.get("info_url")
|
||||
if not url:
|
||||
return False
|
||||
try:
|
||||
get = http_get or _http_get
|
||||
d = get(url)
|
||||
if not isinstance(d, dict):
|
||||
return False
|
||||
if not isinstance(d.get("latest_version"), str) or \
|
||||
not isinstance(d.get("min_required_version"), str):
|
||||
return False
|
||||
keep = {k: d.get(k) for k in ("latest_version", "min_required_version",
|
||||
"release_notes", "package_url", "sha256")}
|
||||
keep["fetched_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
with _lock:
|
||||
_save_cache(keep)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _http_get(url):
|
||||
import httpx # 决策 30 已入包依赖
|
||||
r = httpx.get(url, timeout=FETCH_TIMEOUT,
|
||||
headers={"User-Agent": "costreview-versiongate/1"})
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
|
||||
def _loop():
|
||||
fetch_once()
|
||||
while True:
|
||||
time.sleep(max(300, _cfg.get("interval") or DEFAULT_INTERVAL))
|
||||
fetch_once()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 判定/拦截
|
||||
|
||||
def check():
|
||||
"""(ok, info)。ok=False = 低于最低要求版本。"""
|
||||
if not effective():
|
||||
return True, {"bypass": "dev"}
|
||||
c = _cache or load_cache() or {}
|
||||
cur = vkey(_cfg.get("app_version"))
|
||||
req = vkey(c.get("min_required_version"))
|
||||
info = {"current": _cfg.get("app_version"),
|
||||
"latest": c.get("latest_version") or "",
|
||||
"min_required": c.get("min_required_version") or "",
|
||||
"notes": c.get("release_notes") or "",
|
||||
"package_url": c.get("package_url") or "",
|
||||
"last_check": c.get("fetched_at") or ""}
|
||||
if not cur or not req: # 无缓存/解析失败:不拦(fail-open)
|
||||
return True, info
|
||||
return (cur >= req), info
|
||||
|
||||
|
||||
def intercept(method, path):
|
||||
"""仿 license_client.gate.intercept:None=放行;dict=拦截(html 强制页 / json 403)。"""
|
||||
if not effective():
|
||||
return None
|
||||
ok, info = check()
|
||||
if ok:
|
||||
return None
|
||||
p = (path or "").split("?")[0]
|
||||
if p.startswith(ALWAYS_PREFIX):
|
||||
return None
|
||||
if method == "GET":
|
||||
return {"kind": "html", "code": 200, "text": forced_page(info)}
|
||||
return {"kind": "json", "code": 403,
|
||||
"obj": {"error": {"code": "UPDATE_REQUIRED",
|
||||
"message": "当前版本已停止服务,请升级到 %s 或更高版本"
|
||||
% (info.get("min_required") or "最新版")}}}
|
||||
|
||||
|
||||
def status():
|
||||
"""/api/version_info:当前/最新/最低要求/是否被强制/是否有新版。"""
|
||||
ok, info = check()
|
||||
out = dict(info)
|
||||
out["forced"] = not ok
|
||||
cur, lat = vkey(info.get("current")), vkey(info.get("latest"))
|
||||
out["update_available"] = bool(ok and cur and lat and cur < lat)
|
||||
return out
|
||||
|
||||
|
||||
def forced_page(info):
|
||||
cur = info.get("current") or "?"
|
||||
req = info.get("min_required") or "?"
|
||||
notes = str(info.get("notes") or "")
|
||||
pkg = str(info.get("package_url") or "")
|
||||
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:560px;padding:34px 38px}
|
||||
h1{font-size:20px;color:#b02a2a;margin:0 0 14px}
|
||||
p{color:#33475b;line-height:1.8;margin:8px 0;font-size:14px}
|
||||
.k{color:#8a97a5;font-size:12px;margin-top:18px;line-height:1.7}
|
||||
b{color:#1f2d3d}
|
||||
</style></head><body><div class="c">
|
||||
<h1>⚠ 当前版本已停止服务,需要升级</h1>
|
||||
<p>当前版本:<b>__CUR__</b> | 本软件要求的最低版本:<b>__REQ__</b></p>
|
||||
<p>升级方法:请联系软件提供方获取升级包(或在服务器上运行升级流程),完成后重新打开本页即可自动恢复。</p>
|
||||
__PKG____NOTES__
|
||||
<div class="k">本页面由本机服务提供。升级不会影响任何数据;如对升级有疑问,请联系软件提供方。
|
||||
版本状态口:/api/version_info(供排查用)。</div>
|
||||
</div></body></html>""".replace("__CUR__", cur).replace("__REQ__", req) \
|
||||
.replace("__PKG__", '<p>升级包地址:<a href="%s">%s</a></p>' % (pkg, pkg) if pkg else "") \
|
||||
.replace("__NOTES__", "<p>更新说明:%s</p>" % notes if notes else "")
|
||||
Reference in New Issue
Block a user