本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
367 lines
17 KiB
Python
367 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""客户端(部署端)拉取接口:插件清单 / 平台白名单 / 版本清单 / 包下载 / 离线票据 / 运行上报。
|
||
|
||
权限隔离 + 插件分发 + 版本比对,客户端只经本接口获取能力,不直连数据库。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import secrets
|
||
import time
|
||
|
||
from fastapi import APIRouter, Header, HTTPException, Query, Request
|
||
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.logstore import append_shell_log, store_run_log
|
||
|
||
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}
|
||
|
||
|
||
# 一次性下载票据落库(download_tickets 表):gunicorn 多 worker 下签发与兑换必须共享同一份状态,
|
||
# 否则 A worker 签发的票据落到 B/C/D worker 兑换会 404「票据无效」,3/4 概率下载失败(同云令牌坑)。
|
||
_DL_TICKET_TTL = 3600 # 票据有效期(秒):签发后 1 小时未兑换即清理
|
||
|
||
|
||
@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']}")
|
||
# 票据内含可下载文件名与校验值;落库共享,兑换时原子置 used=1 作废
|
||
nonce = secrets.token_hex(16)
|
||
with _db() as conn:
|
||
# 顺手清理过期票据,防表无限增长
|
||
conn.execute(
|
||
"DELETE FROM download_tickets WHERE created_at < DATE_SUB(NOW(), INTERVAL %d SECOND)"
|
||
% int(_DL_TICKET_TTL))
|
||
conn.execute(
|
||
"INSERT INTO download_tickets(nonce, filename, sha256, used) VALUES (%s, %s, %s, 0)",
|
||
(nonce, ver["filename"], ver["sha256"] or ""))
|
||
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)
|
||
with _db() as conn:
|
||
# 原子占位:仅 used=0 才能改成 1,命中行数=0 说明票据不存在或已被兑换
|
||
cur = conn.execute(
|
||
"UPDATE download_tickets SET used = 1 WHERE nonce = %s AND used = 0", (ticket,))
|
||
row = conn.execute(
|
||
"SELECT filename FROM download_tickets WHERE nonce = %s", (ticket,)).fetchone()
|
||
if not cur.rowcount or not row:
|
||
raise HTTPException(404, "下载票据无效或已使用")
|
||
path = config.PKG_DIR / row["filename"]
|
||
if not path.exists():
|
||
raise HTTPException(404, f"包文件缺失:{row['filename']}")
|
||
_audit("", "download-ticket", row["filename"])
|
||
return FileResponse(path, filename=row["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/runtime/logs")
|
||
def runtime_logs(b: schemas.RunLogIn,
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""接收部署端回传的一次运行完整日志(按 run_id 幂等 upsert,离线补报安全)。
|
||
|
||
运行日志正文(JSON 数组)存 run_logs 表 logs 列,供管理端「运行日志」集中排查,
|
||
无需再去执行机本机翻日志。
|
||
"""
|
||
_check_token(x_api_token)
|
||
payload = b.model_dump()
|
||
store_run_log(payload)
|
||
return {"ok": True, "run_id": b.run_id}
|
||
|
||
|
||
@router.post("/api/runtime/shell-log")
|
||
async def runtime_shell_log(request: Request,
|
||
device_id: str = Query(...),
|
||
account: str = Query(default=""),
|
||
hostname: str = Query(default=""),
|
||
client_version: str = Query(default=""),
|
||
reset: int = Query(default=0),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""接收部署端壳日志增量回传(原始字节体,O_APPEND 追加落盘 logs/shell/<device_id>.log)。
|
||
|
||
reset=1 表示客户端日志已轮转,先截断文件再写入(避免旧内容残留重复)。
|
||
单次体积上限 SHELL_LOG_CHUNK_MAX,防止恶意灌爆。
|
||
"""
|
||
_check_token(x_api_token)
|
||
device_id = (device_id or "").strip()
|
||
if not device_id:
|
||
raise HTTPException(400, "device_id 不能为空")
|
||
body = await request.body()
|
||
if len(body) > config.SHELL_LOG_CHUNK_MAX:
|
||
raise HTTPException(413, f"单次回传超过大小上限({config.SHELL_LOG_CHUNK_MAX // (1024 * 1024)}MB)")
|
||
try:
|
||
result = append_shell_log(device_id, body, account=account or "",
|
||
hostname=hostname or "", client_version=client_version or "",
|
||
reset=bool(reset))
|
||
except ValueError as e:
|
||
raise HTTPException(400, str(e))
|
||
return {"ok": True, "device_id": result["device_id"], "size_bytes": result["size_bytes"]}
|
||
|
||
|
||
@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, client_version, last_seen, status) "
|
||
"VALUES (%s,%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), "
|
||
"client_version = VALUES(client_version), "
|
||
"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)), (b.client_version or "").strip(),
|
||
_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:
|
||
# utf-8-sig:防 version.json 带 UTF-8 BOM(否则 json.loads 抛 JSONDecodeError → 回退失败)
|
||
d = json.loads(vf.read_text(encoding="utf-8-sig"))
|
||
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") |