feat(controlplane): 完成多页面管理台重构与平台权限控制
1. 重构控制面前端为多页面路由架构,拆分出概览/插件/账号/权限管理页面 2. 引入Element Plus组件库优化UI样式与交互 3. 新增平台登录权限校验,支持按账号授权HR/OA平台访问 4. 新增平台登出接口与个人中心功能 5. 完善账号管理、插件授权相关API与UI交互 6. 新增防火墙、启停、自启动脚本与部署文档
This commit is contained in:
+149
-55
@@ -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)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user