feat(controlplane): 完成多页面管理台重构与平台权限控制

1. 重构控制面前端为多页面路由架构,拆分出概览/插件/账号/权限管理页面
2. 引入Element Plus组件库优化UI样式与交互
3. 新增平台登录权限校验,支持按账号授权HR/OA平台访问
4. 新增平台登出接口与个人中心功能
5. 完善账号管理、插件授权相关API与UI交互
6. 新增防火墙、启停、自启动脚本与部署文档
This commit is contained in:
2026-09-10 15:03:21 +08:00
parent 924f572a18
commit 863f818740
47 changed files with 38994 additions and 632 deletions
+13
View File
@@ -68,6 +68,19 @@ def login(pid: str) -> dict:
"message": (result or {}).get("message", "")}
def logout(pid: str) -> dict:
"""登出平台:删除共享 cookies 文件,使该平台登录态失效。
返回 {id, label, online}
"""
if pid not in _COOKIE_DEFS:
raise PlatformAuthError(f"未知平台: {pid}")
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
if os.path.exists(path):
os.remove(path)
return {"id": pid, "label": _LABELS[pid], "online": False}
def build_session(pid: str) -> "requests.Session":
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
+149 -55
View File
@@ -16,6 +16,7 @@ import socket
import subprocess
import sys
import threading
import time
import uuid
from contextlib import asynccontextmanager
from datetime import datetime
@@ -27,6 +28,7 @@ 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 为注册表,启动时显式填装
@@ -63,17 +65,26 @@ 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,进程内保持,供代理转发账号。
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
SESSION_COOKIE = "cp_session"
_SESS: dict[str, str] = {}
_SESS_TTL = 24 * 3600 # 会话空闲有效期 24h(惰性过期,防长期运行无限累积)
_SESS: dict[str, tuple] = {}
_SESS_LOCK = threading.Lock()
def _sess_account(request: Request) -> str:
"""从请求 cookie 会话解析当前登录账号;未登录返回空串。"""
def _sess_account(request) -> str:
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理)。"""
token = request.cookies.get(SESSION_COOKIE, "")
with _SESS_LOCK:
return _SESS.get(token, "")
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:
@@ -88,11 +99,34 @@ def _require_login(request: Request) -> str:
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
for p in platform_auth.platforms()}
# 运行会话:run_id -> {status, result, error}
# 运行会话: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
@@ -153,7 +187,9 @@ def _cp_call(method: str, path: str, **kw) -> dict:
async def lifespan(app: FastAPI):
HUB.bind(asyncio.get_running_loop())
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
load_plugins(_resolve_allowed())
global ALLOWED
ALLOWED = _resolve_allowed()
load_plugins(ALLOWED)
yield
@@ -193,7 +229,7 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
return r
token = uuid.uuid4().hex
with _SESS_LOCK:
_SESS[token] = b.account.strip()
_SESS[token] = (b.account.strip(), time.time())
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
return {**r, "account": b.account.strip()}
@@ -233,22 +269,59 @@ def _plugin_schema(p) -> dict:
"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() -> dict:
plugins = [_plugin_schema(p) for p in PLUGINS]
platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid)}
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:
"""真实登录:需先通过统一账户登录(有会话)。复用有效 cookies 或浏览器自动化登录(滑块)。"""
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
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.login(pid)
return platform_auth.logout(pid)
def _run_target(plugin, fields: dict, run_id: str) -> None:
@@ -260,6 +333,28 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
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")
@@ -270,22 +365,6 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
"pct": int(ev.get("pct", 0))})
try:
proc = subprocess.Popen(
[sys.executable, "-u", str(runner), "--plugin", plugin.id,
"--run", run_id],
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, encoding="utf-8",
errors="replace",
)
except Exception as e: # noqa: BLE001 子进程拉起失败
with RUN_LOCK:
RUNS[run_id] = {"status": "error", "result": None,
"error": f"拉起执行子进程失败: {e}"}
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
"error": f"拉起执行子进程失败: {e}"})
return
_result: dict = {}
_rlock = threading.Lock()
@@ -327,35 +406,35 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
except subprocess.TimeoutExpired:
timed_out = True
try:
proc.kill()
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
proc.wait(timeout=5)
except (subprocess.TimeoutExpired, OSError):
pass
with _rlock:
ev = dict(_result)
if ev:
ok = bool(ev.get("ok"))
with RUN_LOCK:
RUNS[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)已强制终止"
with RUN_LOCK:
RUNS[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})且未返回结果"
with RUN_LOCK:
RUNS[run_id] = {"status": "error", "result": None, "error": msg}
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
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:
_require_login(request)
account = _require_login(request)
try:
plugin = PLUGINS.find(req.plugin_id)
except KeyError:
@@ -364,26 +443,41 @@ def start_run(req: RunReq, request: Request) -> dict:
with RUN_LOCK:
if len(RUNS) >= MAX_RUNS:
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
RUNS[run_id] = {"status": "running", "result": None, "error": None}
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")})
threading.Thread(target=_run_target, args=(plugin, req.fields, run_id),
daemon=True, name=f"run-{plugin.id}").start()
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:
_require_login(request)
account = _require_login(request)
with RUN_LOCK:
run = RUNS.get(run_id)
if not run:
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)
+5 -1
View File
@@ -55,6 +55,10 @@ def _run() -> int:
if not plugin_id:
_emit({"ev": "result", "ok": False, "error": "缺少 --plugin 参数"})
return 2
# 宿主透传的插件白名单:与宿主进程加载集保持一致(未传 = 全量)
allowed_arg = (sys.argv[sys.argv.index("--allowed") + 1]
if "--allowed" in sys.argv else "")
allowed = {s for s in allowed_arg.split(",") if s} if allowed_arg else None
# fields 经 stdin 传入(单行 JSON)
fields: dict = {}
@@ -78,7 +82,7 @@ def _run() -> int:
_emit({"ev": "progress", "pct": int(max(0, min(100, pct)))})
try:
load_plugins()
load_plugins(allowed)
plugin = PLUGINS.find(plugin_id)
ctx = _ChildContext(run_id=args.get("--run", ""), plugin_id=plugin_id,
auth=platform_auth)
+99
View File
@@ -0,0 +1,99 @@
# -*- coding: utf-8 -*-
"""Windows Job Object 封装:插件执行子进程整树托管。
- KILL_ON_JOB_CLOSE:句柄关闭/宿主崩溃时,作业内全部进程(含 DrissionPage 拉起的
浏览器等孙进程)一并终止,杜绝超时强杀后残留孤儿进程;
- PROCESS_MEMORY_LIMIT:作业级内存上限兜底,防插件内存爬升拖垮底座。
非 Windows 平台所有方法安全降级为 no-op。
"""
from __future__ import annotations
import ctypes
import logging
import sys
_LOGGER = logging.getLogger(__name__)
_AVAILABLE = sys.platform == "win32"
if _AVAILABLE:
try:
_K32 = ctypes.WinDLL("kernel32", use_last_error=True)
except AttributeError: # 非 Windows 误导入
_AVAILABLE = False
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x0000_2000
_JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x0000_0100
_PROCESS_SET_QUOTA = 0x0100
_PROCESS_TERMINATE = 0x0001
if _AVAILABLE:
class _IO_COUNTERS(ctypes.Structure):
_fields_ = [(n, ctypes.c_uint64) for n in (
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
class _BASIC_LIMIT_INFO(ctypes.Structure):
_fields_ = [
("PerProcessUserTimeLimit", ctypes.c_int64),
("PerJobUserTimeLimit", ctypes.c_int64),
("LimitFlags", ctypes.c_uint32),
("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t),
("ActiveProcessLimit", ctypes.c_uint32),
("Affinity", ctypes.c_size_t),
("PriorityClass", ctypes.c_uint32),
("SchedulingClass", ctypes.c_uint32),
]
class _EXT_LIMIT_INFO(ctypes.Structure):
_fields_ = [
("BasicLimitInformation", _BASIC_LIMIT_INFO),
("IoInfo", _IO_COUNTERS),
("ProcessMemoryLimit", ctypes.c_size_t),
("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t),
("PeakJobMemoryUsed", ctypes.c_size_t),
]
class Job:
"""一次性的插件子进程作业。用法:job = Job(); job.assign(proc); …; job.terminate()/close()。"""
def __init__(self, max_mem_mb: int = 0):
self._h = None
if not _AVAILABLE:
return
h = _K32.CreateJobObjectW(None, None)
if not h:
_LOGGER.warning("创建 Job Object 失败(winerror=%s),退化为无作业托管", ctypes.get_last_error())
return
info = _EXT_LIMIT_INFO()
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
if max_mem_mb > 0:
info.BasicLimitInformation.LimitFlags |= _JOB_OBJECT_LIMIT_PROCESS_MEMORY
info.ProcessMemoryLimit = max_mem_mb * 1024 * 1024
if not _K32.SetInformationJobObject(
h, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
ctypes.byref(info), ctypes.sizeof(info)):
_LOGGER.warning("设置 Job Object 限制失败(winerror=%s)", ctypes.get_last_error())
self._h = h
def assign(self, proc) -> None:
"""把子进程(及其后代)纳入作业托管。"""
if not self._h:
return
if not _K32.AssignProcessToJobObject(self._h, int(proc._handle)):
_LOGGER.warning("子进程纳入 Job Object 失败(winerror=%s)", ctypes.get_last_error())
def terminate(self, exit_code: int = 1) -> None:
"""终止作业内全部进程(整树强杀,含浏览器等孙进程)。"""
if self._h:
_K32.TerminateJobObject(self._h, exit_code)
def close(self) -> None:
"""关闭作业句柄;KILL_ON_JOB_CLOSE 保证句柄消失后作业内进程全部退出。"""
if self._h:
_K32.CloseHandle(self._h)
self._h = None