feat: 新增xq0031_xq0032 ERP报表导出插件,完成功能与基建更新
1. 新增xq0031_xq0032插件:包含前后端源码、打包脚本、配置文件与插件元数据 2. 新增内网文件服务器组件:exe、启停脚本、打包脚本与配置 3. 新增敏感凭证RSA加密下发能力与存储结构 4. 新增大文件源管理表与相关API 5. 优化登录流程与会话管理,新增Chrome自动化安装工具链 6. 清理废弃插件与示例代码 7. 更新版本号至1.1.3,完善安装包与.gitignore配置
This commit is contained in:
@@ -6,16 +6,12 @@
|
||||
"""
|
||||
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,
|
||||
_cloud_account, _issue_cloud_token, _resolve_login, _require_admin, _sign_admin_token,
|
||||
)
|
||||
from controlplane.core.crypto import _hash_password, _verify_password
|
||||
from controlplane.core.db import _db
|
||||
@@ -30,14 +26,21 @@ _CONTROLPLANE_PLATFORMS = [
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
def admin_me(authorization: str = Header(default="", alias="Authorization"),
|
||||
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 = ""
|
||||
"""查询当前账号信息:管理员标识 + 部门 + 昵称 + 头像。
|
||||
|
||||
身份来源依次:登录时签发的用户云令牌(Bearer) → 签名票据(X-Admin-Token) →
|
||||
底座注入的 X-Admin-User(仅当配了 CONTROLPLANE_TOKEN 时可信)。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
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": "", "avatar": ""}
|
||||
with _db() as conn:
|
||||
@@ -65,8 +68,8 @@ def admin_platforms(x_admin_token: str = Header(default="", alias="X-Admin-Token
|
||||
@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)
|
||||
"""统一账户登录:所有账号均可登录(需密码正确);是否管理员由 is_admin 决定。
|
||||
登录接口为公开入口,不要求 X-API-Token(否则未登录无法着装鉴权)。"""
|
||||
account = a.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
@@ -82,23 +85,28 @@ def admin_auth(a: schemas.AuthIn,
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
_nickname = (row["nickname"] or "")
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"dept": (row["dept"] or ""), "nickname": (row["nickname"] or ""),
|
||||
"dept": (row["dept"] or ""), "nickname": _nickname,
|
||||
"avatar": (row["avatar"] or ""),
|
||||
"must_change_pwd": bool(row["must_change_pwd"]),
|
||||
"token": _sign_admin_token(account)}
|
||||
"token": _sign_admin_token(account),
|
||||
"cloud_token": _issue_cloud_token(account, _nickname)}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(p: schemas.PwdIn,
|
||||
authorization: str = Header(default="", alias="Authorization"),
|
||||
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, "登录态无效或已过期,请重新登录")
|
||||
login = _cloud_account(authorization)
|
||||
if not login:
|
||||
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:
|
||||
@@ -123,10 +131,8 @@ def admin_password(p: schemas.PwdIn,
|
||||
|
||||
# ==================== 员工端登录 /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()
|
||||
# → 签发云端会话 token(供壳调 /api/plugins 鉴权,见 apis/plugins §2.2)。token 存储统一在
|
||||
# core.auth._cloud_tokens(_issue_cloud_token 签发、_cloud_account 解析),此处不再重复声明。
|
||||
|
||||
|
||||
@router.post("/auth/exchange")
|
||||
@@ -142,14 +148,8 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
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 "")}
|
||||
nickname = acct["nickname"] or (info.get("nickname") or "")
|
||||
token = _issue_cloud_token(account, nickname)
|
||||
return {"token": token,
|
||||
"account": account, "nickname": acct["nickname"] or (info.get("nickname") or ""),
|
||||
"account": account, "nickname": nickname,
|
||||
"exists": bool(acct["exists"]), "is_admin": False}
|
||||
@@ -0,0 +1,154 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""客户端敏感凭证中心化拉取(服务端侧):公钥登记 / 敏感凭证加密拉取 / 明文源管理。
|
||||
|
||||
- 凭证明文源存服务端 MySQL `client_creds.creds`(JSON: {key: plaintext}),
|
||||
明文源只由管理员经「敏感凭证」页面(/creds/manage 查看 + /creds/seed 保存)录入;
|
||||
register 仅登记执行机 RSA 公钥,不自动填充默认值。
|
||||
- 拉取 GET /api/admin/creds:**仅管理员可拉**(解析身份后校验 is_admin),服务端用该账号
|
||||
上报的 RSA 公钥把每个明文值 OAEP 加密为 base64 返回;客户端本机私钥解密。
|
||||
- 钉钉扫码 URL 已改由控制面代理构造(/api/dingtalk/login-url),执行机不再消费下发的钉钉值,
|
||||
链路保留供未来每账号敏感值下发能力使用。
|
||||
- 仅含钉钉开放平台凭证;HR/OA 平台登录账号由客户端本地加密存储(platform_accounts),不经服务端。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import schemas
|
||||
from controlplane.core.auth import _cloud_account, _resolve_login, _require_admin
|
||||
from controlplane.core.crypto import rsa_encrypt
|
||||
from controlplane.core.db import _db, _now
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 与 webhost/backend/core/creds_sync.py 的敏感键白名单保持一致(双重保障:下发限定范围)。
|
||||
# 仅下发钉钉开放平台凭证;HR/OA 平台登录账号改由执行机本地加密存储(platform_accounts),不经中心机。
|
||||
_ALLOWED_KEYS = (
|
||||
"DINGTALK_APPKEY", "DINGTALK_APPSECRET", "DINGTALK_AGENT_ID", "DINGTALK_CORP_ID",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/admin/creds/register")
|
||||
def creds_register(b: schemas.CredsRegisterIn,
|
||||
authorization: str = Header(default="", alias="Authorization"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""登记/更新某账号的 RSA 公钥(明文源不变)。
|
||||
|
||||
鉴权双轨(对齐方案"admin 或云令牌关联账号"):
|
||||
- 管理员(X-Admin-Token)可为任意账号登记;
|
||||
- 登录云令牌(Bearer)账号只能登记本人公钥(公钥本身公开,本人登记安全)。
|
||||
"""
|
||||
try:
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
except HTTPException:
|
||||
_self = _cloud_account(authorization)
|
||||
if not _self or _self != b.account.strip():
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
account = b.account.strip()
|
||||
pem = b.pubkey_pem.strip()
|
||||
if not account or not pem:
|
||||
raise HTTPException(400, "account 与 pubkey_pem 不能为空")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT creds FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||
# 明文源只由管理员 seed 创建/更新:register 仅登记公钥,保留现有明文源(无则空)
|
||||
existing = (row["creds"] if row else None) or "{}"
|
||||
conn.execute(
|
||||
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, %s, %s, %s) "
|
||||
"ON DUPLICATE KEY UPDATE pubkey_pem = VALUES(pubkey_pem), "
|
||||
"creds = VALUES(creds), updated_at = VALUES(updated_at)",
|
||||
(account, pem, existing, _now()))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@router.post("/api/admin/creds/seed")
|
||||
def creds_seed(b: schemas.CredsSeedIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""录入/更新某账号的敏感凭证明文源(管理员,只允许白名单内键)。
|
||||
|
||||
仅当 pubkey_pem 非空时才需要用现有公钥给新增值加密留档;这里统一存明文源,
|
||||
/creds 下发时实时用该账号公钥加密,故无需在此预加密。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = b.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
allowed = {k: v for k, v in b.values.items() if k in _ALLOWED_KEYS}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT pubkey_pem FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||
if row:
|
||||
conn.execute(
|
||||
"UPDATE client_creds SET creds = %s, updated_at = %s WHERE account = %s",
|
||||
(json.dumps(allowed, ensure_ascii=False), _now(), account))
|
||||
else:
|
||||
conn.execute(
|
||||
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, '', %s, %s)",
|
||||
(account, json.dumps(allowed, ensure_ascii=False), _now()))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "seeded_keys": sorted(allowed)}
|
||||
|
||||
|
||||
@router.get("/api/admin/creds/manage")
|
||||
def creds_manage(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 = conn.execute(
|
||||
"SELECT account, pubkey_pem, creds, updated_at FROM client_creds ORDER BY account").fetchall()
|
||||
return {
|
||||
"accounts": [{
|
||||
"account": r["account"],
|
||||
"has_pubkey": bool(r["pubkey_pem"]),
|
||||
"creds": json.loads(r["creds"] or "{}"),
|
||||
"updated_at": str(r["updated_at"] or ""),
|
||||
} for r in rows],
|
||||
"allowed_keys": list(_ALLOWED_KEYS),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/creds")
|
||||
def creds_fetch(authorization: str = Header(default="", alias="Authorization"),
|
||||
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:
|
||||
"""下发敏感凭证(**仅管理员可拉**)。鉴权:登录云令牌(Bearer) → 签名票据 → X-Admin-User。
|
||||
|
||||
解析出账号后校验 is_admin=1,非管理员一律 403(员工无法拉取,堵住越权窃取口子)。
|
||||
用账号上报的 RSA 公钥把每个明文值 OAEP 加密为 base64;无公钥或无明文源返回空。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
with _db() as conn:
|
||||
admin = conn.execute(
|
||||
"SELECT is_admin FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if not admin or not admin["is_admin"]:
|
||||
raise HTTPException(403, "仅管理员可拉取敏感凭证")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT pubkey_pem, creds FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||
if not row or not row["pubkey_pem"]:
|
||||
return {"account": account, "creds": {}}
|
||||
try:
|
||||
source = json.loads(row["creds"] or "{}")
|
||||
encrypted = {k: rsa_encrypt(row["pubkey_pem"], v)
|
||||
for k, v in source.items() if v is not None}
|
||||
except Exception as e: # noqa: BLE001
|
||||
raise HTTPException(500, f"凭证加密失败: {e}") from e
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE client_creds SET updated_at = %s WHERE account = %s",
|
||||
(_now(), account))
|
||||
conn.commit()
|
||||
return {"account": account, "creds": encrypted}
|
||||
@@ -126,4 +126,28 @@ def dingtalk_inline_qr(back: str = Query(default="", description="(兼容保留
|
||||
"&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)}
|
||||
return {"goto": quote(auth_url)}
|
||||
|
||||
|
||||
@router.get("/api/dingtalk/login-url")
|
||||
def dingtalk_login_url(back: str = Query(...),
|
||||
state: str = Query(default=""),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""构造钉钉扫码授权 URL(执行机代理调用):执行机无需自带钉钉应用凭证。
|
||||
|
||||
back 为执行机本机回跳地址(如 http://localhost:8799/auth/done),state 由执行机生成防回跳伪造;
|
||||
扫码后钉钉跳回 back,执行机再拿 code 走 /auth/exchange 换身份。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
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, "回跳地址非法(防止开放重定向)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": back,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state or back})
|
||||
return {"url": login_url}
|
||||
@@ -0,0 +1,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""大文件源管理 API(管理员):登记/更新内网直链、列表、启停、删除。
|
||||
|
||||
大文件(壳子安装包、Chrome 安装包等)走内网文件服务器,中心机只存其直链。
|
||||
发布动作由 agent_cli 完成:先传文件服务器拿 url,再经本接口登记。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from controlplane.core.auth import _check_token, _require_admin
|
||||
from controlplane.core.db import _db, _now
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class FileSourceIn(BaseModel):
|
||||
"""登记/更新一条大文件源。同一 category+version 重复提交则覆盖 url/notes/sha256/enabled。"""
|
||||
category: str = Field(default="", max_length=32)
|
||||
version: str = Field(default="", max_length=32)
|
||||
filename: str = Field(default="", max_length=255)
|
||||
url: str = Field(default="", max_length=2000)
|
||||
sha256: str = Field(default="", max_length=64)
|
||||
notes: str = Field(default="", max_length=512)
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class FileSourcePatch(BaseModel):
|
||||
"""启停 / 改说明。"""
|
||||
enabled: Optional[bool] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
def _rows_to_dicts(rows) -> list[dict]:
|
||||
out = []
|
||||
for r in rows:
|
||||
out.append({"id": r["id"], "category": r["category"], "version": r["version"],
|
||||
"filename": r["filename"], "url": r["url"], "sha256": r["sha256"],
|
||||
"notes": r["notes"], "enabled": bool(r["enabled"]),
|
||||
"updated_at": str(r["updated_at"] or "")})
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/api/admin/file-sources")
|
||||
def file_sources_list(category: str = "",
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""按 category 列出大文件源(可按 category 过滤,分组也可由 category 字段区分)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
if category.strip():
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources WHERE category = %s ORDER BY version, id",
|
||||
(category.strip(),)).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources ORDER BY category, version, id").fetchall()
|
||||
return {"category": category, "files": _rows_to_dicts(rows)}
|
||||
|
||||
|
||||
@router.post("/api/admin/file-sources")
|
||||
def file_sources_upsert(b: FileSourceIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""登记/覆盖一条大文件源(同一 category+version 去重)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
category, version = b.category.strip(), b.version.strip()
|
||||
url = b.url.strip()
|
||||
if not category:
|
||||
raise HTTPException(400, "category 不能为空")
|
||||
if not url:
|
||||
raise HTTPException(400, "url 不能为空")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM file_sources WHERE category = %s AND version = %s",
|
||||
(category, version)).fetchone()
|
||||
if row:
|
||||
conn.execute(
|
||||
"UPDATE file_sources SET filename=%s, url=%s, sha256=%s, notes=%s, "
|
||||
"enabled=%s, updated_at=%s WHERE id=%s",
|
||||
(b.filename.strip(), url, b.sha256.strip(), b.notes.strip(),
|
||||
int(b.enabled), _now(), row["id"]))
|
||||
fid = row["id"]
|
||||
else:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO file_sources(category, version, filename, url, sha256, notes, "
|
||||
"enabled, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
(category, version, b.filename.strip(), url, b.sha256.strip(),
|
||||
b.notes.strip(), int(b.enabled), _now()))
|
||||
fid = cur.lastrowid
|
||||
conn.commit()
|
||||
return {"ok": True, "id": fid, "category": category, "version": version}
|
||||
|
||||
|
||||
@router.patch("/api/admin/file-sources/{fid}")
|
||||
def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||
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)
|
||||
fields, vals = [], []
|
||||
if b.enabled is not None:
|
||||
fields.append("enabled = %s"); vals.append(int(b.enabled))
|
||||
if b.notes is not None:
|
||||
fields.append("notes = %s"); vals.append(b.notes.strip())
|
||||
if not fields:
|
||||
raise HTTPException(400, "无更新字段")
|
||||
fields.append("updated_at = %s"); vals.append(_now())
|
||||
with _db() as conn:
|
||||
cur = conn.execute(f"UPDATE file_sources SET {', '.join(fields)} WHERE id=%s",
|
||||
(*vals, fid))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@router.delete("/api/admin/file-sources/{fid}")
|
||||
def file_sources_delete(fid: int,
|
||||
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:
|
||||
cur = conn.execute("DELETE FROM file_sources WHERE id = %s", (fid,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@router.get("/api/file-sources/{category}")
|
||||
def file_sources_public_latest(category: str,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""客户端只读取某 category 最新启用的一条大文件源(带 X-API-Token 即可,无需 admin 票据)。
|
||||
|
||||
供执行机消费内网大文件直链(如 Chrome 安装包)。返回最近 version 的一条;无则 available=False。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, category, version, filename, url, sha256, notes FROM file_sources "
|
||||
"WHERE category = %s AND enabled = 1 ORDER BY version DESC, id DESC LIMIT 1",
|
||||
(category.strip(),)).fetchall()
|
||||
if not rows:
|
||||
return {"available": False, "category": category.strip()}
|
||||
r = rows[0]
|
||||
return {
|
||||
"available": True,
|
||||
"category": r["category"], "version": r["version"],
|
||||
"filename": r["filename"], "url": r["url"], "sha256": r["sha256"],
|
||||
"notes": r["notes"] or "",
|
||||
}
|
||||
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -14,7 +15,6 @@ 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()
|
||||
|
||||
@@ -78,52 +78,6 @@ def platforms_allowed(account: str = Query(default="", description="账号(旧
|
||||
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:
|
||||
@@ -136,7 +90,8 @@ 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():
|
||||
@@ -157,14 +112,19 @@ def me_license(account: str = Query(...), device: str = Query(default=""),
|
||||
"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": _now(), "plugins": plugins})
|
||||
return {"ticket": blob, "plugins": plugins, "issuedAt": _now()}
|
||||
"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 签名。"""
|
||||
"""签发管控清单:下架(revoke)/禁用(disable)/强制更新(force-update)聚合,Ed25519 签名。
|
||||
|
||||
与授权票据同窗口携带 expiresAt:执行机刷新票据时一并刷新管控清单。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
revoked = []
|
||||
disabled = []
|
||||
@@ -181,7 +141,8 @@ def me_control_list(x_api_token: str = Header(default="", alias="X-API-Token"))
|
||||
forced.append({"pluginId": pid, "minVersion": r["force_min_version"],
|
||||
"deadline": r["force_deadline"]})
|
||||
payload = {"revokedPlugins": revoked, "disabledPlugins": disabled,
|
||||
"forcedUpdates": forced, "updatedAt": _now()}
|
||||
"forcedUpdates": forced, "updatedAt": _now(),
|
||||
"expiresAt": int(time.time()) + config.LICENSE_TTL_DAYS * 24 * 3600}
|
||||
return {"ticket": crypto._sign_blob(payload), "control": payload}
|
||||
|
||||
|
||||
@@ -296,16 +257,44 @@ def _shell_meta() -> dict:
|
||||
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)
|
||||
m = _shell_meta()
|
||||
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", "")}
|
||||
"notes": m.get("notes", ""), "url": ""}
|
||||
|
||||
|
||||
@router.get("/api/shell/pkg")
|
||||
|
||||
Reference in New Issue
Block a user