feat: 新增控制面管理功能,优化插件加载与消息通知

- 新增内网插件控制面服务,实现统一账户、权限管理与插件分发
- 重构后端插件加载逻辑,支持按账号动态权限白名单加载
- 优化XQ0001排班异常提醒文案与推送群配置
- 新增前端管理界面与登录态会话管理
- 新增插件上传、账号管理等后台管理接口
This commit is contained in:
2026-09-09 11:31:41 +08:00
parent 53913f0c7d
commit 5419ae4234
13 changed files with 1214 additions and 37 deletions
+222 -7
View File
@@ -9,6 +9,8 @@
from __future__ import annotations
import asyncio
import logging
import os
import socket
import threading
import uuid
@@ -16,19 +18,48 @@ from contextlib import asynccontextmanager
from datetime import datetime
from pathlib import Path
from fastapi import FastAPI, HTTPException, WebSocket
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 pydantic import BaseModel
from webhost.backend import auth as platform_auth
from webhost.backend.hub import HUB
from webhost.backend.plugins import PLUGINS # noqa: F401 触发注册
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()}
@@ -44,9 +75,61 @@ class RunReq(BaseModel):
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
@@ -54,6 +137,135 @@ 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),
@@ -69,8 +281,9 @@ def meta() -> dict:
@app.post("/api/platforms/{pid}/login")
def login(pid: str) -> dict:
"""真实登录:复用有效 cookies 或浏览器自动化登录(滑块),秒级~分钟级阻塞。"""
def login(pid: str, request: Request) -> dict:
"""真实登录:需先通过统一账户登录(有会话)。复用有效 cookies 或浏览器自动化登录(滑块)。"""
_require_login(request)
plat = PLATFORMS.get(pid)
if not plat:
raise HTTPException(404, "平台不存在")
@@ -91,7 +304,8 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
@app.post("/api/runs", status_code=202)
def start_run(req: RunReq) -> dict:
def start_run(req: RunReq, request: Request) -> dict:
_require_login(request)
try:
plugin = PLUGINS.find(req.plugin_id)
except KeyError:
@@ -109,7 +323,8 @@ def start_run(req: RunReq) -> dict:
@app.get("/api/runs/{run_id}")
def get_run(run_id: str) -> dict:
def get_run(run_id: str, request: Request) -> dict:
_require_login(request)
with RUN_LOCK:
run = RUNS.get(run_id)
if not run:
+4 -5
View File
@@ -48,13 +48,12 @@ def _discover_modules() -> list:
def load_plugins(allowed: set = None) -> None:
"""动态加载插件。allowed 为空 = 全量;否则仅加载白名单内的插件。
"""动态加载插件。allowed 为 None = 全量;否则为严格白名单(空集 = 零权限,全不加载)。
单插件加载失败记 ERROR(含堆栈首行)后跳过,不拖垮整体启动。
"""
allowed = allowed if allowed is not None else set()
for _mod in _discover_modules():
if allowed and _mod not in allowed:
if allowed is not None and _mod not in allowed:
_LOGGER.info("插件 %s 不在权限白名单,跳过加载", _mod)
continue
try:
@@ -64,5 +63,5 @@ def load_plugins(allowed: set = None) -> None:
traceback.format_exc(limit=1))
# 触发加载(阶段一:全量;阶段二改由 main.py 显式调用并传入权限白名单)
load_plugins()
# 注意:这里不再 import 时自动加载。由宿主(main.py)在应用启动时显式调用
# load_plugins(allowed) 一次性加载,以便阶段二可传入按账号动态计算的权限白名单。