Files
37duAutomation/webhost/backend/main.py
T
puddy ba24c29d53 refactor: 项目重命名为37du自动化工作台,完成全链路更新
本次提交完成了项目从"业务场景工具集"到"自动化工作台"的全链路重命名:
1.  更新所有页面标题、应用名称配置
2.  重构前端登录页UI与交互逻辑,新增启动加载动画
3.  移除旧版钉钉登录相关API与代码
4.  优化控制面板后台统计接口的SQL查询与字段映射
5.  新增agent_cli命令行管理工具,支持插件与账号权限管理
6.  修复后端插件权限校验逻辑,新增云端权限拉取能力
7.  更新控制面登录页面样式与交互体验
2026-09-14 00:34:54 +08:00

930 lines
39 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 secrets
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.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from urllib.parse import urlencode
from webhost.backend import auth as platform_auth
from webhost.backend import licensing
from webhost.backend import scheduler as _scheduler
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", "")
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
SESSION_COOKIE = "cp_session"
# 会话空闲有效期:7 天滑动续期(每次有效请求刷新 TTL;天天用永不重登,超期需重登)
_SESS_TTL = 7 * 24 * 3600
_SESS: dict[str, tuple] = {}
_SESS_LOCK = threading.Lock()
# 本机会话落盘文件:重启后端不丢会话(兑现"双击壳直接进插件页、不必每次重登")
_SESS_FILE = Path(__file__).resolve().parents[1] / "_cp_sessions.json"
def _sess_persist():
"""把本机会话快照落盘为首存(token → [account, 最近活跃ts]),进程重启后仍有效。"""
try:
with _SESS_LOCK:
_payload = {t: [a, int(_ts)] for t, (a, _ts) in _SESS.items()}
_SESS_FILE.write_text(json.dumps(_payload, ensure_ascii=False), encoding="utf-8")
except OSError as _exc: # noqa: BLE001
_LOGGER.warning("本机会话持久化失败: %s", _exc)
def _sess_load():
"""启动时从磁盘恢复本机会话(惰性丢弃已过期条)。"""
if not _SESS_FILE.is_file():
return
try:
_raw = json.loads(_SESS_FILE.read_text(encoding="utf-8"))
except (OSError, ValueError):
return
_now = time.time()
with _SESS_LOCK:
for _t, _it in (_raw or {}).items():
try:
_a, _ts = _it[0], float(_it[1])
except (KeyError, IndexError, TypeError, ValueError):
continue
if _now - _ts <= _SESS_TTL:
_SESS[_t] = (_a, _ts)
def _sess_account(request) -> str:
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理并落盘)。"""
token = request.cookies.get(SESSION_COOKIE, "")
account = ""
with _SESS_LOCK:
item = _SESS.get(token)
if item:
_account, _ts = item
if time.time() - _ts <= _SESS_TTL:
_SESS[token] = (_account, time.time()) # 滑动续期
account = _account
else:
_SESS.pop(token, None)
if account:
_sess_persist() # 滑动续期也落盘,重启后仍有效
return account
def _require_login(request: Request) -> str:
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
account = _sess_account(request)
if not account:
raise HTTPException(401, "未登录:请先登录统一账户")
return account
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
# 平台登录态:标签/展示名来自 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
# ==================== 产品化:离线授权同步 + 单活调度终止注册表 ====================
def _sync_licensing(account: str) -> None:
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
"""
if not CONTROLPLANE_URL or not account:
return
import requests
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
r = requests.get(f"{CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
r.raise_for_status()
licensing.cache_public_key(r.json().get("pub", ""))
r = requests.get(f"{CONTROLPLANE_URL}/api/me/license",
params={"account": account}, headers=headers, timeout=5)
r.raise_for_status()
licensing.save_license(r.json())
r = requests.get(f"{CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
r.raise_for_status()
licensing.save_control(r.json())
licensing.flush_offline_reports()
@asynccontextmanager
async def lifespan(app: FastAPI):
HUB.bind(asyncio.get_running_loop())
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
global ALLOWED
ALLOWED = _resolve_allowed()
load_plugins(ALLOWED)
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
licensing.init(CONTROLPLANE_URL, threading.Lock())
_scheduler.init_active()
if CONTROLPLANE_URL:
try:
_sync_licensing(CONTROLPLANE_ACCOUNT)
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", CONTROLPLANE_ACCOUNT)
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
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)。
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
不影响员工正常进入插件页(前端以 account 非空判登录)。
"""
account = _sess_account(request)
if not account:
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
try:
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
if r.get("account") == account:
return r
except HTTPException:
pass
return {"account": account, "is_admin": False, "dept": "", "nickname": ""}
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())
_sess_persist()
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
if CONTROLPLANE_URL:
try:
_sync_licensing(b.account.strip())
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return {**r, "account": b.account.strip()}
class _DingTalkIn(BaseModel):
account: str # 钉钉工号(作为统一账号)
nickname: str = "" # 钉钉姓名
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
@app.post("/api/admin/dingtalk/login")
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
if not d.account:
raise HTTPException(400, "工号不能为空")
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
"""
r = _cp_call(
"POST", "/api/admin/dingtalk/auth",
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
acct = r.get("account") or account
token = uuid.uuid4().hex
with _SESS_LOCK:
_SESS[token] = (acct, time.time())
_sess_persist()
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
if CONTROLPLANE_URL:
try:
_sync_licensing(acct)
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
class _InlineIn(BaseModel):
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
@app.post("/api/admin/dingtalk/inline")
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
"""
if not d.code.strip():
raise HTTPException(400, "缺少扫码截图码")
if not CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
info = _cp_call(
"POST", "/api/admin/dingtalk/sns",
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
json={"code": d.code.strip()})
account = (info.get("account") or "").strip()
if not account:
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
@app.get("/api/admin/dingtalk/inline_qr")
def admin_dingtalk_inline_qr(request: Request) -> dict:
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
if not CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
return _cp_call(
"GET", "/api/admin/dingtalk/inline_qr",
params={"back": back},
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}))
# ==================== v3 钉钉直连接登录:/api/auth/dingtalk + /auth/done(§2.1,待 §0 验证后实测) ====================
# 浏览器跳转模型:壳生成 state → 打开钉钉授权URL(redirect_uri=http://localhost:8799/auth/done)
# → 用户本机浏览器带回 code+state → 壳校验 state → POST 云端 /auth/exchange{code} 换工号+云端token → 建本机会话。
# 云端只参与换 token,AppSecret 不出云端;会话存本机、重启不掉(见上方 _SESS 持久化)。
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
_LOGIN_LOCK = threading.Lock()
# account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2)
_ACCT_CLOUD_TOKEN: dict[str, str] = {}
def _login_state_new() -> str:
with _LOGIN_LOCK:
_now = time.time()
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
_LOGIN_STATES.pop(s, None)
state = secrets.token_urlsafe(24)
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
return state
def _login_state_take(state: str) -> bool:
with _LOGIN_LOCK:
exp = _LOGIN_STATES.pop(state, None)
return bool(exp and exp >= time.time())
def _auth_done_page(text: str) -> HTMLResponse:
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
<body style="font-family:sans-serif;text-align:center;padding:60px">
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
@app.get("/api/auth/dingtalk")
def auth_dingtalk_url() -> dict:
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
if not DINGTALK_APP_KEY:
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
if not CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
state = _login_state_new()
redirect_uri = f"http://localhost:{PORT}/auth/done"
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
"redirect_uri": redirect_uri,
"response_type": "code",
"client_id": DINGTALK_APP_KEY,
"scope": "openid",
"prompt": "consent",
"state": state})
return {"url": login_url, "state": state}
@app.get("/auth/done")
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
"""
if error:
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
if not (code and state) or not _login_state_take(state):
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
try:
info = _cp_call("POST", "/auth/exchange", json={"code": code})
except HTTPException as e:
return _auth_done_page(f"登录失败:{e.detail}")
account = (info.get("account") or "").strip()
if not account or not info.get("exists"):
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
_token = uuid.uuid4().hex
with _SESS_LOCK:
_SESS[_token] = (account, time.time())
_sess_persist()
if info.get("token"):
_ACCT_CLOUD_TOKEN[account] = info["token"]
resp = RedirectResponse("/")
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
if CONTROLPLANE_URL:
try:
_sync_licensing(account)
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return resp
# ==================== 钉钉真实扫码:扫码URL + 静默回调页 ====================
# 扫码 URL 指向中心机 /api/admin/dingtalk/scan(back 回跳到本机 /cb);
# 扫码成功 → 中心机 /cb 302 回本机 /cb?account=&nickname= → 本页静默调 dingtalk/login 建会话
# → 刷新父窗口(登录完成)。身份源为钉钉+中心机(可信),与账号密码登录同会话机制。
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
<script>
(async function(){
var q = new URLSearchParams(location.search);
var account = q.get('account') || '';
var nickname = q.get('nickname') || '';
if (account) {
try {
await fetch('/api/admin/dingtalk/login', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({ account: account, nickname: nickname })
});
} catch (e) {}
}
try { window.opener && window.opener.location.reload(); } catch (e) {}
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
})();
</script></body></html>"""
@app.get("/api/admin/dingtalk/qr")
def dingtalk_qr(request: Request) -> dict:
"""返回中心机扫码登录 URL。
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
"""
if not CONTROLPLANE_URL:
return {"url": ""}
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
return {"url": f"{CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
@app.get("/api/admin/dingtalk/cb")
def dingtalk_cb() -> HTMLResponse:
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
return HTMLResponse(_DINGTALK_CB_HTML)
@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)
_sess_persist()
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:
"""组装插件元数据(manifest 驱动)。
plugin.json(与插件代码同目录)为权威:存在则其字段/能力/权限优先,仅当缺失时才
回退到 ScenePlugin 类上的 fields/capabilities,保证离线与旧插件兼容。
"""
manifest = _read_own_manifest(p)
name = (manifest or {}).get("name") or p.name
description = (manifest or {}).get("description")
if description is None:
description = p.description
fields = _fields_from_schema((manifest or {}).get("fields")) if manifest else None
if fields is None:
fields = p.fields
caps = (manifest or {}).get("capabilities") or p.capabilities
perms = (manifest or {}).get("permissions") or p.permissions
return {"id": p.id, "name": name, "version": p.version,
"description": description, "uses_month": getattr(p, "uses_month", False),
"capabilities": caps, "permissions": perms, "fields": fields}
def _read_own_manifest(p) -> dict | None:
"""读取与插件注册模块同目录的 plugin.json;缺文件或解析失败返回 None(不阻断)。"""
try:
mod = sys.modules.get(type(p).__module__)
jar = (mod and Path(mod.__file__).resolve().parent / "plugin.json")
if not jar or not jar.is_file():
return None
return json.loads(jar.read_text(encoding="utf-8"))
except Exception: # noqa: BLE001
return None
def _fields_from_schema(schema: dict) -> list | None:
"""JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options}]。"""
if not schema or schema.get("type") != "object" or not schema.get("properties"):
return None
out = []
for key, prop in schema["properties"].items():
item = {"key": key, "label": prop.get("title", key),
"default": prop.get("default", "")}
t = prop.get("type", "string")
if t == "integer" or t == "number":
item["type"] = "int"
elif t == "string" and "enum" in prop:
item["type"] = "select"
item["options"] = prop["enum"]
else:
item["type"] = "text"
d = prop.get("description")
if d:
item["description"] = d
out.append(item)
return out
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
def _cloud_plugin_ids(account: str) -> set | None:
"""已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。
降级策略(三态):
- 200 → 返回账号允许的插件 id 集(真正按员工权限过滤)
- 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露
- 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5)
"""
token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None
if not token or not CONTROLPLANE_URL:
return None
import requests
try:
r = requests.get(f"{CONTROLPLANE_URL}/api/plugins",
headers={"Authorization": f"Bearer {token}"}, timeout=5)
except Exception: # noqa: BLE001 云端不可达 → 离线兜底
return None
if r.status_code == 401:
return set()
if r.status_code != 200:
return None
return {p["id"] for p in r.json().get("plugins", [])}
@app.get("/api/meta")
def meta(request: Request) -> dict:
account = _sess_account(request)
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
if account:
allowed = _cloud_plugin_ids(account)
plugins = ([_plugin_schema(p) for p in PLUGINS if p.id in allowed]
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
else [_plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
else:
plugins = []
allowed_plats = _account_allowed_platforms(account) if account else None
platforms = [{"id": pid, "label": m["label"],
"online": platform_auth.is_online(pid),
# 已登录时按账号白名单;未登录/中心机不可达默认展示
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
for pid, m in PLATFORMS.items()]
return {
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
"controlplane": CONTROLPLANE_URL,
"appName": "37du 自动化工作台",
"dingtalkScan": bool(DINGTALK_APP_KEY),
"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:
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
def _report_run(plugin_id: str, run_id: str) -> None:
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
try:
with RUN_LOCK:
run = RUNS.get(run_id) or {}
account = run.get("account", "")
status = "done" if run.get("status") == "done" else \
("running" if run.get("status") == "running" else "error")
msg = run.get("error") or ""
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
licensing.report(account=account, device_id="",
plugin_id=plugin_id, version=run.get("version", ""),
status=status, msg=msg, duration_sec=duration)
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
_LOGGER.warning("运行上报失败:%s", _exc)
@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, "插件不存在")
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
online = licensing.is_online()
deny = licensing.run_check_allowed(plugin.id, account, online)
if deny:
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
raise HTTPException(403, deny)
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,
"version": getattr(plugin, "version", "0"),
"started": time.time(),
"result": None, "error": None}
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
"at": datetime.now().strftime("%H:%M:%S")})
licensing.report(account=account, device_id="", plugin_id=plugin.id,
version=getattr(plugin, "version", "0"), status="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:
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
if _scheduler._is_busy():
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": "INFO",
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
def _start(_run_id):
threading.Thread(target=_run_target,
args=(plugin, req.fields, _run_id),
daemon=True, name=f"exec-{plugin.id}").start()
return _run_id
_scheduler.request_start(account, plugin.id,
getattr(plugin, "version", "0"), _start)
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")