feat: 新增xq0031_xq0032 ERP报表导出插件,完成功能与基建更新
1. 新增xq0031_xq0032插件:包含前后端源码、打包脚本、配置文件与插件元数据 2. 新增内网文件服务器组件:exe、启停脚本、打包脚本与配置 3. 新增敏感凭证RSA加密下发能力与存储结构 4. 新增大文件源管理表与相关API 5. 优化登录流程与会话管理,新增Chrome自动化安装工具链 6. 清理废弃插件与示例代码 7. 更新版本号至1.1.3,完善安装包与.gitignore配置
This commit is contained in:
@@ -12,7 +12,7 @@ from pydantic import BaseModel
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _cp_headers, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _SESS, _SESS_LOCK,
|
||||
_sess_account, _sess_persist)
|
||||
_sess_account, _sess_persist, _ACCT_CLOUD_TOKEN)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -66,6 +66,10 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
# 沿用中心机登录时签发的用户云令牌,后续 /api/admin/me 等调用凭它定位账号(无需机器 TOKEN)
|
||||
_cloud_tok = (r or {}).get("cloud_token") or ""
|
||||
if _cloud_tok:
|
||||
_ACCT_CLOUD_TOKEN[b.account.strip()] = _cloud_tok
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
@@ -82,6 +86,15 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后插件同步失败:%s", _exc)
|
||||
# 登录后刷新该账号敏感凭证(管理员可拉到;员工被服务端 403 拒绝 → 走本地缓存,无害)
|
||||
try:
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load(b.account.strip())
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后敏感凭证刷新失败:%s", _exc)
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
@@ -84,6 +83,14 @@ def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response
|
||||
_sync_licensing(acct)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
# 登录后刷新该账号敏感凭证(管理员可拉到;员工被服务端 403 拒绝 → 走本地缓存,无害)
|
||||
try:
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load(acct)
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
except Exception as _exc: # noqa: BLE001 刷新失败不影响登录本身
|
||||
_LOGGER.warning("登录后敏感凭证刷新失败:%s", _exc)
|
||||
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
|
||||
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
|
||||
|
||||
@@ -131,21 +138,20 @@ def admin_dingtalk_inline_qr(request: Request) -> dict:
|
||||
|
||||
@router.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done),URL 由控制面代理构造。
|
||||
|
||||
执行机无需任何钉钉应用凭证(凭证只在控制面);前端「钉钉登录」当前窗口跳转该 URL,
|
||||
扫码后浏览器自动回跳本机 /auth/done。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
r = _cp_call(
|
||||
"GET", "/api/dingtalk/login-url",
|
||||
params={"back": redirect_uri, "state": state},
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
|
||||
return {"url": r.get("url") or "", "state": state}
|
||||
|
||||
|
||||
@router.get("/auth/done")
|
||||
|
||||
@@ -12,6 +12,8 @@ from webhost.backend.plugins import PLUGINS, load_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins, _cloud_plugin_manifest
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import chrome_manager as _chrome
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -19,13 +21,17 @@ router = APIRouter()
|
||||
@router.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
# 插件可见性 = 本地授权票据快照(统一真源,与运行门禁一致):仅展示票据内被授权插件;
|
||||
# 票据不可用(缺失/过期且刷新失败)→ 空列表 + authExpired,前端提示联网刷新(超时不能使用)。
|
||||
auth_expired = False
|
||||
if account:
|
||||
allowed = _meta._cloud_plugin_ids(account)
|
||||
plugins = ([_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_meta._plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
ok, lic = licensing.ensure_license(account)
|
||||
if ok:
|
||||
allowed = {p.get("pluginId") for p in (lic or {}).get("plugins", [])}
|
||||
plugins = [_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
else:
|
||||
plugins = []
|
||||
auth_expired = True
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _meta._account_allowed_platforms(account) if account else None
|
||||
@@ -35,10 +41,10 @@ def meta(request: Request) -> dict:
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in _st.PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": config.CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(config.DINGTALK_APP_KEY),
|
||||
# 钉钉扫码 URL 由控制面代理构造,客户端零钉钉凭证;控制面配置了即可用扫码入口
|
||||
"dingtalkScan": bool(config.CONTROLPLANE_URL),
|
||||
"authExpired": auth_expired,
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
@@ -49,29 +55,55 @@ def plugins_sync(request: Request) -> dict:
|
||||
"""按当前登录账号权限自下载/更新插件,成功后重载注册表。
|
||||
|
||||
离线(控制面不可达)/未配置时返回空统计,前端直接沿用本地插件进入主界面。
|
||||
全程持 SYNC_LOCK:与启动后台同步串行,避免旧账号白名单覆盖本次同步结果。
|
||||
"""
|
||||
account = _require_login(request)
|
||||
result = sync_plugins(account)
|
||||
try:
|
||||
# 以「登录账号的授权插件集」作为加载白名单(替代启动时 CONTROLPLANE_ACCOUNT 的固定白名单),
|
||||
# 保证给员工账号授权插件后登录即可见/可运行;控制面不可达(manifest=None)时保持原白名单。
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is not None:
|
||||
_st.set_allowed({p.get("id") for p in manifest})
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
from webhost.backend.core.plugin_sync import SYNC_LOCK
|
||||
with SYNC_LOCK:
|
||||
result = sync_plugins(account)
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is not None:
|
||||
_st.set_allowed({p.get("id") for p in manifest})
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001 重载失败不阻断返回
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("插件同步后重载失败:%s", _exc)
|
||||
# 授权票据一并刷新:管理台新授的插件在「F5 同步」后立即可运行,
|
||||
# 否则本地许可票据停留在上次登录时的快照,点执行会被 403 拒绝(须重登才恢复)。
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _sync_licensing
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 票据刷新失败不阻断同步结果
|
||||
logging.getLogger(__name__).warning("同步后刷新授权票据失败:%s", _exc)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/shell/update-status")
|
||||
def shell_update_status(request: Request) -> dict:
|
||||
"""壳子更新状态:前端据此显示"发现新版本,点击重启更新"提示。"""
|
||||
"""壳子更新状态:前端据此显示"发现新版本,点击重启更新"提示与手动检查结果轮询。"""
|
||||
_require_login(request)
|
||||
return _shell_updater.pending_status()
|
||||
|
||||
|
||||
@router.post("/api/shell/check")
|
||||
def shell_check(request: Request) -> dict:
|
||||
"""手动检查壳子更新:只比对版本(秒级),不下载;有新版由前端提示用户确认下载。"""
|
||||
_require_login(request)
|
||||
_shell_updater.start_check()
|
||||
return {"ok": True, "checking": True}
|
||||
|
||||
|
||||
@router.post("/api/shell/download")
|
||||
def shell_download(request: Request) -> dict:
|
||||
"""开始下载新版安装包(后台流式下载,进度经 update-status 的 dl 字段轮询)。"""
|
||||
_require_login(request)
|
||||
_shell_updater.start_download()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/shell/apply")
|
||||
def shell_apply(request: Request) -> dict:
|
||||
"""应用壳子更新:运行新版安装包静默安装并退出进程(升级完成后自动重启新版本)。"""
|
||||
@@ -80,13 +112,48 @@ def shell_apply(request: Request) -> dict:
|
||||
return {"ok": True} # 实际不会走到这里(apply 内 os._exit)
|
||||
|
||||
|
||||
# ===================== 浏览器(Chrome)检测/下载/安装 =====================
|
||||
|
||||
@router.get("/api/chrome/status")
|
||||
def chrome_status(request: Request) -> dict:
|
||||
"""浏览器状态:是否已装、版本、需否下载、下载进度。前端据此显示"安装 Chrome"图标提示。"""
|
||||
_require_login(request)
|
||||
return _chrome.status()
|
||||
|
||||
|
||||
@router.post("/api/chrome/check")
|
||||
def chrome_check(request: Request) -> dict:
|
||||
"""手动检测浏览器:刷新本机安装状态 + 中心机有无登记内网安装包。"""
|
||||
_require_login(request)
|
||||
_chrome.refresh()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/chrome/download")
|
||||
def chrome_download(request: Request) -> dict:
|
||||
"""开始后台下载 Chrome 安装包(进度经 /api/chrome/status 的 dl 字段轮询)。"""
|
||||
_require_login(request)
|
||||
_chrome.start_download()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/chrome/install")
|
||||
def chrome_install(request: Request) -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包(后台进行,前端轮询 status.installed 感知成功)。"""
|
||||
_require_login(request)
|
||||
return _chrome.install()
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/login")
|
||||
def platform_login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
"""真实登录:需先通过统一账户登录(有会话)、授权票据有效,且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
ok, _lic = licensing.ensure_license(account)
|
||||
if not ok:
|
||||
raise HTTPException(403, "授权已过期(最长离线 7 天),请联网刷新后重试")
|
||||
allowed = _meta._account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「插件配置 + 插件 UI」路由:带 UI 插件的底座通用约定。
|
||||
|
||||
两块能力(插件包内 ui/ 目录 + 本地配置存取):
|
||||
- GET/POST /api/plugin-config/{pid} per-plugin JSON 配置存取(落执行机本机
|
||||
%LOCALAPPDATA%\\37duAutomation\\plugin_configs\\,账号密码等个性化配置改一次永久生效)
|
||||
- GET /pui/{pid}[/path] 插件自带前端静态托管(源码态与打包态都从
|
||||
plugins/<pid>/ui/ 现读,插件 UI 更新只发插件包、不随壳子发版)
|
||||
鉴权与其他 API 一致:统一账户 cookie 会话(壳子内嵌 iframe 同源自动携带)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.session import _require_login
|
||||
from webhost.backend.plugins import PLUGINS, _PLUGINS_ROOT # noqa: SLF001 插件根单一真源
|
||||
|
||||
router = APIRouter()
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_UI_DIRNAME = "ui" # 插件包内前端目录名(与 plugin.json 的 "ui": true 声明配套)
|
||||
_MIME = {".html": "text/html", ".js": "application/javascript",
|
||||
".mjs": "application/javascript", ".css": "text/css",
|
||||
".json": "application/json", ".map": "application/json",
|
||||
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg",
|
||||
".gif": "image/gif", ".ico": "image/x-icon", ".woff": "font/woff",
|
||||
".woff2": "font/woff2", ".ttf": "font/ttf", ".txt": "text/plain"}
|
||||
|
||||
|
||||
def _check_ui_allowed(plugin_id: str) -> None:
|
||||
"""托管/配置读写的前置校验:插件已加载且在账号白名单内,否则 404(不泄露存在性)。"""
|
||||
try:
|
||||
PLUGINS.find(plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
if _st.ALLOWED is not None and plugin_id not in _st.ALLOWED:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
|
||||
|
||||
# ==================== per-plugin 本地配置存取 ====================
|
||||
def _config_path(plugin_id: str):
|
||||
return config.PLUGIN_CONFIG_DIR / f"{plugin_id}.json"
|
||||
|
||||
|
||||
@router.get("/api/plugin-config/{plugin_id}")
|
||||
def get_plugin_config(plugin_id: str, request: Request):
|
||||
"""读取插件本地配置;从未保存过返回空对象(前端用默认值兜底)。"""
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
path = _config_path(plugin_id)
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
@router.post("/api/plugin-config/{plugin_id}")
|
||||
async def save_plugin_config(plugin_id: str, request: Request):
|
||||
"""整体保存插件配置(前端提交完整表单对象,本地原子落盘)。"""
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
raise HTTPException(400, "配置体必须是 JSON 对象")
|
||||
if not isinstance(data, dict):
|
||||
raise HTTPException(400, "配置体必须是 JSON 对象")
|
||||
path = _config_path(plugin_id)
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
tmp.replace(path) # 原子替换,避免写一半被读到
|
||||
except OSError as exc:
|
||||
_LOGGER.warning("插件 %s 配置保存失败:%s", plugin_id, exc)
|
||||
raise HTTPException(500, "配置保存失败")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ==================== 插件 UI 静态托管 ====================
|
||||
def _serve_ui(plugin_id: str, rel: str, request: Request) -> FileResponse:
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
ui_root = (_PLUGINS_ROOT / plugin_id / _UI_DIRNAME).resolve()
|
||||
if not ui_root.is_dir():
|
||||
raise HTTPException(404, "该插件未提供前端界面")
|
||||
target = (ui_root / rel).resolve() if rel.strip() else ui_root / "index.html"
|
||||
if not target.is_relative_to(ui_root): # 防路径穿越(..、绝对路径拼接等)
|
||||
raise HTTPException(404, "not found")
|
||||
if target.is_dir():
|
||||
target = target / "index.html"
|
||||
if not target.is_file():
|
||||
# SPA 兜底:未知路径回 index.html(history 路由可用)
|
||||
target = ui_root / "index.html"
|
||||
if not target.is_file():
|
||||
raise HTTPException(404, "not found")
|
||||
media_type = (_MIME.get(target.suffix.lower())
|
||||
or mimetypes.guess_type(str(target))[0] or "application/octet-stream")
|
||||
# index.html 不缓存(插件更新后刷新即生效);带 hash 的静态资源可长缓存
|
||||
headers = {"Cache-Control": "no-cache" if target.name == "index.html"
|
||||
else "public, max-age=86400"}
|
||||
return FileResponse(str(target), media_type=media_type, headers=headers)
|
||||
|
||||
|
||||
@router.get("/pui/{plugin_id}")
|
||||
def plugin_ui_root(plugin_id: str, request: Request):
|
||||
return _serve_ui(plugin_id, "", request)
|
||||
|
||||
|
||||
@router.get("/pui/{plugin_id}/{path:path}")
|
||||
def plugin_ui_file(plugin_id: str, path: str, request: Request):
|
||||
return _serve_ui(plugin_id, path, request)
|
||||
@@ -63,13 +63,21 @@ def start_run(req: RunReq, request: Request) -> dict:
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start(_run_id):
|
||||
# start_fn 无参调用(scheduler 约定):run_id 由外层闭包捕获;
|
||||
# 之前签名带 _run_id 形参会因 TypeError 启动失败且被静默吞掉,运行记录永久卡 running
|
||||
def _start():
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.fields, _run_id),
|
||||
args=(plugin, req.fields, run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return _run_id
|
||||
_scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
return run_id
|
||||
r = _scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
if not r.get("ok"):
|
||||
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
|
||||
_st._set_run(run_id, status="error", result=None,
|
||||
error=r.get("error") or "启动失败")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": r.get("error") or "启动失败"})
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
_LOGGER.warning("等待 Chrome 安装完成超时")
|
||||
@@ -24,6 +24,11 @@ else:
|
||||
|
||||
PORT = 8799
|
||||
|
||||
# 插件本地配置目录:per-plugin JSON 持久化(账号密码/仓库编码等个性化配置)。
|
||||
# 放 %LOCALAPPDATA% 下:按 Windows 用户隔离、清浏览器缓存不丢、壳子升级不丢。
|
||||
PLUGIN_CONFIG_DIR = (Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "plugin_configs")
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
@@ -45,12 +50,17 @@ def _load_dotenv() -> None:
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
|
||||
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
|
||||
# ==================== 插件权限源(控制面拉取 + 本地缓存,见 cpapi._resolve_allowed) ====================
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
|
||||
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
|
||||
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
|
||||
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
|
||||
# ==================== 敏感凭证中心化下发(唯一来源:中心机下发/本地加密缓存) ====================
|
||||
# 钉钉扫码 URL 已改由控制面代理构造(/api/dingtalk/login-url),执行机不再消费下发的钉钉凭证值;
|
||||
# apply_creds 仅保留进程级覆盖存储,供未来每账号敏感值下发能力使用(当前无消费点)。
|
||||
# 启动时由 main.py 调 creds_sync.load() 从中心机拉取(RSA 解密)后经 apply_creds() 注入。
|
||||
_CREDS_OVERRIDE: dict = {}
|
||||
|
||||
|
||||
def apply_creds(values: dict) -> None:
|
||||
"""把中心机下发的敏感凭证写入进程级覆盖 dict(敏感值唯一来源,不做本地 .env 回退)。"""
|
||||
_CREDS_OVERRIDE.update(values or {})
|
||||
@@ -5,7 +5,10 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
@@ -16,32 +19,76 @@ from webhost.backend.core.session import _sess_account
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _resolve_allowed() -> set | None:
|
||||
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
|
||||
if config.PLUGIN_SOURCE != "controlplane" or not config.CONTROLPLANE_URL:
|
||||
_ALLOW_CACHE = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "plugin_allow.json")
|
||||
|
||||
|
||||
def _save_allowed_cache(ids: set) -> None:
|
||||
"""权限清单落盘缓存(登录拉取时写入,离线/中心机不可达时直接复用)。"""
|
||||
try:
|
||||
_ALLOW_CACHE.parent.mkdir(parents=True, exist_ok=True)
|
||||
_ALLOW_CACHE.write_text(json.dumps(sorted(ids), ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("插件权限清单缓存写入失败: %s", _exc)
|
||||
|
||||
|
||||
def _load_allowed_cache() -> set | None:
|
||||
"""读权限清单缓存;无缓存/损坏返回 None。"""
|
||||
if not _ALLOW_CACHE.is_file():
|
||||
return None
|
||||
if not config.CONTROLPLANE_ACCOUNT:
|
||||
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
|
||||
try:
|
||||
raw = json.loads(_ALLOW_CACHE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return {str(x) for x in (raw or [])}
|
||||
|
||||
|
||||
def _resolve_allowed() -> set:
|
||||
"""插件权限白名单(fail-closed,绝不回退全量):控制面拉取 + 本地缓存。
|
||||
|
||||
语义:
|
||||
- 未登录(无恢复会话账号)→ 无权限,返回空集(零权限,不加载任何插件);
|
||||
- 登录过 → 拉取账号插件清单并落盘缓存;后续离线直接复用缓存清单;
|
||||
- 有账号但离线且无缓存 → 空集(无权限依据,fail-closed 防越权)。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return set()
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
account = config.CONTROLPLANE_ACCOUNT or _sess_active_account()
|
||||
if not account:
|
||||
_LOGGER.info("未登录(无会话账号),插件零权限加载")
|
||||
return set()
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": config.CONTROLPLANE_ACCOUNT},
|
||||
headers=headers, timeout=5)
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", config.CONTROLPLANE_ACCOUNT,
|
||||
sorted(allowed) or "(空)")
|
||||
_LOGGER.info("控制面权限清单(%s):%s", account, sorted(allowed) or "(空)")
|
||||
_save_allowed_cache(allowed)
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
|
||||
return None
|
||||
except Exception as _exc: # noqa: BLE001 不可达/失败:缓存兜底,无缓存零权限
|
||||
cached = _load_allowed_cache()
|
||||
if cached is not None:
|
||||
_LOGGER.info("权限清单拉取失败,用本地缓存(%s):%s", account, _exc)
|
||||
return cached
|
||||
_LOGGER.warning("权限清单拉取失败且无缓存,插件零权限加载:%s", _exc)
|
||||
return set()
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
h = {"X-Admin-User": _sess_account(request)}
|
||||
"""构造到中心机的调用头:优先带「当前登录账号的云令牌」(登录时中心机签发,中心机
|
||||
_cloud_account 据此定位用户),不再依赖 CONTROLPLANE_TOKEN;X-Admin-User 仅作兜底。"""
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
h = {}
|
||||
account = _sess_account(request)
|
||||
if account:
|
||||
_cloud_tok = (_ACCT_CLOUD_TOKEN or {}).get(account)
|
||||
if _cloud_tok:
|
||||
h["Authorization"] = f"Bearer {_cloud_tok}"
|
||||
h["X-Admin-User"] = account
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
@@ -65,21 +112,36 @@ def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
def _sync_licensing(account: str) -> None:
|
||||
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
|
||||
|
||||
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
|
||||
逐资源容错:公钥/授权票据/管控清单各自 try,单个接口失败不阻断其余(成功部分照常落盘
|
||||
+ touch_sync),保证一次刷新尽量完整;全部失败也静默,调用方按本地缓存兜底。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
licensing.flush_offline_reports()
|
||||
got_any = False
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 公钥拉取失败不阻断授权/管控刷新
|
||||
_LOGGER.warning("中心机公钥拉取失败:%s", _exc)
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 授权票据拉取失败不阻断公钥/管控刷新
|
||||
_LOGGER.warning("离线授权票据拉取失败:%s", _exc)
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 管控清单拉取失败不阻断公钥/授权刷新
|
||||
_LOGGER.warning("管控清单拉取失败:%s", _exc)
|
||||
if got_any:
|
||||
licensing.flush_offline_reports()
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机敏感凭证:RSA 密钥对管理(私钥本机持久化,公钥上报中心机用于加密下发)。
|
||||
|
||||
- 首启生成 RSA-2048 密钥对,私钥 PKCS8(PEM) 落盘
|
||||
%LOCALAPPDATA%\\37duAutomation\\creds\\id_rsa.pem(公钥由私钥导出)。
|
||||
- 私钥必须在执行机本机可解(解密中心机下发的敏感凭证),故本机明文存私钥是必要权衡
|
||||
(与现有 %LOCALAPPDATA%\\37duAutomation\\.env 同级保护;如需更高级别可后续加 DPAPI,本期不做)。
|
||||
- 公钥上报中心机后,中心机用它 OAEP-SHA256 逐个加密敏感值下发,本机私钥解密。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_CREDS_DIR = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "creds")
|
||||
_PRIV_PATH = _CREDS_DIR / "id_rsa.pem"
|
||||
|
||||
|
||||
def _load_or_create() -> rsa.RSAPrivateKey:
|
||||
"""加载本机 RSA 私钥;不存在则生成 RSA-2048 并持久化(重启复用)。"""
|
||||
if _PRIV_PATH.is_file():
|
||||
try:
|
||||
_key = serialization.load_pem_private_key(_PRIV_PATH.read_bytes(), password=None)
|
||||
if isinstance(_key, rsa.RSAPrivateKey):
|
||||
return _key
|
||||
except (ValueError, TypeError, OSError) as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 RSA 私钥失败,重新生成: %s", _exc)
|
||||
_CREDS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
_PRIV_PATH.write_bytes(_key.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
return _key
|
||||
|
||||
|
||||
_priv = _load_or_create() # 进程内复用同一私钥
|
||||
|
||||
|
||||
def public_key_pem() -> str:
|
||||
"""本机 RSA 公钥 PEM(上报中心机用)。"""
|
||||
return _priv.public_key().public_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
||||
|
||||
|
||||
def decrypt(cipher_b64: str) -> str:
|
||||
"""用本机私钥 OAEP-SHA256 解密密文 base64 → 明文(与服务端 rsa_encrypt 对称)。"""
|
||||
_ct = base64.b64decode(cipher_b64)
|
||||
_pt = _priv.decrypt(_ct, padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(), label=None))
|
||||
return _pt.decode("utf-8")
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机敏感凭证下发与缓存:中心机在线拉取(RSA 解密) + 加密缓存(离线复用)。
|
||||
|
||||
流程:
|
||||
sync(): 有登录云令牌且中心机可达 →
|
||||
1. POST /api/admin/creds/register 上报本机 RSA 公钥(幂等 upsert,本人云令牌可登记)
|
||||
2. GET /api/admin/creds (Bearer) 拉取 {key: base64(RSA 密文)}——服务端仅管理员可拉,
|
||||
员工账号 403 会走缓存(本地无密文则为空,不影响业务)
|
||||
3. 本机私钥逐个解密 → 返回明文 dict
|
||||
4. 拉到的密文 JSON 原样写缓存 %LOCALAPPDATA%\\37duAutomation\\creds\\cache.json
|
||||
(落盘的是密文,叠加中心机加密层)
|
||||
load(): 中心机可达走 sync();不可达/无云令牌则读缓存密文用私钥解密(离线可用)。
|
||||
|
||||
敏感键白名单与服务端 config_push._ALLOWED_KEYS 保持一致(仅钉钉开放平台凭证;
|
||||
HR/OA 平台登录账号由本地加密存储 platform_accounts,不经中心机)。
|
||||
钉钉扫码 URL 已由控制面代理构造(/api/dingtalk/login-url),本模块下发的值当前无消费点,
|
||||
链路保留供未来每账号敏感值下发能力使用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.creds_store import decrypt, public_key_pem
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 与服务端 apis/config_push.py _ALLOWED_KEYS 保持一致(双重保障:下发限定范围)
|
||||
_ALLOWED_KEYS = (
|
||||
"DINGTALK_APPKEY", "DINGTALK_APPSECRET", "DINGTALK_AGENT_ID", "DINGTALK_CORP_ID",
|
||||
)
|
||||
|
||||
_CACHE_DIR = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "creds")
|
||||
_CACHE_FILE = _CACHE_DIR / "cache.json"
|
||||
|
||||
|
||||
def _cloud_token(account: str) -> str:
|
||||
"""当前账号的云端会话 token(登录时中心机签发,进程内存态;重启后需重新登录才有)。"""
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
return (_ACCT_CLOUD_TOKEN or {}).get(account) or ""
|
||||
|
||||
|
||||
def _headers(account: str) -> dict:
|
||||
h = {"Authorization": f"Bearer {_cloud_token(account)}"}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _save_cache(encrypted: dict) -> None:
|
||||
"""密文 JSON 原样落盘(落盘的是密文,叠加中心机加密层;离线用私钥解密)。"""
|
||||
try:
|
||||
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_CACHE_FILE.write_text(json.dumps(encrypted, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("敏感凭证缓存写入失败: %s", _exc)
|
||||
|
||||
|
||||
def _load_cache() -> dict:
|
||||
"""读缓存密文并用本机私钥解密为明文 dict;缺失/解密失败返回空 dict(不阻断)。"""
|
||||
if not _CACHE_FILE.is_file():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(_CACHE_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
out = {}
|
||||
for _k, _b64 in (raw or {}).items():
|
||||
if _k not in _ALLOWED_KEYS:
|
||||
continue
|
||||
try:
|
||||
out[_k] = decrypt(_b64)
|
||||
except Exception: # noqa: BLE001 单值解密失败跳过(如密钥更换后旧缓存)
|
||||
_LOGGER.warning("敏感凭证缓存解密失败: %s", _k)
|
||||
return out
|
||||
|
||||
|
||||
def sync(account: str) -> dict | None:
|
||||
"""中心机在线拉取并解密敏感凭证,返回明文 dict;不可用返回 None(走缓存兜底)。"""
|
||||
if not config.CONTROLPLANE_URL or not account or not _cloud_token(account):
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
# 1. 上报本机 RSA 公钥(幂等 upsert;中心机用该公钥加密下发)
|
||||
r = requests.post(f"{config.CONTROLPLANE_URL}/api/admin/creds/register",
|
||||
json={"account": account, "pubkey_pem": public_key_pem()},
|
||||
headers=_headers(account), timeout=10)
|
||||
r.raise_for_status()
|
||||
# 2. 拉取加密后的敏感凭证
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/admin/creds",
|
||||
headers=_headers(account), timeout=10)
|
||||
r.raise_for_status()
|
||||
encrypted = r.json().get("creds") or {}
|
||||
except Exception as _exc: # noqa: BLE001 中心机不可达/鉴权失败 → 走缓存
|
||||
_LOGGER.warning("中心机敏感凭证拉取失败(用本地缓存): %s", _exc)
|
||||
return None
|
||||
if not encrypted:
|
||||
return {}
|
||||
# 3. 本机私钥逐个解密
|
||||
out = {}
|
||||
for _k, _b64 in encrypted.items():
|
||||
if _k not in _ALLOWED_KEYS:
|
||||
continue
|
||||
try:
|
||||
out[_k] = decrypt(_b64)
|
||||
except Exception as _exc: # noqa: BLE001 单值解密失败跳过
|
||||
_LOGGER.warning("敏感凭证解密失败: %s", _k)
|
||||
# 4. 密文原样落盘缓存(离线复用)
|
||||
_save_cache(encrypted)
|
||||
return out
|
||||
|
||||
|
||||
def load(account: str = "") -> dict:
|
||||
"""获取当前账号敏感凭证明文:中心机可达走 sync();否则读缓存密文解密(离线可用)。
|
||||
|
||||
返回 dict[key]=明文,仅含成功解密项;空 dict 表示无可用的下发值(不阻断启动)。
|
||||
"""
|
||||
account = account or config.CONTROLPLANE_ACCOUNT
|
||||
if not account:
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
account = _sess_active_account()
|
||||
synced = sync(account)
|
||||
if synced is not None:
|
||||
return synced
|
||||
cached = _load_cache()
|
||||
if cached:
|
||||
_LOGGER.info("使用本地敏感凭证缓存(中心机不可达或无云令牌)")
|
||||
return cached
|
||||
@@ -125,6 +125,43 @@ def verify_control() -> dict:
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
|
||||
|
||||
# ==================== 授权周期(离线最多 LICENSE_TTL_DAYS 天) ====================
|
||||
def license_status() -> tuple[str, dict | None]:
|
||||
"""本地授权票据状态:("ok", payload) / ("missing", None) / ("invalid", None) / ("expired", payload)。
|
||||
|
||||
过期判定以票据内 expiresAt(控制面签发,issuedAt + 7 天)为基准;缺该字段一律视为过期
|
||||
(fail-safe,触发联网刷新,不因旧票据而永久放行)。
|
||||
"""
|
||||
if not license_path.is_file():
|
||||
return ("missing", None)
|
||||
try:
|
||||
lic = verify_license()
|
||||
except ValueError:
|
||||
return ("invalid", None)
|
||||
exp = lic.get("expiresAt")
|
||||
if not exp or time.time() > int(exp):
|
||||
return ("expired", lic)
|
||||
return ("ok", lic)
|
||||
|
||||
|
||||
def ensure_license(account: str) -> tuple[bool, dict | None]:
|
||||
"""确保本地授权票据可用:ok → (True, payload);否则联网刷新一次后复查。
|
||||
|
||||
刷新失败(离线/控制面不可达)→ (False, None)。这是「可见性/运行/平台登录」的统一授权门禁,
|
||||
过期且实际在线时会自动刷新恢复(用户无感),离线则拒绝并提示联网刷新。
|
||||
"""
|
||||
status, payload = license_status()
|
||||
if status == "ok":
|
||||
return True, payload
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _sync_licensing # 延迟导入,避免模块环
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 联网刷新失败(离线/控制面不可达)
|
||||
_LOGGER.warning("授权票据联网刷新失败(离线或控制面不可达):%s", _exc)
|
||||
status, payload = license_status()
|
||||
return (status == "ok"), payload
|
||||
|
||||
|
||||
# ==================== 缓存写读 ====================
|
||||
def save_license(ticket_json: dict | str) -> None:
|
||||
"""持久化授权票据。ticket 可为 {ticket,...} 或原始签名串。"""
|
||||
@@ -149,24 +186,24 @@ def save_control(ticket_json: dict | str) -> None:
|
||||
def run_check_allowed(plugin_id: str, account: str, online: bool) -> str | None:
|
||||
"""启动前校验链(离线/联网通用骨架),返回 None=可运行,否则返回拒绝原因字符串。
|
||||
|
||||
- 授权周期:本地票据须有效(7 天窗口,见 ensure_license);缺失/过期先联网刷新一次,
|
||||
仍不可用则拒绝(离线超期必须联网更新票据)。
|
||||
- 验签授权票据,校验该插件 canRun。
|
||||
- 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。
|
||||
- 离线:跳过强制更新 deadline 检查(不联网一直能用)。
|
||||
- 联网:额外校验强制更新 deadline 已过则拒启旧版本。
|
||||
"""
|
||||
ok, lic = ensure_license(account)
|
||||
if not ok:
|
||||
return "授权已过期(最长离线 7 天),请联网刷新后重试"
|
||||
|
||||
control = verify_control()
|
||||
if plugin_id in control.get("revokedPlugins", []):
|
||||
return "插件已被下架(revoked),禁止运行"
|
||||
if plugin_id in control.get("disabledPlugins", []):
|
||||
return "插件已被禁用(disabled),禁止运行"
|
||||
|
||||
# 授权:先验签本地授权票据(离线可用)
|
||||
try:
|
||||
lic = verify_license()
|
||||
except Exception as _exc: # noqa: BLE001 授权票据不可用
|
||||
return f"本地授权票据校验失败:{_exc}" if online else "本地授权票据校验失败"
|
||||
|
||||
lic_plugins = {p.get("pluginId"): p for p in lic.get("plugins", [])}
|
||||
lic_plugins = {p.get("pluginId"): p for p in (lic or {}).get("plugins", [])}
|
||||
grant = lic_plugins.get(plugin_id)
|
||||
if not grant:
|
||||
return f"账号 {account} 无插件「{plugin_id}」的授权"
|
||||
|
||||
@@ -12,7 +12,6 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -35,6 +34,7 @@ def _plugin_schema(p) -> dict:
|
||||
perms = (manifest or {}).get("permissions") or p.permissions
|
||||
return {"id": p.id, "name": name, "version": p.version,
|
||||
"description": description, "uses_month": getattr(p, "uses_month", False),
|
||||
"ui": bool((manifest or {}).get("ui")),
|
||||
"capabilities": caps, "permissions": perms, "fields": fields}
|
||||
|
||||
|
||||
@@ -64,6 +64,13 @@ def _fields_from_schema(schema: dict) -> list | None:
|
||||
elif t == "string" and "enum" in prop:
|
||||
item["type"] = "select"
|
||||
item["options"] = prop["enum"]
|
||||
elif t == "string" and prop.get("format") == "password":
|
||||
item["type"] = "password"
|
||||
elif t == "array":
|
||||
# 多选:items.enum 为预设选项;无 enum 则纯自由输入(前端 tags 可自建条目)
|
||||
item["type"] = "multiselect"
|
||||
if isinstance(prop.get("items"), dict) and "enum" in prop["items"]:
|
||||
item["options"] = prop["items"]["enum"]
|
||||
else:
|
||||
item["type"] = "text"
|
||||
d = prop.get("description")
|
||||
@@ -86,29 +93,4 @@ def _account_allowed_platforms(account: str) -> set | None:
|
||||
r.raise_for_status()
|
||||
return set(r.json().get("allowed", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _cloud_plugin_ids(account: str) -> set | None:
|
||||
"""已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。
|
||||
|
||||
降级策略(三态):
|
||||
- 200 → 返回账号允许的插件 id 集(真正按员工权限过滤)
|
||||
- 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露
|
||||
- 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5)
|
||||
"""
|
||||
token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None
|
||||
if not token or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
except Exception: # noqa: BLE001 云端不可达 → 离线兜底
|
||||
return None
|
||||
if r.status_code == 401:
|
||||
return set()
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
return {p["id"] for p in r.json().get("plugins", [])}
|
||||
return None
|
||||
@@ -5,6 +5,9 @@
|
||||
缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到
|
||||
plugins/<id>/ 原子替换;更新成功后由宿主重载插件注册表。
|
||||
|
||||
本地清理:云端清单可达时,本地存在但不在清单中的插件(中心机已删除/已收回
|
||||
授权)同步移除本地目录;清单不可达(离线)时不动本地,保证离线可继续运行。
|
||||
|
||||
降级策略:
|
||||
- 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行)
|
||||
- 单个插件下载/校验/解压失败 → 记 ERROR 跳过,不影响其它插件与本地旧版本
|
||||
@@ -17,6 +20,7 @@ import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
@@ -25,9 +29,13 @@ from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 30 # 包下载超时(秒)
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
@@ -145,14 +153,62 @@ def _install_pkg(plugin_id: str, content: bytes) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": []}
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
for p in manifest:
|
||||
pid = p.get("id", "")
|
||||
ver = p.get("version", "") or p.get("latest_version", "")
|
||||
@@ -179,7 +235,7 @@ def sync_plugins(account: str) -> dict:
|
||||
(result["updated"] if local else result["downloaded"]).append(pid)
|
||||
else:
|
||||
result["failed"].append(pid)
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 失败=%s",
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 清理=%s 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["failed"])
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
|
||||
@@ -87,4 +87,11 @@ def _require_login(request: Request) -> str:
|
||||
return account
|
||||
|
||||
|
||||
def _sess_active_account() -> str:
|
||||
"""取最近活跃的本机会话账号(重启恢复的会话;CONTROLPLANE_ACCOUNT 不再配置时的兜底)。"""
|
||||
with _SESS_LOCK:
|
||||
items = sorted(_SESS.values(), key=lambda _it: _it[1], reverse=True)
|
||||
return items[0][0] if items else ""
|
||||
|
||||
|
||||
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
@@ -1,13 +1,20 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机壳子(主程序)自动更新:自动下载新版安装包,由用户点击触发静默升级重启。
|
||||
"""执行机壳子(主程序)自动更新:检查 → 用户确认下载(带进度)→ 点击重启升级。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检查+下载:启动时后台检查控制面 /api/shell/version,版本落后则自动把新版安装包
|
||||
下载到 %LOCALAPPDATA%\\37duAutomation\\shell\\(本地缓存,不打断用户)。
|
||||
2. 应用:前端提示"发现新版本"后用户点击 → apply_update() 运行安装包
|
||||
1. 检查:启动时/每 30 分钟/手动"检查更新",只比对控制面 /api/shell/version,
|
||||
秒级返回"有新版/已是最新/不可达",不下载大包。发现新版后由前端提示用户,
|
||||
由用户决定是否下载(不默默后台拉包)。
|
||||
2. 下载:用户点击"立即下载" → 后台流式下载到
|
||||
%LOCALAPPDATA%\\37duAutomation\\shell\\(先写 .part 临时文件,完成校验后改名),
|
||||
进度(已下载/总量/百分比)写入状态供前端轮询展示。
|
||||
3. 应用:下载完成后前端提示"重启更新",用户点击 → apply_update() 运行安装包
|
||||
/VERYSILENT 静默覆盖安装,随后本进程退出,Inno CloseApplications 收尾,
|
||||
安装完成由 [Run] 自动重启新版本主程序。
|
||||
3. 离线/控制面不可达/校验失败:静默跳过,不影响使用。
|
||||
4. 离线/控制面不可达/校验失败:状态记录错误原因,前端提示,不影响使用。
|
||||
|
||||
并发控制:检查与下载各持独立锁(检查是 5s 的版本接口,下载是数百 MB 大包,
|
||||
两者互不阻塞)。下载内部再防重入,避免重复拉包。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -16,6 +23,7 @@ import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
@@ -25,8 +33,36 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存的安装包目录:独立于程序目录(升级时不被覆盖/清理)
|
||||
_SHELL_CACHE = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "shell"
|
||||
|
||||
# 检查互斥锁:启动/周期/手动三入口共用,检查期间视为"检查中"(pending_status.checking)
|
||||
_CHECK_LOCK = threading.Lock()
|
||||
# 下载互斥锁:防止并发重复下载同一大包
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待应用的新版本(模块内状态,供 update-status 查询)
|
||||
_PENDING: dict = {}
|
||||
_PENDING_VERSION = ""
|
||||
_PENDING_NOTES = ""
|
||||
|
||||
# 运行态(供前端轮询 update-status)
|
||||
_STATE: dict = {
|
||||
# 版本检查
|
||||
"checking": False, # 版本检查进行中(秒级,很快结束)
|
||||
"check_at": 0.0, # 最近一次检查完成时间
|
||||
"latest": "", # 云端最新版本
|
||||
"notes": "", # 云端最新版本更新说明
|
||||
"available": False, # 检测到可用新版本(当前 < 云端 且 尚未下载完成)
|
||||
"check_error": "", # 检查失败原因(控制面不可达/源码模式等)
|
||||
# 下载(流式,带进度)
|
||||
"dl_version": "", # 正在下载/刚下载完成的版本
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0, # 已下载字节
|
||||
"dl_total": 0, # 总字节(0 = 未知,无法算百分比)
|
||||
"dl_pct": 0, # 0-100
|
||||
"dl_error": "", # 下载失败原因
|
||||
"applying": False, # 正在静默安装升级
|
||||
}
|
||||
|
||||
_PERIODIC_INTERVAL = 30 * 60 # 周期检查间隔(秒)
|
||||
|
||||
|
||||
def local_shell_version() -> str:
|
||||
@@ -56,10 +92,10 @@ def _version_lt(a: str, b: str) -> bool:
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def check_and_download() -> dict | None:
|
||||
"""检查壳子更新并自动下载安装包到本地缓存。有可用更新返回 {version, notes};否则 None。"""
|
||||
cur = local_shell_version()
|
||||
if not cur or not config.CONTROLPLANE_URL:
|
||||
def fetch_cloud_version() -> dict | None:
|
||||
"""拉取控制面壳子版本信息;非打包运行/未配置/不可达返回 None(失败原因记入 _STATE)。"""
|
||||
if not local_shell_version() or not config.CONTROLPLANE_URL:
|
||||
_STATE["check_error"] = "源码开发模式,不参与自更新" if not local_shell_version() else "未配置中心机地址"
|
||||
return None
|
||||
import requests
|
||||
|
||||
@@ -67,38 +103,183 @@ def check_and_download() -> dict | None:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/version",
|
||||
headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
info = r.json()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001 离线/不可达
|
||||
_LOGGER.info("检查壳子更新失败(离线跳过):%s", _exc)
|
||||
_STATE["check_error"] = f"控制面不可达({_exc.__class__.__name__})"
|
||||
return None
|
||||
if not info.get("available") or not info.get("version"):
|
||||
return None
|
||||
cloud = str(info["version"])
|
||||
if not _version_lt(cur, cloud):
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 检查(只比对版本,不下载) =====================
|
||||
|
||||
def check_update() -> None:
|
||||
"""只检查版本:比对控制面最新版,写入 _STATE。秒级完成,不下载大包。"""
|
||||
if not _CHECK_LOCK.acquire(blocking=False):
|
||||
return # 已有检查在进行,沿用其状态
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/pkg",
|
||||
headers=_headers(), timeout=300)
|
||||
r.raise_for_status()
|
||||
data = r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载壳子安装包失败:%s", _exc)
|
||||
return None
|
||||
_STATE["checking"] = True
|
||||
cur = local_shell_version()
|
||||
info = fetch_cloud_version()
|
||||
_STATE["check_at"] = time.time()
|
||||
if not cur:
|
||||
_STATE["latest"] = ""
|
||||
_STATE["notes"] = ""
|
||||
_STATE["available"] = False
|
||||
return
|
||||
if not info:
|
||||
_STATE["available"] = False
|
||||
return
|
||||
cloud = str(info.get("version") or "")
|
||||
notes = str(info.get("notes") or "")
|
||||
_STATE["latest"] = cloud
|
||||
_STATE["notes"] = notes
|
||||
_STATE["check_error"] = ""
|
||||
if not cloud or not _version_lt(cur, cloud):
|
||||
# 已是最新:清掉"待下载"占位(若之前处于 failed,供用户重试的 available 也置 False)
|
||||
_STATE["available"] = False
|
||||
return
|
||||
_STATE["available"] = True
|
||||
# 缓存中已有该版本安装包 → 恢复为"已下载待应用",提示重启更新
|
||||
if cached_pkg(cloud) is not None:
|
||||
_restore_pending(cloud, notes)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
_CHECK_LOCK.release()
|
||||
|
||||
|
||||
def _restore_pending(cloud: str, notes: str) -> None:
|
||||
"""把已落盘的安装包恢复为待应用状态(重启后/下载完成后沿用)。"""
|
||||
global _PENDING_VERSION, _PENDING_NOTES
|
||||
_PENDING_VERSION = cloud
|
||||
_PENDING_NOTES = notes
|
||||
_STATE["dl_version"] = cloud
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_LOGGER.info("壳子新版本 %s 已在缓存中,等待用户重启更新", cloud)
|
||||
|
||||
|
||||
def start_check() -> None:
|
||||
"""后台线程触发一次检查(启动/手动入口):立即返回,结果经 pending_status 轮询获取。"""
|
||||
threading.Thread(target=check_update, daemon=True, name="shell-check").start()
|
||||
|
||||
|
||||
def start_periodic_check(interval: int = _PERIODIC_INTERVAL) -> None:
|
||||
"""常驻周期检查:壳子长开时也能自动发现新版本(只比对版本,不自动下载)。"""
|
||||
def _loop() -> None:
|
||||
while True:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
check_update()
|
||||
except Exception as _exc: # noqa: BLE001 周期失败不中断循环
|
||||
_LOGGER.warning("周期检查壳子更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_loop, daemon=True, name="shell-check-loop").start()
|
||||
|
||||
|
||||
# ===================== 下载(流式 + 进度) =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载新版本安装包(后台线程)。已有下载/已完成则直接沿用,不重复拉包。"""
|
||||
cur = local_shell_version()
|
||||
if not cur:
|
||||
return
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_VERSION:
|
||||
return
|
||||
info = fetch_cloud_version()
|
||||
if not info:
|
||||
return
|
||||
cloud = str(info.get("version") or "")
|
||||
if not cloud or not _version_lt(cur, cloud):
|
||||
return
|
||||
if cached_pkg(cloud) is not None:
|
||||
_restore_pending(cloud, str(info.get("notes") or ""))
|
||||
return
|
||||
# 占位防重入,随后后台流式下载
|
||||
_STATE["dl_version"] = cloud
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(cloud, info), daemon=True,
|
||||
name="shell-download").start()
|
||||
_LOGGER.info("开始下载壳子新版本 %s", cloud)
|
||||
|
||||
|
||||
def _download(cloud: str, info: dict) -> None:
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(cloud, info)
|
||||
except Exception as _exc: # noqa: BLE001 下载异常兜底
|
||||
_LOGGER.exception("下载壳子安装包异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part(cloud)
|
||||
|
||||
|
||||
def _download_locked(cloud: str, info: dict) -> None:
|
||||
import requests
|
||||
|
||||
# 中心机 version 接口新增 url 字段:有则直连内网文件服务器下载大包(无鉴权);
|
||||
# 为空回退中心机 /api/shell/pkg(该路径带 X-API-Token)。
|
||||
inner_url = (info.get("url") or "").strip()
|
||||
if inner_url:
|
||||
url = inner_url
|
||||
dl_headers = {}
|
||||
else:
|
||||
url = f"{config.CONTROLPLANE_URL}/api/shell/pkg"
|
||||
dl_headers = _headers()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(data).hexdigest() != expect:
|
||||
_LOGGER.error("壳子安装包 sha256 校验失败,放弃更新")
|
||||
return None
|
||||
tmp = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe.part"
|
||||
pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe"
|
||||
try:
|
||||
_SHELL_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe"
|
||||
pkg.write_bytes(data)
|
||||
with requests.get(url, headers=dl_headers, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载壳子安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("壳子安装包 sha256 校验失败,放弃更新")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("壳子安装包落盘失败:%s", _exc)
|
||||
return None
|
||||
_PENDING["version"] = cloud
|
||||
_PENDING["notes"] = info.get("notes", "")
|
||||
_LOGGER.info("壳子新版本已下载待应用:%s → %s(%d 字节)", cur, cloud, len(data))
|
||||
return {"version": cloud, "notes": _PENDING["notes"]}
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_restore_pending(cloud, str(info.get("notes") or ""))
|
||||
|
||||
|
||||
def _cleanup_part(cloud: str) -> None:
|
||||
try:
|
||||
(_SHELL_CACHE / f"setup-37du-host-{cloud}.exe.part").unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def cached_pkg(version: str) -> Path | None:
|
||||
@@ -108,13 +289,32 @@ def cached_pkg(version: str) -> Path | None:
|
||||
|
||||
|
||||
def pending_status() -> dict:
|
||||
"""当前更新状态(供前端提示):当前版本 / 待应用新版本 / 是否已下载。"""
|
||||
"""当前更新状态(供前端展示与轮询):兼容旧字段,并补充下载进度/可用版本。"""
|
||||
global _PENDING_VERSION, _PENDING_NOTES
|
||||
cur = local_shell_version()
|
||||
downloaded = bool(_PENDING_VERSION) and cached_pkg(_PENDING_VERSION) is not None
|
||||
if not downloaded:
|
||||
_PENDING_VERSION = ""
|
||||
_PENDING_NOTES = ""
|
||||
return {
|
||||
"current": local_shell_version(),
|
||||
"new": _PENDING.get("version", ""),
|
||||
"notes": _PENDING.get("notes", ""),
|
||||
"downloaded": bool(_PENDING.get("version"))
|
||||
and cached_pkg(_PENDING.get("version", "")) is not None,
|
||||
"current": cur,
|
||||
"new": _PENDING_VERSION if downloaded else "",
|
||||
"notes": _PENDING_NOTES if downloaded else "",
|
||||
"downloaded": downloaded,
|
||||
"available": bool(_STATE["available"]),
|
||||
"latest": _STATE.get("latest", ""),
|
||||
"checked_at": _STATE.get("check_at", 0),
|
||||
"checking": bool(_STATE.get("checking", False)),
|
||||
"error": _STATE.get("check_error", ""),
|
||||
"applying": bool(_STATE.get("applying", False)),
|
||||
"dl": {
|
||||
"version": _STATE.get("dl_version", ""),
|
||||
"status": _STATE.get("dl_status", "idle"),
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -123,10 +323,11 @@ def apply_update() -> None:
|
||||
|
||||
注意:本函数在返回前 os._exit(0) 退出整个进程,调用方无需继续处理。
|
||||
"""
|
||||
version = _PENDING.get("version", "")
|
||||
version = _PENDING_VERSION
|
||||
pkg = cached_pkg(version)
|
||||
if not pkg:
|
||||
raise FileNotFoundError(f"未找到已下载的安装包:setup-37du-host-{version}.exe")
|
||||
_STATE["applying"] = True
|
||||
_LOGGER.info("开始静默升级到 %s:%s", version, pkg)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"],
|
||||
|
||||
@@ -12,8 +12,10 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
@@ -29,6 +31,7 @@ from webhost.backend.plugins import load_plugins
|
||||
from webhost.backend.apis import admin as api_admin
|
||||
from webhost.backend.apis import dingtalk as api_dingtalk
|
||||
from webhost.backend.apis import meta as api_meta
|
||||
from webhost.backend.apis import plugin_ui as api_plugin_ui
|
||||
from webhost.backend.apis import runs as api_runs
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -36,48 +39,73 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(config.CONTROLPLANE_ACCOUNT)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", config.CONTROLPLANE_ACCOUNT)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
# 启动即检查插件更新:有恢复的会话账号时后台同步(每次启动确定是否更新,不阻塞启动)
|
||||
try:
|
||||
from webhost.backend.core.session import _SESS
|
||||
_accts = {_a for _, (_a, _t) in _SESS.items()}
|
||||
except Exception: # noqa: BLE001
|
||||
_accts = set()
|
||||
if _accts:
|
||||
_acct = next(iter(_accts))
|
||||
|
||||
def _boot_sync() -> None:
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
sync_plugins(_acct)
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
_LOGGER.info("启动插件更新完成(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 更新失败不阻断启动
|
||||
_LOGGER.warning("启动插件更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_sync, daemon=True).start()
|
||||
# 启动即检查壳子(主程序)更新:有新版本自动下载,前端提示后由用户点击重启升级
|
||||
def _boot_shell_check() -> None:
|
||||
try:
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if config.CONTROLPLANE_URL:
|
||||
# 敏感凭证中心化下发:优先服务端在线拉取(RSA 解密),否则用本地缓存密文解密;
|
||||
# 失败不阻断启动(.env 回退 / 等待下次登录后刷新)
|
||||
try:
|
||||
from webhost.backend.core.shell_updater import check_and_download
|
||||
check_and_download()
|
||||
except Exception as _exc: # noqa: BLE001 检查失败不阻断启动
|
||||
_LOGGER.warning("启动壳子更新检查失败:%s", _exc)
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load()
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
_LOGGER.info("中心机敏感凭证下发完成(%s 个键)", len(_creds))
|
||||
except Exception as _exc: # noqa: BLE001 下发失败不影响启动
|
||||
_LOGGER.warning("加载中心机敏感凭证失败:%s", _exc)
|
||||
# 账号:.env 不再配置 CONTROLPLANE_ACCOUNT,取最近活跃的本机会话账号(重启恢复)
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
_acct = config.CONTROLPLANE_ACCOUNT or _sess_active_account()
|
||||
if _acct:
|
||||
try:
|
||||
_sync_licensing(_acct)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
# 启动即检查插件更新:有恢复的会话账号时后台同步(每次启动确定是否更新,不阻塞启动)
|
||||
try:
|
||||
from webhost.backend.core.session import _SESS
|
||||
_accts = {_a for _, (_a, _t) in _SESS.items()}
|
||||
except Exception: # noqa: BLE001
|
||||
_accts = set()
|
||||
if _accts:
|
||||
_acct = next(iter(_accts))
|
||||
|
||||
threading.Thread(target=_boot_shell_check, daemon=True).start()
|
||||
yield
|
||||
def _boot_sync() -> None:
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins, SYNC_LOCK
|
||||
with SYNC_LOCK:
|
||||
sync_plugins(_acct)
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
_LOGGER.info("启动插件更新完成(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 更新失败不阻断启动
|
||||
_LOGGER.warning("启动插件更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_sync, daemon=True).start()
|
||||
# 启动即检查壳子(主程序)更新:有新版本自动下载,前端提示后由用户点击重启升级;
|
||||
# 并常驻周期检查(默认 30 分钟),壳子长开时也能自动发现新版本
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
_shell_updater.start_check()
|
||||
_shell_updater.start_periodic_check()
|
||||
yield
|
||||
except BaseException:
|
||||
# lifespan 失败会被 uvicorn 吞成 SystemExit(3);frozen 下 stderr 已重定向 devnull,
|
||||
# 报错无处可看:崩溃现场记入 webhost.log,frozen 时并追加到 exe 同级 crash.log
|
||||
import traceback
|
||||
_tb = traceback.format_exc()
|
||||
_LOGGER.error("启动初始化失败:\n%s", _tb)
|
||||
if getattr(sys, "frozen", False):
|
||||
try:
|
||||
with open(Path(sys.executable).parent / "crash.log", "a", encoding="utf-8") as _f:
|
||||
_f.write("\n[lifespan]\n" + _tb)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
@@ -87,6 +115,7 @@ app.include_router(api_admin.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_runs.router)
|
||||
app.include_router(api_plugin_ui.router)
|
||||
|
||||
|
||||
if config.DIST.exists():
|
||||
|
||||
@@ -41,7 +41,13 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _discover_modules() -> list:
|
||||
"""发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。"""
|
||||
"""发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。
|
||||
|
||||
全新安装时 plugins/ 尚不存在(插件由登录后按权限自下载,不随安装包分发),
|
||||
必须视为"零插件"而不是抛错——否则 lifespan 失败导致壳子无法启动。
|
||||
"""
|
||||
if not _PLUGINS_ROOT.is_dir():
|
||||
return []
|
||||
names: list = []
|
||||
seen: set = set()
|
||||
for d in sorted(_PLUGINS_ROOT.iterdir()):
|
||||
@@ -66,8 +72,11 @@ def load_plugins(allowed: set = None, reload: bool = False) -> None:
|
||||
"""
|
||||
if reload:
|
||||
PLUGINS.clear()
|
||||
# base 是 PLUGINS 注册表的单例宿主:reload 时绝不能删,否则插件模块重新
|
||||
# import base 会得到全新空注册表,注册的插件对 meta/runs 等引用方全部不可见。
|
||||
for _m in [m for m in sys.modules
|
||||
if m.startswith(_PKG_NAME + ".") and m != _PKG_NAME]:
|
||||
if m.startswith(_PKG_NAME + ".") and m != _PKG_NAME
|
||||
and m != _PKG_NAME + ".base"]:
|
||||
del sys.modules[_m]
|
||||
for _mod in _discover_modules():
|
||||
if allowed is not None and _mod not in allowed:
|
||||
|
||||
Reference in New Issue
Block a user