Files
37duAutomation/desktop/controlplane/apis/plugins.py
T
puddy b32f8e8fe2 feat: 新增xq0031_xq0032 ERP报表导出插件,完成功能与基建更新
1. 新增xq0031_xq0032插件:包含前后端源码、打包脚本、配置文件与插件元数据
2. 新增内网文件服务器组件:exe、启停脚本、打包脚本与配置
3. 新增敏感凭证RSA加密下发能力与存储结构
4. 新增大文件源管理表与相关API
5. 优化登录流程与会话管理,新增Chrome自动化安装工具链
6. 清理废弃插件与示例代码
7. 更新版本号至1.1.3,完善安装包与.gitignore配置
2026-09-17 12:42:44 +08:00

309 lines
14 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 -*-
"""客户端(部署端)拉取接口:插件清单 / 平台白名单 / 版本清单 / 包下载 / 离线票据 / 运行上报。
权限隔离 + 插件分发 + 版本比对,客户端只经本接口获取能力,不直连数据库。
"""
from __future__ import annotations
import json
import secrets
import time
from fastapi import APIRouter, Header, HTTPException, Query
from fastapi.responses import FileResponse
from controlplane import config, crypto, schemas
from controlplane.core.auth import _check_token, _cloud_account
from controlplane.core.db import _audit, _db, _now
router = APIRouter()
def _account_disabled(acct: str) -> bool:
"""账号是否已停用(停用后机器侧一律不给插件/授权)。"""
with _db() as conn:
row = conn.execute("SELECT status FROM accounts WHERE account = %s", (acct,)).fetchone()
return bool(row) and not bool(row["status"])
@router.get("/api/plugins", response_model=dict)
def plugins(account: str = Query(default="", description="账号(旧底座按此传)"),
x_api_token: str = Header(default="", alias="X-API-Token"),
authorization: str = Header(default="", alias="Authorization")) -> dict:
"""按账号返回可用插件清单(权限隔离):无权限的账号返回空列表。
§2.2:优先用云端会话 token(Authorization: Bearer <token>)解出工号,不再明文传 account;
兜底兼容旧底座 `account?` + X-API-Token 的调用方式。
"""
acct = _cloud_account(authorization)
if not acct:
_check_token(x_api_token)
acct = (account or "").strip()
if not acct:
raise HTTPException(400, "缺少有效会话或 account")
if _account_disabled(acct):
return {"account": acct, "plugins": []}
with _db() as conn:
rows = conn.execute(
"""
SELECT p.id, p.name, p.latest_version AS version
FROM plugins p
JOIN account_plugins ap ON ap.plugin_id = p.id
WHERE ap.account = %s
ORDER BY p.id
""",
(acct,),
).fetchall()
return {"account": acct, "plugins": [schemas.PluginOut(**dict(r)).model_dump() for r in rows]}
@router.get("/api/platforms/allowed", response_model=dict)
def platforms_allowed(account: str = Query(default="", description="账号(旧底座按此传)"),
x_api_token: str = Header(default="", alias="X-API-Token"),
authorization: str = Header(default="", alias="Authorization")) -> dict:
"""按账号返回可登录平台白名单(与插件权限同模式)。支持云端会话 token 或旧底座 account 两种身份来源。"""
acct = _cloud_account(authorization)
if not acct:
_check_token(x_api_token)
acct = (account or "").strip()
if not acct:
raise HTTPException(400, "缺少有效会话或 account")
if _account_disabled(acct):
return {"account": acct, "allowed": []}
with _db() as conn:
rows = conn.execute(
"SELECT platform_id FROM account_platforms WHERE account = %s ORDER BY platform_id",
(acct,),
).fetchall()
return {"account": acct, "allowed": [dict(r)["platform_id"] for r in rows]}
# ==================== 产品化:客户端(部署端)拉取接口 ====================
@router.get("/api/me/pubkey")
def me_pubkey() -> dict:
"""下发中心机公钥(PEM 文本),部署端首次联网时缓存用于离线验签。"""
return {"pub": crypto._pubkey_pem().decode("ascii"), "algo": "ed25519"}
@router.get("/api/me/license")
def me_license(account: str = Query(...), device: str = Query(default=""),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""签发离线授权票据:基于当前账号的插件级授权(can_run)快照,Ed25519 签名。
票据含 expiresAt(issuedAt + LICENSE_TTL_DAYS 天):执行机最多离线该天数,
超时须联网刷新票据后才可继续使用(每次刷新重置窗口)。
"""
_check_token(x_api_token)
if not account.strip():
raise HTTPException(400, "account 不能为空")
if _account_disabled(account.strip()):
raise HTTPException(403, "账号已停用,无法获取授权")
with _db() as conn:
rows = conn.execute(
"""
SELECT g.plugin_id, g.can_download, g.can_run, p.name, p.status, p.latest_version
FROM account_plugins g
JOIN plugins p ON p.id = g.plugin_id
WHERE g.account = %s
""",
(account.strip(),),
).fetchall()
plugins = [{"pluginId": r["plugin_id"], "name": r["name"],
"canDownload": bool(r["can_download"]), "canRun": bool(r["can_run"]),
"status": r["status"], "latestVersion": r["latest_version"]}
for r in rows]
issued_at = _now()
expires_at = int(time.time()) + config.LICENSE_TTL_DAYS * 24 * 3600
blob = crypto._sign_blob({"userId": account.strip(), "deviceId": device or "",
"issuedAt": issued_at, "expiresAt": expires_at, "plugins": plugins})
return {"ticket": blob, "plugins": plugins, "issuedAt": issued_at, "expiresAt": expires_at}
@router.get("/api/me/control-list")
def me_control_list(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""签发管控清单:下架(revoke)/禁用(disable)/强制更新(force-update)聚合,Ed25519 签名。
与授权票据同窗口携带 expiresAt:执行机刷新票据时一并刷新管控清单。
"""
_check_token(x_api_token)
revoked = []
disabled = []
forced = []
with _db() as conn:
for r in conn.execute(
"SELECT id, name, status, force_min_version, force_deadline FROM plugins"):
pid = r["id"]
if r["status"] == "revoked":
revoked.append(pid)
elif r["status"] == "disabled":
disabled.append(pid)
if r["force_min_version"] and r["force_deadline"]:
forced.append({"pluginId": pid, "minVersion": r["force_min_version"],
"deadline": r["force_deadline"]})
payload = {"revokedPlugins": revoked, "disabledPlugins": disabled,
"forcedUpdates": forced, "updatedAt": _now(),
"expiresAt": int(time.time()) + config.LICENSE_TTL_DAYS * 24 * 3600}
return {"ticket": crypto._sign_blob(payload), "control": payload}
# 一次性下载票据(内存态,兑换后失效)
_DL_TICKETS: dict = {}
@router.get("/api/plugins/{plugin_id}/versions/{version}/download-ticket")
def download_ticket(plugin_id: str, version: str,
account: str = Query(...),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""签发一次性下载票据:校验账号对该插件的 can_download 授权后签发,票据仅可换一次。"""
_check_token(x_api_token)
if not account.strip():
raise HTTPException(400, "account 不能为空")
with _db() as conn:
row = conn.execute(
"SELECT can_download FROM account_plugins WHERE account = %s AND plugin_id = %s",
(account.strip(), plugin_id)).fetchone()
ver = conn.execute(
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = %s AND version = %s",
(plugin_id, version)).fetchone()
if not ver:
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
if not row or not row["can_download"]:
raise HTTPException(403, "无该插件的下载授权")
path = config.PKG_DIR / ver["filename"]
if not path.exists():
raise HTTPException(404, f"包文件缺失:{ver['filename']}")
# 票据内含可下载文件名与校验值;用一次性 nonce 存内存,兑换后失效
nonce = secrets.token_hex(16)
_DL_TICKETS[nonce] = {"filename": ver["filename"], "sha256": ver["sha256"] or "",
"used": False}
url = f"/api/download/{nonce}"
return {"ticket": nonce, "url": url, "filename": ver["filename"],
"sha256": ver["sha256"] or "", "expiresAt": _now()}
@router.get("/api/download/{ticket}")
def download(ticket: str, x_api_token: str = Header(default="", alias="X-API-Token")):
"""兑换下载票据:一次性有效,兑换即作废并写审计。"""
_check_token(x_api_token)
item = _DL_TICKETS.get(ticket)
if not item or item["used"]:
raise HTTPException(404, "下载票据无效或已使用")
item["used"] = True
path = config.PKG_DIR / item["filename"]
if not path.exists():
raise HTTPException(404, f"包文件缺失:{item['filename']}")
_audit("", "download-ticket", item["filename"])
return FileResponse(path, filename=item["filename"], media_type="application/octet-stream")
@router.post("/api/runtime/report")
def runtime_report(b: schemas.RuntimeReportIn,
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""接收部署端运行上报(启动/完成/失败/离线补报),统一落库。"""
_check_token(x_api_token)
with _db() as conn:
conn.execute(
"INSERT INTO runtime_reports(account, device_id, plugin_id, version, status, msg, duration_sec, at) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(b.account, b.device_id, b.plugin_id, b.version, b.status, b.msg, b.duration_sec, _now()))
conn.commit()
return {"ok": True}
@router.post("/api/device/report")
def device_report(b: schemas.DeviceReportIn,
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""执行机心跳/环境上报(含 Chrome 检测结果):按 device_id 幂等 upsert 设备记录。
供壳(执行机底座)启动/定时上报本机环境;last_seen 与 status 由中心机统一维护
在线态(status 由调用方按心跳状态传,离线清理逻辑在管理端查询侧)。
"""
_check_token(x_api_token)
device_id = (b.device_id or "").strip()
if not device_id:
raise HTTPException(400, "device_id 不能为空")
with _db() as conn:
conn.execute(
"INSERT INTO devices(device_id, account, hostname, os, ip, "
"chrome_installed, chrome_version, chrome_ok, last_seen, status) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) "
"ON DUPLICATE KEY UPDATE "
"account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os), "
"ip = VALUES(ip), chrome_installed = VALUES(chrome_installed), "
"chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok), "
"last_seen = VALUES(last_seen), status = VALUES(status)",
(device_id, (b.account or "").strip(), (b.hostname or "").strip(),
(b.os or "").strip(), (b.ip or "").strip(),
int(bool(b.chrome_installed)), (b.chrome_version or "").strip(),
int(bool(b.chrome_ok)), _now(), int(bool(b.status))))
conn.commit()
return {"ok": True, "device_id": device_id}
# ==================== 壳子(执行机主程序)自动更新 ====================
# shell/version.json 约定:{"version": "1.0.0", "filename": "setup-37du-host-1.0.0.exe",
# "sha256": "<可选,安装包校验值>", "notes": "<可选,更新说明>"}
def _shell_meta() -> dict:
"""读 shell/version.json;缺失/非法返回空 dict。"""
vf = config.SHELL_DIR / "version.json"
if not vf.is_file():
return {}
try:
d = json.loads(vf.read_text(encoding="utf-8"))
return d if isinstance(d, dict) else {}
except Exception: # noqa: BLE001
return {}
def _shell_source_url() -> dict:
"""优先取 file_sources 表 category='shell' 的启用记录(最新一条),返回含 url 的字典;
无记录返回空 dict。大文件走内网文件服务器时,客户端据此直连下载。"""
try:
with _db() as conn:
row = conn.execute(
"SELECT version, filename, url, sha256, notes FROM file_sources "
"WHERE category = 'shell' AND enabled = 1 ORDER BY id DESC LIMIT 1").fetchone()
except Exception: # noqa: BLE001 DB 未就绪等,回退 version.json
return {}
if not row or not row.get("url"):
return {}
return {"version": row.get("version") or "", "filename": row.get("filename") or "",
"url": row["url"], "sha256": row.get("sha256") or "",
"notes": row.get("notes") or ""}
@router.get("/api/shell/version")
def shell_version(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""壳子版本清单:执行端启动时比对,判断是否需要自动下载升级包。
优先用 file_sources(category=shell) 的内网直链;未登记时回退 version.json。
响应含 url:客户端据此直连内网文件服务器下载大包;url 为空则回退中心机 /api/shell/pkg。
"""
_check_token(x_api_token)
source = _shell_source_url()
meta = _shell_meta()
if source.get("url"):
return {"available": True, "version": source.get("version") or meta.get("version", ""),
"filename": source.get("filename") or meta.get("filename", ""),
"url": source["url"], "sha256": source.get("sha256") or meta.get("sha256", ""),
"notes": source.get("notes") or meta.get("notes", "")}
m = meta
if not m.get("version"):
return {"available": False, "version": ""}
return {"available": True, "version": str(m["version"]),
"filename": m.get("filename", ""), "sha256": m.get("sha256", ""),
"notes": m.get("notes", ""), "url": ""}
@router.get("/api/shell/pkg")
def shell_pkg(x_api_token: str = Header(default="", alias="X-API-Token")):
"""下载壳子安装包(setup.exe),供执行端静默升级。"""
_check_token(x_api_token)
m = _shell_meta()
fn = m.get("filename", "")
path = config.SHELL_DIR / fn if fn else None
if not path or not path.exists():
raise HTTPException(404, "壳子安装包缺失,请联系管理员")
return FileResponse(path, filename=path.name, media_type="application/octet-stream")