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()
|
||||
|
||||
Reference in New Issue
Block a user