refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移: 1. 将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构 2. 移动并整理了插件目录结构,将插件统一放入根级plugins/ 3. 调整了前端项目的路径与配置,统一前后端开发构建流程 4. 清理了废弃的旧版app/目录与冗余的构建中间文件 5. 更新了.gitignore与README.md,适配新的项目结构
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane 路由子包:按领域组织 APIRouter,由 app.py 底层组装。"""
|
||||
@@ -0,0 +1,541 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""管理侧路由(写操作,需正确 token):账号 CRUD / 插件上传与维护 / 授权 / 看板 / 审计 / 运行记录。
|
||||
|
||||
所有写操作均以 `_require_admin`(X-API-Token + X-Admin-Token 管理员票据)把关。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import _require_admin
|
||||
from controlplane.core.crypto import _hash_password
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.pkgutil import (
|
||||
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
|
||||
_validate_pkg_zip, _version_key,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||||
@router.get("/api/admin/accounts")
|
||||
def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全部账号(含部门/管理员标记/已授权插件/可登录平台)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd "
|
||||
"FROM accounts ORDER BY account")]
|
||||
for a in rows:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
a["grants"] = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants WHERE account = ?",
|
||||
(a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
return {"accounts": rows}
|
||||
|
||||
|
||||
@router.post("/api/admin/account")
|
||||
def admin_account_create(a: schemas.AccountCreateIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""新建账号:密码必填,可指定部门/昵称/是否管理员。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
with _db() as conn:
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
if exists:
|
||||
raise HTTPException(400, f"账号 {account} 已存在")
|
||||
_hex, _salt = _hash_password(a.password)
|
||||
with _db() as conn:
|
||||
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
|
||||
(a.nickname or "").strip()))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||||
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
|
||||
|
||||
|
||||
@router.post("/api/admin/account/update")
|
||||
def admin_account_update(a: schemas.AccountUpdateIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""更新账号:改部门 / 昵称 / 授予或撤销管理员。"""
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
if a.dept is not None:
|
||||
conn.execute("UPDATE accounts SET dept = ? WHERE account = ?",
|
||||
((a.dept or "").strip(), account))
|
||||
if a.nickname is not None:
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
((a.nickname or "").strip(), account))
|
||||
if a.is_admin is not None:
|
||||
# 禁止撤销自己的管理员身份,避免把自己锁在门外
|
||||
if a.is_admin:
|
||||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
|
||||
else:
|
||||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
|
||||
(account, login))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@router.post("/api/admin/account/reset_pwd")
|
||||
def admin_account_reset(r: schemas.AccountResetIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""管理员重置任意账号密码(无需原密码)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = r.account.strip()
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
_hex, _salt = _hash_password(r.new_password)
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||||
(_hex, _salt, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@router.post("/api/admin/account/delete")
|
||||
def admin_account_delete(d: schemas.AccountDelIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除账号:不可删除自己;连带清除其插件授权。"""
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = d.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 必填")
|
||||
if account == login:
|
||||
raise HTTPException(400, "不能删除当前登录的账号")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
conn.execute("DELETE FROM accounts WHERE account = ?", (account,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ?", (account,))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
# ==================== 授权 / 插件维护 ====================
|
||||
@router.post("/api/admin/account_plugins")
|
||||
def admin_grant(g: schemas.GrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤;同时维护插件级授权表。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
plugin_id = g.plugin_id.strip()
|
||||
if not account or not plugin_id:
|
||||
raise HTTPException(400, "account 与 plugin_id 不能为空")
|
||||
with _db() as conn:
|
||||
if g.granted:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||||
(account, plugin_id))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(account, plugin_id) DO UPDATE SET "
|
||||
"can_download = excluded.can_download, can_run = excluded.can_run",
|
||||
(account, plugin_id, int(g.can_download), int(g.can_run)))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
|
||||
(account, plugin_id))
|
||||
conn.execute("DELETE FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
(account, plugin_id))
|
||||
conn.commit()
|
||||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
f"can_download={g.can_download},can_run={g.can_run}")
|
||||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||||
|
||||
|
||||
@router.post("/api/admin/account_platforms")
|
||||
def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予或撤销某账号对某平台的登录权限。granted=True 授,False 撤。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
platform_id = g.platform_id.strip()
|
||||
if not account or not platform_id:
|
||||
raise HTTPException(400, "account 与 platform_id 不能为空")
|
||||
with _db() as conn:
|
||||
if g.granted:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
|
||||
(account, platform_id))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||
|
||||
|
||||
@router.post("/api/admin/pkg")
|
||||
async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
plugin_id: str = Query(...), name: str = Query(...),
|
||||
version: str = Query(...),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""上传并发布插件包:完整性校验 → 存盘 → 登记版本 → 更新最新版 → 仅保留最近 3 个版本。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = plugin_id.strip()
|
||||
name = name.strip() or plugin_id
|
||||
version = version.strip()
|
||||
if not plugin_id or not version:
|
||||
raise HTTPException(400, "plugin_id 与 version 不能为空")
|
||||
# 只允许安全字符(防止拼进文件路径造成目录穿越)
|
||||
if not _SAFE_NAME_RE.match(plugin_id) or not _SAFE_NAME_RE.match(version):
|
||||
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||||
filename = f"{plugin_id}_v{version}.zip"
|
||||
target = config.PKG_DIR / filename
|
||||
content = await upload.read()
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
_validate_pkg_zip(content)
|
||||
|
||||
# manifest 为插件契约权威来源:plugin.json 内 id 与路径 plugin_id 不一致时拒绝,
|
||||
# 否则以 manifest.metadata 覆盖 name/category/icon/description 并整份入库。
|
||||
manifest = _extract_manifest(content)
|
||||
if manifest:
|
||||
mid = str((manifest.get("id") or "")).strip()
|
||||
if mid and mid != plugin_id:
|
||||
raise HTTPException(400, f"plugin.json 内 id「{mid}」与路径 plugin_id「{plugin_id}」不一致")
|
||||
name = str(manifest.get("name") or name).strip() or plugin_id
|
||||
manifest_json = json.dumps(manifest, ensure_ascii=False) if manifest else "{}"
|
||||
|
||||
target.write_bytes(content)
|
||||
pkg_sha256 = hashlib.sha256(content).hexdigest() # 供部署端装包后防篡改校验
|
||||
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
|
||||
"name = excluded.name, manifest = excluded.manifest"
|
||||
+ (", description = excluded.description" if manifest else "")
|
||||
+ (", category = excluded.category" if manifest else "")
|
||||
+ (", icon = excluded.icon" if manifest else ""),
|
||||
(plugin_id, name, version,
|
||||
(manifest or {}).get("description", ""),
|
||||
(manifest or {}).get("category", ""),
|
||||
(manifest or {}).get("icon", ""),
|
||||
manifest_json))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256) "
|
||||
"VALUES (?, ?, ?, ?, ?) ON CONFLICT(plugin_id, version) DO UPDATE SET "
|
||||
"filename = excluded.filename, uploaded_at = excluded.uploaded_at, sha256 = excluded.sha256",
|
||||
(plugin_id, version, filename, _now(), pkg_sha256))
|
||||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
|
||||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||||
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (version, plugin_id))
|
||||
stale_files = _prune_versions(conn, plugin_id)
|
||||
conn.commit()
|
||||
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
|
||||
try:
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||||
|
||||
|
||||
@router.post("/api/admin/plugin/delete")
|
||||
def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除插件:连带删除其全部版本记录、授权,并清理磁盘包文件。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = d.plugin_id.strip()
|
||||
if not plugin_id:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (plugin_id,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {plugin_id} 不存在")
|
||||
files = [dict(r)["filename"] for r in conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))]
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugins WHERE id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = ?", (plugin_id,))
|
||||
conn.commit()
|
||||
for fn in files:
|
||||
try:
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return {"ok": True, "plugin_id": plugin_id}
|
||||
|
||||
|
||||
@router.post("/api/admin/plugin/patch")
|
||||
def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
plugin_id: str = Query(...),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""更新插件元信息/状态/强制更新配置。
|
||||
|
||||
status: published=正常 / disabled=禁用(停止发布) / revoked=下架(拒绝运行)。
|
||||
force_min_version + force_deadline 组合开启强制更新(deadline 已过联线拒启旧版);
|
||||
clear_force=True 清除强制更新;仅给其一且未 clear 则报 400。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
pid = plugin_id.strip()
|
||||
if not pid:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
fields = []
|
||||
vals = []
|
||||
if d.name is not None and d.name.strip():
|
||||
fields.append("name = ?"); vals.append(d.name.strip())
|
||||
if d.description:
|
||||
fields.append("description = ?"); vals.append(d.description.strip())
|
||||
if d.category:
|
||||
fields.append("category = ?"); vals.append(d.category.strip())
|
||||
if d.icon:
|
||||
fields.append("icon = ?"); vals.append(d.icon.strip())
|
||||
if d.status in ("published", "disabled", "revoked"):
|
||||
fields.append("status = ?"); vals.append(d.status)
|
||||
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
|
||||
if d.force_min_version and d.force_deadline:
|
||||
fields.append("force_min_version = ?"); vals.append(d.force_min_version.strip())
|
||||
fields.append("force_deadline = ?"); vals.append(d.force_deadline.strip())
|
||||
elif (d.force_min_version or d.force_deadline) and not d.clear_force:
|
||||
raise HTTPException(400, "强制更新需同时提供 force_min_version 与 force_deadline")
|
||||
elif d.clear_force:
|
||||
fields.append("force_min_version = NULL")
|
||||
fields.append("force_deadline = NULL")
|
||||
if not fields:
|
||||
return {"ok": True} # 无更新项
|
||||
vals.append(pid)
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (pid,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {pid} 不存在")
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = ?", vals)
|
||||
conn.commit()
|
||||
_audit("", "plugin-patch", pid, ", ".join(
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||||
return {"ok": True, "plugin_id": pid}
|
||||
|
||||
|
||||
# ==================== 看板 / 审计 / 运行记录 ====================
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""管理台一次性拉取:全部插件(含元信息/状态/版本/被授权账号)+ 全部账号 + 管理员名单。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
plugins = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, description, category, icon, status, latest_version, "
|
||||
" force_min_version, force_deadline, manifest "
|
||||
"FROM plugins ORDER BY id")]
|
||||
for p in plugins:
|
||||
m = _load_manifest(p.pop("manifest"))
|
||||
p["manifest"] = m
|
||||
p["capabilities"] = m.get("capabilities") or []
|
||||
p["permissions"] = m.get("permissions") or {}
|
||||
props = (m.get("fields") or {}).get("properties") or {}
|
||||
p["field_count"] = len(props)
|
||||
p["versions"] = [dict(r) for r in conn.execute(
|
||||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||
"WHERE plugin_id = ? ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = ?", (p["id"],))]
|
||||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, can_download, can_run FROM plugin_grants "
|
||||
"WHERE plugin_id = ?", (p["id"],))}
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT account, is_admin, dept, nickname FROM accounts ORDER BY account")]
|
||||
for a in accounts:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants "
|
||||
"WHERE account = ?", (a["account"],))}
|
||||
admins = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM accounts WHERE is_admin = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts, "admins": admins}
|
||||
|
||||
|
||||
@router.get("/api/admin/stats")
|
||||
def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""数据看板:账号/插件规模 + 运行统计(次数/时长/成败)+ 近 14 天趋势 + 排行。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
users = dict(conn.execute(
|
||||
"SELECT (SELECT COUNT(*) FROM accounts) AS total, "
|
||||
"(SELECT COUNT(*) FROM accounts WHERE is_admin = 1) AS admins, "
|
||||
"(SELECT COUNT(DISTINCT account) FROM account_plugins) AS authorized").fetchone())
|
||||
plugins = dict(conn.execute(
|
||||
"SELECT (SELECT COUNT(*) FROM plugins) AS total, "
|
||||
"(SELECT COUNT(*) FROM plugins WHERE status = 'published') AS published, "
|
||||
"(SELECT COUNT(*) FROM plugins WHERE status = 'disabled') AS disabled, "
|
||||
"(SELECT COUNT(*) FROM plugins WHERE status = 'revoked') AS revoked").fetchone())
|
||||
runs = dict(conn.execute(
|
||||
"SELECT (SELECT COUNT(*) FROM runtime_reports WHERE status = 'start') AS started, "
|
||||
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')) AS success, "
|
||||
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')) AS failed, "
|
||||
"(SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports) AS duration_sec, "
|
||||
"(SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> '') AS active_users, "
|
||||
"(SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '') AS active_plugins").fetchone())
|
||||
|
||||
# 近 14 天运行趋势(按日:触发次数 / 成功 / 失败)
|
||||
trend_rows = conn.execute(
|
||||
"SELECT substr(at,1,10) AS day, "
|
||||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS runs, "
|
||||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed "
|
||||
"FROM runtime_reports WHERE at >= date('now','-13 days') GROUP BY day ORDER BY day"
|
||||
).fetchall()
|
||||
trend_map = {r["day"]: r for r in trend_rows}
|
||||
trend = []
|
||||
day = datetime.now() - timedelta(days=13)
|
||||
for _i in range(14):
|
||||
key = day.strftime("%Y-%m-%d")
|
||||
r = trend_map.get(key)
|
||||
trend.append({"day": key[5:], "runs": int(r["runs"] or 0) if r else 0,
|
||||
"success": int(r["success"] or 0) if r else 0,
|
||||
"failed": int(r["failed"] or 0) if r else 0})
|
||||
day = day + timedelta(days=1)
|
||||
|
||||
# 插件排行:按执行次数(以 status='start' 为一次完整触发)
|
||||
top_plugins = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id AS pluginId, "
|
||||
" COUNT(*) AS runs, "
|
||||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS triggered, "
|
||||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed, "
|
||||
" COALESCE(SUM(duration_sec),0) AS durationSec "
|
||||
"FROM runtime_reports GROUP BY plugin_id "
|
||||
"ORDER BY triggered DESC LIMIT 8")]
|
||||
pnames = {dict(r)["id"]: dict(r)["name"] for r in conn.execute(
|
||||
"SELECT id, name FROM plugins")}
|
||||
for tp in top_plugins:
|
||||
tp["name"] = pnames.get(tp["pluginId"]) or tp["pluginId"]
|
||||
tp["runs"] = int(tp["triggered"] or 0)
|
||||
|
||||
# 活跃用户排行
|
||||
top_users = [{"account": r["account"], "runs": int(r["runs"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, COUNT(*) AS runs FROM runtime_reports "
|
||||
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||||
"ORDER BY runs DESC LIMIT 8")]
|
||||
|
||||
# 最近运行列表
|
||||
recent = [dict(r) for r in conn.execute(
|
||||
"SELECT at, account, plugin_id AS pluginId, version, status, msg, duration_sec AS durationSec "
|
||||
"FROM runtime_reports WHERE status <> 'start' "
|
||||
"ORDER BY id DESC LIMIT 20")]
|
||||
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
for tu in top_users:
|
||||
tu["nickname"] = nick.get(tu["account"], "")
|
||||
for rc in recent:
|
||||
rc["nickname"] = nick.get(rc.get("account", ""), "")
|
||||
|
||||
now_day = datetime.now().strftime("%Y-%m-%d")
|
||||
return {
|
||||
"users": {"total": int(users["total"] or 0), "admins": int(users["admins"] or 0),
|
||||
"authorized": int(users["authorized"] or 0)},
|
||||
"plugins": {"total": int(plugins["total"] or 0), "published": int(plugins["published"] or 0),
|
||||
"disabled": int(plugins["disabled"] or 0), "revoked": int(plugins["revoked"] or 0)},
|
||||
"runs": {"total": int(runs["started"] or 0), "success": int(runs["success"] or 0),
|
||||
"failed": int(runs["failed"] or 0), "durationSec": int(runs["duration_sec"] or 0),
|
||||
"activeUsers": int(runs["active_users"] or 0), "activePlugins": int(runs["active_plugins"] or 0)},
|
||||
"trend": trend, "topPlugins": top_plugins, "topUsers": top_users,
|
||||
"recent": recent, "today": now_day,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/audit")
|
||||
def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""审计日志(最新在前,分页取 limit 条)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs "
|
||||
"ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"auditlogs": rows}
|
||||
|
||||
|
||||
@router.get("/api/admin/reports")
|
||||
def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""运行上报记录(最新在前)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, device_id, plugin_id, version, status, msg, duration_sec, at "
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"reports": rows}
|
||||
|
||||
|
||||
@router.post("/api/admin/shell-release")
|
||||
async def admin_shell_release(upload: UploadFile = File(...),
|
||||
version: str = Query(...),
|
||||
notes: str = Query(default=""),
|
||||
sha256: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""发布执行机壳子新版安装包:存到 shell/ + 写 version.json(管理员)。
|
||||
|
||||
供 agent CLI / 管理端从任意机器上传壳子安装包,执行机据此自动下载升级。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
version = version.strip()
|
||||
if not version:
|
||||
raise HTTPException(400, "version 不能为空")
|
||||
if not _SAFE_NAME_RE.match(version):
|
||||
raise HTTPException(400, "version 仅允许字母数字及 . _ -")
|
||||
config.SHELL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
filename = f"setup-37du-host-{version}.exe"
|
||||
content = await upload.read()
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
if not sha256:
|
||||
sha256 = hashlib.sha256(content).hexdigest()
|
||||
(config.SHELL_DIR / filename).write_bytes(content)
|
||||
(config.SHELL_DIR / "version.json").write_text(
|
||||
json.dumps({"version": version, "filename": filename,
|
||||
"sha256": sha256, "notes": notes},
|
||||
ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
_audit("", "shell-release", filename)
|
||||
return {"ok": True, "version": version, "filename": filename, "sha256": sha256}
|
||||
@@ -0,0 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""账号登录与身份路由:当前账号信息 / 可授权平台 / 账号密码登录 / 自助改密 / 员工端扫码换 token。
|
||||
|
||||
- 管理写操作(改他人账号/插件)统一走 apis.admin(_require_admin);
|
||||
- 此处为"自助/登录"类只读或本账号操作。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import (
|
||||
_AUTH_FAILS, _auth_account_lookup, _auth_fail, _auth_gate, _check_token,
|
||||
_resolve_login, _require_admin, _sign_admin_token,
|
||||
)
|
||||
from controlplane.core.crypto import _hash_password, _verify_password
|
||||
from controlplane.core.db import _db
|
||||
from controlplane.core.dingtalk import _dingtalk_userinfo
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_CONTROLPLANE_PLATFORMS = [
|
||||
{"id": "hr", "label": "HR 系统"},
|
||||
{"id": "oa", "label": "OA 系统"},
|
||||
] # 需与 webhost/backend/auth.py `_LABELS` 保持一致;新增平台时两侧同步
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""查询当前账号信息:管理员标识 + 部门 + 昵称。"""
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin, dept, nickname FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
return {"account": account,
|
||||
"is_admin": bool(row and row["is_admin"]),
|
||||
"dept": (row["dept"] if row else "") or "",
|
||||
"nickname": (row["nickname"] if row else "") or ""}
|
||||
|
||||
|
||||
@router.get("/api/admin/platforms")
|
||||
def admin_platforms(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""可授权平台列表(只读,替代授权页写死 hr/oa)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
return {"platforms": _CONTROLPLANE_PLATFORMS}
|
||||
|
||||
|
||||
@router.post("/api/admin/auth")
|
||||
def admin_auth(a: schemas.AuthIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""统一账户登录:所有账号均可登录(需密码正确);是否管理员由 is_admin 决定。"""
|
||||
_check_token(x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
_auth_gate(account)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, is_admin, dept, must_change_pwd FROM accounts WHERE account = ?",
|
||||
(account,)).fetchone()
|
||||
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
|
||||
_auth_fail(account)
|
||||
raise HTTPException(401, "账号或密码错误")
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"must_change_pwd": bool(row["must_change_pwd"]),
|
||||
"token": _sign_admin_token(account)}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(p: schemas.PwdIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not p.account.strip() or not p.new_password:
|
||||
raise HTTPException(400, "account 与新密码不能为空")
|
||||
if p.account != login:
|
||||
raise HTTPException(403, "只能修改自己的密码")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = ?",
|
||||
(login,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, "账号不存在")
|
||||
# 首次登录(must_change_pwd=1,钉钉自动建号的默认密码)允许免旧密码直接改密
|
||||
if not row["must_change_pwd"] and (
|
||||
not row["salt"] or not _verify_password(p.old_password, row["salt"], row["password_hash"])):
|
||||
raise HTTPException(401, "原密码错误")
|
||||
_hex, _salt = _hash_password(p.new_password)
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 0 "
|
||||
"WHERE account = ?", (_hex, _salt, login))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": login}
|
||||
|
||||
|
||||
# ==================== 员工端登录 /auth/exchange(v3 最简方案,壳本机直连接 code) ====================
|
||||
# 壳 login 云端的唯一接口:壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 只验证不建号
|
||||
# → 签发云端会话 token(供壳调 /api/plugins 鉴权,见 apis/plugins §2.2)。
|
||||
_CLOUD_TOKEN_TTL = 7 * 24 * 3600
|
||||
_cloud_tokens: dict = {}
|
||||
_cloud_lock = threading.Lock()
|
||||
|
||||
|
||||
@router.post("/auth/exchange")
|
||||
def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
"""壳 → 云端:壳 POST 钉钉授权码 code,换取员工工号 + 云端会话 token(只验证不建号)。"""
|
||||
code = (d.code or "").strip()
|
||||
if not code:
|
||||
raise HTTPException(400, "缺少 code")
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
info = _dingtalk_userinfo(code)
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account:
|
||||
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||
acct = _auth_account_lookup(account)
|
||||
token = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
# 惰性清理过期云端会话,防内存无限增长
|
||||
for k in [k for k, v in _cloud_tokens.items() if v["exp"] < now]:
|
||||
_cloud_tokens.pop(k, None)
|
||||
_cloud_tokens[token] = {"exp": now + _CLOUD_TOKEN_TTL, "account": account,
|
||||
"nickname": acct["nickname"] or (info.get("nickname") or "")}
|
||||
return {"token": token,
|
||||
"account": account, "nickname": acct["nickname"] or (info.get("nickname") or ""),
|
||||
"exists": bool(acct["exists"]), "is_admin": False}
|
||||
@@ -0,0 +1,127 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉扫码路由:找建账号 / OAuth 扫码页 + 回调 / 内嵌二维码(DDLogin)。
|
||||
|
||||
- 账号建立/鉴权统一走 /api/admin/dingtalk/auth(find-or-create,仅底座 X-API-Token 可调);
|
||||
- /scan→/cb 与 /sns 仅为可信扫码入口,仅换取身份不建号(建号仍由 auth 把关)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import secrets
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import _check_token, _sign_admin_token
|
||||
from controlplane.core.crypto import _hash_password
|
||||
from controlplane.core.db import _db
|
||||
from controlplane.core.dingtalk import _dingtalk_sns_userinfo, _dingtalk_userinfo
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/auth")
|
||||
def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""钉钉扫码身份 → 找建统一账号(仅底座 X-API-Token 可调)。
|
||||
|
||||
返回 {ok, account, nickname, is_admin, created, must_change_pwd, token}。
|
||||
created=True 表示本次新建;must_change_pwd=True 表示当前为默认密码,前端须提示改密。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
account = d.account.strip()
|
||||
if not account or not account.isprintable() or re.search(r"[\s]", account):
|
||||
raise HTTPException(400, "工号不能为空且不可包含空白字符")
|
||||
nickname = (d.nickname or "").strip()
|
||||
ding_uid = (d.dingtalk_uid or "").strip()
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT account, is_admin, must_change_pwd, nickname FROM accounts WHERE account = ?",
|
||||
(account,)).fetchone()
|
||||
if row:
|
||||
# 已存在:顺带同步昵称(钉钉名),但不改密码/权限;原有 must_change_pwd 保留
|
||||
if nickname and nickname != (row["nickname"] or ""):
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
(nickname, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account,
|
||||
"nickname": nickname or (row["nickname"] or ""),
|
||||
"is_admin": bool(row["is_admin"]),
|
||||
"created": False, "must_change_pwd": bool(row["must_change_pwd"]),
|
||||
"token": _sign_admin_token(account)}
|
||||
# 不存在:自动建号(空壳),初始密码取覆盖值或默认值,强制改密
|
||||
pwd = (d.password.strip() if d.password else config.DINGTALK_DEFAULT_PASSWORD)
|
||||
if len(pwd) < 6:
|
||||
raise HTTPException(400, "初始密码至少 6 位")
|
||||
_hex, _salt = _hash_password(pwd)
|
||||
conn.execute(
|
||||
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||||
"dingtalk_uid, must_change_pwd) VALUES (?, ?, ?, 0, '', ?, ?, 1)",
|
||||
(account, _hex, _salt, nickname, ding_uid))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "nickname": nickname,
|
||||
"is_admin": False, "created": True, "must_change_pwd": True,
|
||||
"token": _sign_admin_token(account)}
|
||||
|
||||
|
||||
# ==================== 钉钉真实扫码(OAuth):扫码页 + 回调换取身份 ====================
|
||||
# 流程:部署机扫码按钮 → 本机 /api/admin/dingtalk/scan → 跳钉钉登录页(redirect_uri=本中心机回调)
|
||||
# → 用户扫码确认 → 钉钉回调 /api/admin/dingtalk/cb?code → 换 token 拉工号/姓名 →
|
||||
# 302 回部署机(state 中带回的 back)携带身份 → 部署机静默建会话。
|
||||
@router.get("/api/admin/dingtalk/scan")
|
||||
def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳地址")) -> RedirectResponse:
|
||||
"""扫码入口:302 到钉钉扫码登录页;state 携带部署机回跳地址,扫码成功后由 /cb 带回。"""
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
if not config.DINGTALK_CALLBACK:
|
||||
raise HTTPException(400, "未配置 DINGTALK_CALLBACK(钉钉后台登记的回调地址)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb",
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": back})
|
||||
return RedirectResponse(login_url)
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb(code: str = Query(...), state: str = Query(...)) -> RedirectResponse:
|
||||
"""钉钉回调:换 token 拉工号/姓名后,302 回部署机(state 里的回跳地址)携带身份。"""
|
||||
if not (state.startswith("http://") or state.startswith("https://")):
|
||||
raise HTTPException(400, "非法回跳地址")
|
||||
info = _dingtalk_userinfo(code)
|
||||
qs = urlencode({"account": info["account"] or "", "nickname": info["nickname"],
|
||||
"unionid": info["unionid"] or ""})
|
||||
sep = "&" if "?" in state else "?"
|
||||
return RedirectResponse(f"{state}{sep}{qs}")
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/sns")
|
||||
def dingtalk_sns(d: schemas.SnsIn) -> dict:
|
||||
"""内嵌二维码扫码换取身份:loginTmpCode → 工号/姓名/unionid。
|
||||
|
||||
与 /scan→/cb 同为可信扫码入口,仅换取身份(不建号),故与链接授权链路一致不强制 X-API-Token;
|
||||
账号创建仍由 /api/admin/dingtalk(find-or-create, _check_token)把关。
|
||||
"""
|
||||
if not d.code.strip():
|
||||
raise HTTPException(400, "缺少扫码截图码")
|
||||
return _dingtalk_sns_userinfo(d.code.strip())
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/inline_qr")
|
||||
def dingtalk_inline_qr(back: str = Query(default="", description="(兼容保留,内嵌不直接跳转)")) -> dict:
|
||||
"""构造内嵌二维码(DDLogin)所需的 goto:登录页在本页内渲染二维码,不弹新窗口。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not config.DINGTALK_CALLBACK:
|
||||
raise HTTPException(503, "未配置中心机回调域名(DINGTALK_CALLBACK)")
|
||||
auth_url = ("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=%s"
|
||||
"&response_type=code&scope=snsapi_login&state=%s&redirect_uri=%s") % (
|
||||
config.DINGTALK_APP_KEY, secrets.token_hex(8),
|
||||
quote(f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb"))
|
||||
return {"goto": quote(auth_url)}
|
||||
@@ -0,0 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""基础元信息路由:健康检查。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from controlplane import config
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True, "db": config.DB_PATH.name}
|
||||
@@ -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