1. 重构controlplane与webhost后端的包结构,按领域拆分模块到core/apis子包 2. 移动并整理工具脚本到tools子目录,统一管理运维脚本 3. 重构插件运行时、调度、作业管理等核心模块到core子包 4. 更新AGENTS.md文档,明确各代码形态的组织规范 5. 清理重复的旧文件与冗余代码
235 lines
10 KiB
Python
235 lines
10 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""客户端(部署端)拉取接口:插件清单 / 平台白名单 / 版本清单 / 包下载 / 离线票据 / 运行上报。
|
||
|
||
权限隔离 + 插件分发 + 版本比对,客户端只经本接口获取能力,不直连数据库。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
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()
|
||
|
||
|
||
@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")
|
||
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 = ?
|
||
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")
|
||
with _db() as conn:
|
||
rows = conn.execute(
|
||
"SELECT platform_id FROM account_platforms WHERE account = ? 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 = ? AND version = ?",
|
||
(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 不能为空")
|
||
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 plugin_grants g
|
||
JOIN plugins p ON p.id = g.plugin_id
|
||
WHERE g.account = ?
|
||
""",
|
||
(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 plugin_grants WHERE account = ? AND plugin_id = ?",
|
||
(account.strip(), plugin_id)).fetchone()
|
||
ver = conn.execute(
|
||
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||
(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 (?,?,?,?,?,?,?,?)",
|
||
(b.account, b.device_id, b.plugin_id, b.version, b.status, b.msg, b.duration_sec, _now()))
|
||
conn.commit()
|
||
return {"ok": True} |