1. 移除naive-ui依赖,迁移前端至Element Plus 2. 重构后端数据库层,切换为MySQL替代SQLite 3. 调整项目部署架构,停止exe打包改为源码部署 4. 新增设备上报接口与相关数据库模型 5. 优化配置路径与SQL语法,替换为MySQL占位符格式 6. 调整站点名称与文案,统一为「37du 插件管理平台」 7. 新增SQLite到MySQL迁移脚本
320 lines
14 KiB
Python
320 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""客户端(部署端)拉取接口:插件清单 / 平台白名单 / 版本清单 / 包下载 / 离线票据 / 运行上报。
|
||
|
||
权限隔离 + 插件分发 + 版本比对,客户端只经本接口获取能力,不直连数据库。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import secrets
|
||
|
||
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
|
||
from controlplane.core.pkgutil import _load_manifest
|
||
|
||
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/manifest")
|
||
def manifest(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""全量插件版本清单:客户端据此比对是否需要拉新包。"""
|
||
_check_token(x_api_token)
|
||
with _db() as conn:
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT p.id, p.name, p.latest_version AS version, pv.uploaded_at,
|
||
p.status, p.category, pv.sha256 AS pkg_sha256, p.manifest
|
||
FROM plugins p
|
||
LEFT JOIN plugin_versions pv ON pv.plugin_id = p.id AND pv.version = p.latest_version
|
||
ORDER BY p.id
|
||
"""
|
||
).fetchall()
|
||
out = []
|
||
for r in rows:
|
||
item = dict(r)
|
||
m = _load_manifest(item.pop("manifest"))
|
||
item["manifest"] = m
|
||
item["capabilities"] = m.get("capabilities") or []
|
||
item["permissions"] = m.get("permissions") or {}
|
||
props = (m.get("fields") or {}).get("properties") or {}
|
||
item["field_count"] = len(props)
|
||
out.append(item)
|
||
return {"plugins": out, "generated_at": _now()}
|
||
|
||
|
||
@router.get("/api/pkg/{plugin_id}/{version}")
|
||
def pkg(plugin_id: str, version: str,
|
||
x_api_token: str = Header(default="", alias="X-API-Token")):
|
||
"""下载指定版本插件包。包文件存磁盘,DB 记 filename 索引。"""
|
||
_check_token(x_api_token)
|
||
with _db() as conn:
|
||
row = conn.execute(
|
||
"SELECT filename FROM plugin_versions WHERE plugin_id = %s AND version = %s",
|
||
(plugin_id, version),
|
||
).fetchone()
|
||
if not row:
|
||
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||
path = config.PKG_DIR / row["filename"]
|
||
if not path.exists():
|
||
raise HTTPException(404, f"包文件缺失:{row['filename']}")
|
||
_audit("", "download", f"{plugin_id}@{version}")
|
||
return FileResponse(path, filename=row["filename"], media_type="application/octet-stream")
|
||
|
||
|
||
# ==================== 产品化:客户端(部署端)拉取接口 ====================
|
||
@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 签名。
|
||
|
||
票据无硬过期——部署端离线时凭缓存副本持续可用(符合"不联网一直能用")。
|
||
"""
|
||
_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]
|
||
blob = crypto._sign_blob({"userId": account.strip(), "deviceId": device or "",
|
||
"issuedAt": _now(), "plugins": plugins})
|
||
return {"ticket": blob, "plugins": plugins, "issuedAt": _now()}
|
||
|
||
|
||
@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 签名。"""
|
||
_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()}
|
||
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 {}
|
||
|
||
|
||
@router.get("/api/shell/version")
|
||
def shell_version(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""壳子版本清单:执行端启动时比对,判断是否需要自动下载升级包。"""
|
||
_check_token(x_api_token)
|
||
m = _shell_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", "")}
|
||
|
||
|
||
@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") |