refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移: 1. 将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构 2. 移动并整理了插件目录结构,将插件统一放入根级plugins/ 3. 调整了前端项目的路径与配置,统一前后端开发构建流程 4. 清理了废弃的旧版app/目录与冗余的构建中间文件 5. 更新了.gitignore与README.md,适配新的项目结构
This commit is contained in:
@@ -0,0 +1,277 @@
|
||||
# -*- 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()
|
||||
|
||||
|
||||
@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}
|
||||
|
||||
|
||||
# ==================== 壳子(执行机主程序)自动更新 ====================
|
||||
# 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")
|
||||
Reference in New Issue
Block a user