Files
37duAutomation/webhost/backend/main.py
T
puddy 863f818740 feat(controlplane): 完成多页面管理台重构与平台权限控制
1. 重构控制面前端为多页面路由架构,拆分出概览/插件/账号/权限管理页面
2. 引入Element Plus组件库优化UI样式与交互
3. 新增平台登录权限校验,支持按账号授权HR/OA平台访问
4. 新增平台登出接口与个人中心功能
5. 完善账号管理、插件授权相关API与UI交互
6. 新增防火墙、启停、自启动脚本与部署文档
2026-09-10 15:03:21 +08:00

497 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""webhost 宿主:FastAPI 后端。
- 承载平台登录态(复用 desktop/shared 的共享登录态单一真源,真实登录/校验)
- 场景插件注册表 + 表单 schema
- 执行 run 到 worker 线程,经 /ws 广播 日志/进度/完成
- 挂载前端构建产物(frontend/dist)实现单产物
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import socket
import subprocess
import sys
import threading
import time
import uuid
from contextlib import asynccontextmanager
from datetime import datetime
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, Response, WebSocket
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from webhost.backend import auth as platform_auth
from webhost.backend import winjob as _winjob
from webhost.backend.hub import HUB
from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装
PORT = 8799
DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist"
_LOGGER = logging.getLogger(__name__)
# ==================== 配置固化:加载本模块 env(webhost/.env;免命令行传参;环境变量优先) ====================
def _load_dotenv() -> None:
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
env_path = Path(__file__).resolve().parents[1] / ".env"
if not env_path.is_file():
return
try:
for _ln in env_path.read_text(encoding="utf-8").splitlines():
_line = _ln.strip()
if not _line or _line.startswith("#") or "=" not in _line:
continue
_k, _v = _line.split("=", 1)
_k, _v = _k.strip(), _v.strip()
if _k and _k not in os.environ:
os.environ[_k] = _v
except OSError as _exc: # noqa: BLE001
_LOGGER.warning("读取 .env 失败: %s", _exc)
_load_dotenv()
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
SESSION_COOKIE = "cp_session"
_SESS_TTL = 24 * 3600 # 会话空闲有效期 24h(惰性过期,防长期运行无限累积)
_SESS: dict[str, tuple] = {}
_SESS_LOCK = threading.Lock()
def _sess_account(request) -> str:
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理)。"""
token = request.cookies.get(SESSION_COOKIE, "")
with _SESS_LOCK:
item = _SESS.get(token)
if not item:
return ""
account, ts = item
if time.time() - ts > _SESS_TTL:
_SESS.pop(token, None)
return ""
_SESS[token] = (account, time.time()) # 滑动续期
return account
def _require_login(request: Request) -> str:
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
account = _sess_account(request)
if not account:
raise HTTPException(401, "未登录:请先登录统一账户")
return account
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
for p in platform_auth.platforms()}
# 运行会话:run_id -> {status, account, result, error}
RUNS: dict = {}
RUN_LOCK = threading.Lock()
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
ALLOWED: set | None = None
# 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢
_NS_LOCKS: dict[str, threading.Lock] = {}
_NS_GUARD = threading.Lock()
def _ns_gate(platform: str) -> threading.Lock:
key = (platform or "").strip() or "local"
with _NS_GUARD:
if key not in _NS_LOCKS:
_NS_LOCKS[key] = threading.Lock()
return _NS_LOCKS[key]
def _set_run(run_id: str, **kw) -> None:
"""更新运行记录字段(保留 account 等既有键)。"""
with RUN_LOCK:
run = RUNS.get(run_id)
if run is not None:
run.update(kw)
class RunReq(BaseModel):
plugin_id: str
fields: dict = {}
def _resolve_allowed() -> set | None:
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
if PLUGIN_SOURCE != "controlplane" or not CONTROLPLANE_URL:
return None
if not CONTROLPLANE_ACCOUNT:
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
return None
import requests
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
try:
r = requests.get(f"{CONTROLPLANE_URL}/api/plugins",
params={"account": CONTROLPLANE_ACCOUNT},
headers=headers, timeout=5)
r.raise_for_status()
allowed = {p["id"] for p in r.json().get("plugins", [])}
_LOGGER.info("控制面权限清单(%s):%s", CONTROLPLANE_ACCOUNT,
sorted(allowed) or "(空)")
return allowed
except Exception as _exc: # noqa: BLE001
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
return None
# ==================== 统一后端(数据库 API)代理:底座前端访问统一后端的唯一通道 ====================
# 底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
def _cp_headers(request: Request) -> dict:
h = {"X-Admin-User": _sess_account(request)}
if CONTROLPLANE_TOKEN:
h["X-API-Token"] = CONTROLPLANE_TOKEN
return h
def _cp_call(method: str, path: str, **kw) -> dict:
if not CONTROLPLANE_URL:
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
import requests
r = requests.request(method, f"{CONTROLPLANE_URL}{path}", timeout=30, **kw)
try:
body = r.json()
except ValueError:
body = {"detail": r.text[:300]}
if r.status_code >= 400:
raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}"))
return body
@asynccontextmanager
async def lifespan(app: FastAPI):
HUB.bind(asyncio.get_running_loop())
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
global ALLOWED
ALLOWED = _resolve_allowed()
load_plugins(ALLOWED)
yield
app = FastAPI(title="37du Web Host", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
@app.get("/api/admin/me")
def admin_me(request: Request) -> dict:
"""当前登录账号是否为管理员(会话 cookie)。统一后端不可达时视为非管理员。"""
account = _sess_account(request)
if not account:
return {"account": "", "is_admin": False}
try:
return _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
except HTTPException:
return {"account": account, "is_admin": False}
class _LoginIn(BaseModel):
account: str
password: str
@app.post("/api/admin/login")
def admin_login(b: _LoginIn, response: Response) -> dict:
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
try:
r = _cp_call("POST", "/api/admin/auth",
headers={"X-Admin-User": b.account.strip(),
**({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
"Content-Type": "application/json"},
json={"account": b.account, "password": b.password})
except HTTPException as e:
raise e
if not r.get("ok"):
return r
token = uuid.uuid4().hex
with _SESS_LOCK:
_SESS[token] = (b.account.strip(), time.time())
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
return {**r, "account": b.account.strip()}
@app.post("/api/admin/logout")
def admin_logout(request: Request, response: Response) -> dict:
"""登出:清除会话 cookie 与内存会话。"""
token = request.cookies.get(SESSION_COOKIE, "")
with _SESS_LOCK:
_SESS.pop(token, None)
response.delete_cookie(SESSION_COOKIE)
return {"ok": True}
class _PwdIn(BaseModel):
account: str
old_password: str
new_password: str
@app.post("/api/admin/password")
def admin_password(b: _PwdIn, request: Request) -> dict:
return _cp_call("POST", "/api/admin/password",
headers={**_cp_headers(request), "Content-Type": "application/json"},
json=b.model_dump())
@app.get("/api/admin/overview")
def admin_overview(request: Request) -> dict:
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
return {"plugins": [], "accounts": [], "admins": []}
def _plugin_schema(p) -> dict:
return {"id": p.id, "name": p.name, "version": p.version,
"description": p.description, "uses_month": getattr(p, "uses_month", False),
"fields": p.fields}
def _account_allowed_platforms(account: str) -> set | None:
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
if not CONTROLPLANE_URL:
return None
import requests
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
try:
r = requests.get(f"{CONTROLPLANE_URL}/api/platforms/allowed",
params={"account": account}, headers=headers, timeout=5)
r.raise_for_status()
return set(r.json().get("allowed", []))
except Exception: # noqa: BLE001
return None
@app.get("/api/meta")
def meta(request: Request) -> dict:
account = _sess_account(request)
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据)
plugins = [_plugin_schema(p) for p in PLUGINS] if account else []
allowed = _account_allowed_platforms(account) if account else None
platforms = [{"id": pid, "label": m["label"],
"online": platform_auth.is_online(pid),
# 已登录时按账号白名单;未登录/中心机不可达默认展示
"allowed": (pid in allowed) if allowed is not None else True}
for pid, m in PLATFORMS.items()]
return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins}
@app.post("/api/platforms/{pid}/login")
def login(pid: str, request: Request) -> dict:
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
account = _require_login(request)
plat = PLATFORMS.get(pid)
if not plat:
raise HTTPException(404, "平台不存在")
allowed = _account_allowed_platforms(account)
if allowed is None:
raise HTTPException(503, "控制面不可达,无法校验平台权限")
if pid not in allowed:
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
return platform_auth.login(pid)
@app.post("/api/platforms/{pid}/logout")
def platform_logout(pid: str, request: Request) -> dict:
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
_require_login(request)
plat = PLATFORMS.get(pid)
if not plat:
raise HTTPException(404, "平台不存在")
return platform_auth.logout(pid)
def _run_target(plugin, fields: dict, run_id: str) -> None:
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
"""
runner = Path(__file__).with_name("plugin_runner.py")
root = Path(__file__).resolve().parents[2]
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
if ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
cmd += ["--allowed", ",".join(sorted(ALLOWED))]
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
job = _winjob.Job(max_mem_mb=max_mem_mb)
try:
proc = subprocess.Popen(
cmd,
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, encoding="utf-8",
errors="replace",
)
job.assign(proc)
except Exception as e: # noqa: BLE001 子进程拉起失败
job.close()
_set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
"error": f"拉起执行子进程失败: {e}"})
return
def _publish_event(ev: dict):
t = ev.get("ev")
if t == "log":
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
elif t == "progress":
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
"pct": int(ev.get("pct", 0))})
_result: dict = {}
_rlock = threading.Lock()
def _drain_out():
for line in proc.stdout:
line = line.strip()
if not line:
continue
try:
ev = json.loads(line)
except ValueError:
continue
if ev.get("ev") in ("log", "progress"):
_publish_event(ev)
elif ev.get("ev") == "result":
with _rlock:
_result.update(ev)
def _drain_err():
for line in proc.stderr:
line = line.strip()
if line:
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": "ERROR", "msg": line})
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
t_out.start(); t_err.start()
try:
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
proc.stdin.close()
except OSError:
pass
timed_out = False
try:
proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
timed_out = True
try:
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
proc.wait(timeout=5)
except (subprocess.TimeoutExpired, OSError):
pass
try:
with _rlock:
ev = dict(_result)
if ev:
ok = bool(ev.get("ok"))
_set_run(run_id, status="done" if ok else "error",
result=ev.get("result"), error=ev.get("error"))
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
"error": ev.get("error")})
elif timed_out:
msg = f"插件执行超时({timeout}s)已强制终止"
_set_run(run_id, status="error", result=None, error=msg)
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
else:
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
_set_run(run_id, status="error", result=None, error=msg)
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
finally:
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
@app.post("/api/runs", status_code=202)
def start_run(req: RunReq, request: Request) -> dict:
account = _require_login(request)
try:
plugin = PLUGINS.find(req.plugin_id)
except KeyError:
raise HTTPException(404, "插件不存在")
run_id = uuid.uuid4().hex
with RUN_LOCK:
if len(RUNS) >= MAX_RUNS:
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
RUNS[run_id] = {"status": "running", "account": account,
"result": None, "error": None}
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
"at": datetime.now().strftime("%H:%M:%S")})
def _queued():
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
gate = _ns_gate(plugin.platform)
if gate.locked():
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": "INFO",
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
with gate:
_run_target(plugin, req.fields, run_id)
threading.Thread(target=_queued, daemon=True,
name=f"run-{plugin.id}").start()
return {"run_id": run_id}
@app.get("/api/runs/{run_id}")
def get_run(run_id: str, request: Request) -> dict:
account = _require_login(request)
with RUN_LOCK:
run = RUNS.get(run_id)
if not run or run.get("account") != account: # 仅属主可读运行结果
raise HTTPException(404, "运行不存在")
return run
@app.websocket("/ws")
async def ws(websocket: WebSocket):
if not _sess_account(websocket): # WS 握手需有效统一账户会话
await websocket.close(code=1008)
return
await HUB.connect(websocket)
if DIST.exists():
app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web")
def _port_free(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(("127.0.0.1", port)) != 0
if __name__ == "__main__":
import uvicorn
print(f"[webhost] port {PORT} free = {_port_free(PORT)}")
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="info")