Files
37duAutomation/webhost/backend/main.py
T
puddy 65540fb121 feat: 新增控制面管理功能,优化插件加载与消息通知
- 新增内网插件控制面服务,实现统一账户、权限管理与插件分发
- 重构后端插件加载逻辑,支持按账号动态权限白名单加载
- 优化XQ0001排班异常提醒文案与推送群配置
- 新增前端管理界面与登录态会话管理
- 新增插件上传、账号管理等后台管理接口
2026-09-09 11:31:41 +08:00

353 lines
13 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 logging
import os
import socket
import threading
import uuid
from contextlib import asynccontextmanager
from datetime import datetime
from pathlib import Path
from fastapi import FastAPI, File, HTTPException, Request, Response, UploadFile, 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.hub import HUB
from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装
from webhost.backend.plugins.base import RunContext
PORT = 8799
DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist"
_LOGGER = logging.getLogger(__name__)
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
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: dict[str, str] = {}
_SESS_LOCK = threading.Lock()
def _sess_account(request: Request) -> str:
"""从请求 cookie 会话解析当前登录账号;未登录返回空串。"""
token = request.cookies.get(SESSION_COOKIE, "")
with _SESS_LOCK:
return _SESS.get(token, "")
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, result, error}
RUNS: dict = {}
RUN_LOCK = threading.Lock()
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
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 源则按账号权限白名单加载
load_plugins(_resolve_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()
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 _cp_call("GET", "/api/admin/overview", headers=_cp_headers(request))
@app.get("/api/admin/admins")
def admin_list(request: Request) -> dict:
return _cp_call("GET", "/api/admin/admins", headers=_cp_headers(request))
@app.get("/api/admin/accounts")
def admin_accounts(request: Request) -> dict:
return _cp_call("GET", "/api/admin/accounts", headers=_cp_headers(request))
@app.post("/api/admin/account")
def admin_account_create(body: dict, request: Request) -> dict:
return _cp_call("POST", "/api/admin/account",
headers={**_cp_headers(request), "Content-Type": "application/json"},
json=body)
@app.post("/api/admin/account/update")
def admin_account_update(body: dict, request: Request) -> dict:
return _cp_call("POST", "/api/admin/account/update",
headers={**_cp_headers(request), "Content-Type": "application/json"},
json=body)
@app.post("/api/admin/account/reset_pwd")
def admin_account_reset(body: dict, request: Request) -> dict:
return _cp_call("POST", "/api/admin/account/reset_pwd",
headers={**_cp_headers(request), "Content-Type": "application/json"},
json=body)
@app.post("/api/admin/account/delete")
def admin_account_delete(body: dict, request: Request) -> dict:
return _cp_call("POST", "/api/admin/account/delete",
headers={**_cp_headers(request), "Content-Type": "application/json"},
json=body)
@app.post("/api/admin/plugin/delete")
def admin_plugin_delete(body: dict, request: Request) -> dict:
return _cp_call("POST", "/api/admin/plugin/delete",
headers={**_cp_headers(request), "Content-Type": "application/json"},
json=body)
@app.post("/api/admin/account_plugins")
def admin_grant(body: dict, request: Request) -> dict:
return _cp_call("POST", "/api/admin/account_plugins",
headers={**_cp_headers(request), "Content-Type": "application/json"},
json=body)
@app.post("/api/admin/pkg")
async def admin_upload(plugin_id: str, version: str, name: str = "",
upload: UploadFile = File(...), request: Request = None) -> dict:
"""前端上传插件包:接收文件并转发给统一后端 multipart 发布。"""
content = await upload.read()
files = {"upload": (upload.filename or "pkg.zip", content,
upload.content_type or "application/octet-stream")}
params = {"plugin_id": plugin_id, "name": name or plugin_id, "version": version}
return _cp_call("POST", "/api/admin/pkg", params=params,
headers=_cp_headers(request), files=files)
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}
@app.get("/api/meta")
def meta() -> dict:
plugins = [_plugin_schema(p) for p in PLUGINS]
platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid)}
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:
"""真实登录:需先通过统一账户登录(有会话)。复用有效 cookies 或浏览器自动化登录(滑块)。"""
_require_login(request)
plat = PLATFORMS.get(pid)
if not plat:
raise HTTPException(404, "平台不存在")
return platform_auth.login(pid)
def _run_target(plugin, fields: dict, run_id: str) -> None:
ctx = RunContext(HUB, run_id=run_id, plugin_id=plugin.id, auth=platform_auth)
try:
result = plugin.run(fields, ctx)
with RUN_LOCK:
RUNS[run_id] = {"status": "done", "result": result, "error": None}
HUB.publish({"t": "run_done", "run_id": run_id, "ok": True})
except Exception as e: # noqa: BLE001 全局兜底,推送失败给前端
with RUN_LOCK:
RUNS[run_id] = {"status": "error", "result": None, "error": str(e)}
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": str(e)})
@app.post("/api/runs", status_code=202)
def start_run(req: RunReq, request: Request) -> dict:
_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", "result": None, "error": None}
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
"at": datetime.now().strftime("%H:%M:%S")})
threading.Thread(target=_run_target, args=(plugin, req.fields, run_id),
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:
_require_login(request)
with RUN_LOCK:
run = RUNS.get(run_id)
if not run:
raise HTTPException(404, "运行不存在")
return run
@app.websocket("/ws")
async def ws(websocket: WebSocket):
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")