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")
|
||||
|
||||
@@ -29,7 +29,9 @@ from controlplane import config
|
||||
from controlplane.core.db import _init_db, _seed
|
||||
from controlplane.apis import admin as api_admin
|
||||
from controlplane.apis import auth as api_auth
|
||||
from controlplane.apis import config_push as api_config_push
|
||||
from controlplane.apis import dingtalk as api_dingtalk
|
||||
from controlplane.apis import file_sources as api_file_sources
|
||||
from controlplane.apis import meta as api_meta
|
||||
from controlplane.apis import plugins as api_plugins
|
||||
|
||||
@@ -48,6 +50,8 @@ app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_plugins.router)
|
||||
app.include_router(api_auth.router)
|
||||
app.include_router(api_config_push.router)
|
||||
app.include_router(api_file_sources.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_admin.router)
|
||||
|
||||
|
||||
@@ -58,8 +58,7 @@ def _verify_admin_token(tok: str) -> str:
|
||||
|
||||
|
||||
def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
"""管理操作:校验内部凭证(X-API-Token) + 登录票据(X-Admin-Token)对应账号 is_admin=1。返回账号。"""
|
||||
_check_token(x_api_token)
|
||||
"""管理操作:仅校验登录票据(X-Admin-Token)对应账号 is_admin=1(浏览器管理面免 X-API-Token)。返回账号。"""
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
except Exception:
|
||||
@@ -78,11 +77,10 @@ def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||||
x_admin_user: str = "") -> str:
|
||||
"""解析请求身份(用户自助操作用,管理写操作仍走 _require_admin)。
|
||||
|
||||
1. 优先验签名票据 X-Admin-Token(控制台直连场景);
|
||||
1. 优先验签名票据 X-Admin-Token(控制台/浏览器直连场景,免 X-API-Token);
|
||||
2. 兜底接受底座正向代理注入的 X-Admin-User,但仅当 CONTROLPLANE_TOKEN 非空且
|
||||
请求携带匹配的 X-API-Token 时成立(防伪造;TOKEN 为空时拒绝,fail-closed)。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
if account:
|
||||
@@ -149,4 +147,19 @@ def _cloud_account(bearer: str) -> str:
|
||||
return rec["account"]
|
||||
if rec: # 过期顺手清理,防内存无限增长
|
||||
_cloud_tokens.pop(token, None)
|
||||
return ""
|
||||
return ""
|
||||
|
||||
|
||||
def _issue_cloud_token(account: str, nickname: str) -> str:
|
||||
"""签发云端会话 token 并写入共享存储(与 _cloud_account 同源,供 apis/auth /auth/exchange 调用)。
|
||||
|
||||
之前 apis/auth 里另建了一份同名 dict,写读不通导致 Bearer 永远解不出账号;这里统一出口。
|
||||
"""
|
||||
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": nickname}
|
||||
return token
|
||||
@@ -53,6 +53,8 @@ _load_dotenv()
|
||||
# 内部凭证(底座→统一后端的调用凭证)。为空则不强制(内网可信场景)。
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
CONTROLPLANE_PORT = int(os.getenv("CONTROLPLANE_PORT", "8800"))
|
||||
# 离线授权票据有效期(天):执行机最多离线该天数,超时须联网刷新票据后才可继续使用。
|
||||
LICENSE_TTL_DAYS = 7
|
||||
# MySQL 数据层(控制面唯一存储,无 SQLite 回退)。连接参数在 controlplane/.env 配置。
|
||||
MYSQL_HOST = os.getenv("MYSQL_HOST", "")
|
||||
MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306"))
|
||||
@@ -70,6 +72,16 @@ DINGTALK_APP_SECRET = os.getenv("DINGTALK_APP_SECRET", "")
|
||||
# 只要与用户实际访问地址、钉钉后台登记的回调域名一致即可。留空禁用扫码。
|
||||
DINGTALK_CALLBACK = os.getenv("DINGTALK_CALLBACK", "").rstrip("/")
|
||||
|
||||
# 客户端敏感凭证默认值参考(webhost 不再明文落盘,中心机 .env 为唯一可信明文源)。
|
||||
# 明文源只由管理员经 /api/admin/creds/seed 录入;客户端 register 不再自动填充本默认值
|
||||
# (防任何登录账号借 register 自证拿到全局密钥),本配置保留供管理台 seed 时参考/未来使用。
|
||||
# 键名 = 下发白名单键(去掉 CREDS_ 前缀),留空则该键不下发,需管理员用 /api/admin/creds/seed 录入。
|
||||
CREDS_DEFAULT = {
|
||||
_k.removeprefix("CREDS_"): os.getenv(_k, "").strip()
|
||||
for _k in ("CREDS_DINGTALK_APPKEY", "CREDS_DINGTALK_APPSECRET",
|
||||
"CREDS_DINGTALK_AGENT_ID", "CREDS_DINGTALK_CORP_ID")
|
||||
}
|
||||
|
||||
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > 首次随机生成并
|
||||
# 持久化到 .admin_secret(保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
|
||||
@@ -13,7 +13,10 @@ import json
|
||||
import secrets
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
|
||||
from controlplane.core import config
|
||||
|
||||
@@ -86,4 +89,22 @@ def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
|
||||
if len(sig) != 64:
|
||||
raise ValueError("bad signature len")
|
||||
pub.verify(sig, canon)
|
||||
return json.loads(canon)
|
||||
return json.loads(canon)
|
||||
|
||||
|
||||
# ==================== 执行机敏感凭证下发:RSA 加密 ====================
|
||||
def rsa_encrypt(pubkey_pem: str | bytes, plaintext: str) -> str:
|
||||
"""用执行机上报的 RSA 公钥加密敏感明文,返回 base64 密文串。
|
||||
|
||||
凭证值均为短串(口令/密钥),OAEP+SHA256 上限 ~190B(RSA-2048),已足够。
|
||||
供中心机下发 `/api/admin/creds` 时对每个敏感值加密使用。
|
||||
"""
|
||||
pem = pubkey_pem.encode() if isinstance(pubkey_pem, str) else pubkey_pem
|
||||
pub = serialization.load_pem_public_key(pem)
|
||||
if not isinstance(pub, rsa.RSAPublicKey):
|
||||
raise ValueError("pubkey 必须是 RSA 公钥")
|
||||
ct = pub.encrypt(
|
||||
plaintext.encode("utf-8"),
|
||||
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(), label=None))
|
||||
return base64.b64encode(ct).decode()
|
||||
@@ -19,7 +19,7 @@ from controlplane.core import config
|
||||
from controlplane.core.crypto import _hash_password
|
||||
|
||||
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
|
||||
_SCHEMA_VERSION = "20260916_001"
|
||||
_SCHEMA_VERSION = "20260917_001"
|
||||
|
||||
# 全量 DDL(11 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
|
||||
_DDL_TABLES = (
|
||||
@@ -180,6 +180,30 @@ _DDL_TABLES = (
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS client_creds (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)'
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
@@ -260,9 +284,10 @@ def _init_db() -> None:
|
||||
with _db() as conn:
|
||||
for ddl in _DDL_TABLES:
|
||||
conn.execute(ddl)
|
||||
conn.execute(
|
||||
"INSERT IGNORE INTO schema_migrations(version) VALUES (%s)",
|
||||
(_SCHEMA_VERSION,))
|
||||
for _ver in ("20260916_001", _SCHEMA_VERSION):
|
||||
conn.execute(
|
||||
"INSERT IGNORE INTO schema_migrations(version) VALUES (%s)",
|
||||
(_ver,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
|
||||
@@ -39,6 +39,18 @@ class AuthIn(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
class CredsRegisterIn(BaseModel):
|
||||
"""执行机上报 RSA 公钥(一次注册后中心机用其加密敏感凭证下发)。"""
|
||||
account: str
|
||||
pubkey_pem: str
|
||||
|
||||
|
||||
class CredsSeedIn(BaseModel):
|
||||
"""管理员录入/更新某执行机账号的敏感凭证明文源(集中存中心机 DB)。"""
|
||||
account: str
|
||||
values: dict[str, str]
|
||||
|
||||
|
||||
class DingTalkIn(BaseModel):
|
||||
account: str # 工号(作为统一账号)
|
||||
nickname: str = ""
|
||||
|
||||
Binary file not shown.
@@ -30,7 +30,7 @@
|
||||
<aside class="aside">
|
||||
<div class="aside-inner">
|
||||
<el-menu :default-active="activeKey" @select="onMenu">
|
||||
<el-menu-item v-for="m in menuOptions" :key="m.key" :index="m.key">
|
||||
<el-menu-item v-for="m in menu" :key="m.key" :index="m.key">
|
||||
<el-icon><component :is="m.icon" /></el-icon>
|
||||
<span>{{ m.label }}</span>
|
||||
</el-menu-item>
|
||||
@@ -49,7 +49,7 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ArrowDown, Lock, SwitchButton, Odometer, TrendCharts, Box, User, Key, Document } from '@element-plus/icons-vue'
|
||||
import { ArrowDown, Lock, SwitchButton, Odometer, TrendCharts, Box, User, Key, Document, Files } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import PasswordDialog from './components/PasswordDialog.vue'
|
||||
@@ -59,6 +59,8 @@ import AccountManageView from './views/AccountManageView.vue'
|
||||
import GrantManageView from './views/GrantManageView.vue'
|
||||
import StatsView from './views/StatsView.vue'
|
||||
import AuditView from './views/AuditView.vue'
|
||||
import CredsManageView from './views/CredsManageView.vue'
|
||||
import FileSourceManageView from './views/FileSourceManageView.vue'
|
||||
import { store, clearSession } from './store'
|
||||
import { adminMe } from './api'
|
||||
|
||||
@@ -68,8 +70,11 @@ const menuOptions = [
|
||||
{ label: '插件管理', key: 'plugins', icon: Box },
|
||||
{ label: '账号管理', key: 'accounts', icon: User },
|
||||
{ label: '权限授权', key: 'grants', icon: Key },
|
||||
{ label: '敏感凭证', key: 'creds', icon: Lock, admin: true },
|
||||
{ label: '大文件源', key: 'files', icon: Files, admin: true },
|
||||
{ label: '审计报表', key: 'audit', icon: Document },
|
||||
]
|
||||
const menu = computed(() => menuOptions.filter(m => !m.admin || store.isAdmin))
|
||||
|
||||
// 轻量 hash 路由:静态站刷新安全,零后端改动
|
||||
const KEY = {
|
||||
@@ -78,6 +83,8 @@ const KEY = {
|
||||
'#/plugins': 'plugins',
|
||||
'#/accounts': 'accounts',
|
||||
'#/grants': 'grants',
|
||||
'#/creds': 'creds',
|
||||
'#/files': 'files',
|
||||
'#/audit': 'audit',
|
||||
}
|
||||
const VIEWS = {
|
||||
@@ -86,6 +93,8 @@ const VIEWS = {
|
||||
'#/plugins': PluginManageView,
|
||||
'#/accounts': AccountManageView,
|
||||
'#/grants': GrantManageView,
|
||||
'#/creds': CredsManageView,
|
||||
'#/files': FileSourceManageView,
|
||||
'#/audit': AuditView,
|
||||
}
|
||||
const route = ref(VIEWS[location.hash] ? location.hash : '#/overview')
|
||||
|
||||
@@ -5,7 +5,17 @@ async function req(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) {}
|
||||
try {
|
||||
const detail = (await res.json()).detail
|
||||
// FastAPI 422 的 detail 是 [{loc,msg,type},…] 数组;普通错误是字符串/含 msg 的对象
|
||||
if (typeof detail === 'string') msg = detail
|
||||
else if (Array.isArray(detail)) {
|
||||
msg = detail.map((d) => {
|
||||
const where = Array.isArray(d.loc) ? d.loc.filter((p) => p !== 'body').join('.') : ''
|
||||
return where ? `${where}: ${d.msg}` : (d.msg || JSON.stringify(d))
|
||||
}).join(';')
|
||||
} else if (detail && typeof detail === 'object') msg = detail.msg || JSON.stringify(detail)
|
||||
} catch (_) { /* 非 JSON 响应,保留 HTTP 状态码提示 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
@@ -114,6 +124,40 @@ export async function adminReports(limit = 300) {
|
||||
export async function adminStats() {
|
||||
return req('/api/admin/stats', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminCredsList() {
|
||||
return req('/api/admin/creds/manage', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminCredsSeed(body) {
|
||||
return req('/api/admin/creds/seed', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminFileSources(category = '') {
|
||||
const qs = category ? '?category=' + encodeURIComponent(category) : ''
|
||||
return req('/api/admin/file-sources' + qs, { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminFileSourceCreate(body) {
|
||||
return req('/api/admin/file-sources', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminFileSourcePatch(id, body) {
|
||||
return req(`/api/admin/file-sources/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminFileSourceDelete(id) {
|
||||
return req(`/api/admin/file-sources/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' })
|
||||
})
|
||||
}
|
||||
export async function adminUpload(pluginId, name, version, file) {
|
||||
const fd = new FormData()
|
||||
fd.append('upload', file)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
// 图标沿用 @element-plus/icons-vue(纯 SVG 组件)
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import App from './App.vue'
|
||||
@@ -11,4 +12,5 @@ const app = createApp(App)
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component)
|
||||
}
|
||||
app.use(ElementPlus).mount('#app')
|
||||
// 中文语言包:日期选择器等组件的月份/按钮文案默认是英文,必须显式指定 locale
|
||||
app.use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>敏感凭证 <span class="badge">Creds</span></h3>
|
||||
<p>执行机敏感凭证的明文源(钉钉开放平台)。保存后客户端下次启动用 RSA 私钥解密拉取;留空 = 该键不下发</p>
|
||||
</div>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
<el-table :data="rows" v-loading="busy" size="default" style="width: 100%">
|
||||
<el-table-column prop="account" label="执行机账号" width="150">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.account }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="公钥" width="90">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.has_pubkey ? 'success' : 'info'" size="small" effect="light">
|
||||
{{ row.has_pubkey ? '已上报' : '未上报' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-for="k in keyCols" :key="k.key" :label="k.label" min-width="170" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span class="mono dim" :class="{ empty: !row.creds[k.key] }">{{ row.creds[k.key] || '(未配置)' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="updated_at" label="更新时间" width="170" />
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" :icon="EditPen" @click="openEdit(row)">编辑</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<el-empty description="暂无账号,客户端启动注册后自动出现" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="dlg" :title="`编辑凭证 · ${editing?.account || ''}`" width="540px">
|
||||
<div class="form">
|
||||
<div class="fitem" v-for="k in keyCols" :key="k.key">
|
||||
<label>{{ k.label }} <span class="dim mono">({{ k.key }})</span></label>
|
||||
<el-input v-model="form[k.key]" :type="k.key.includes('SECRET') ? 'password' : 'text'"
|
||||
:show-password="k.key.includes('SECRET')" placeholder="留空 = 不下发该键" />
|
||||
</div>
|
||||
<p class="tip">值仅管理台可见;保存后客户端下次启动拉取更新(离线用本地加密缓存)。</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="dlg = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { Refresh, EditPen } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminCredsList, adminCredsSeed } from '../api'
|
||||
|
||||
const KEY_COLS = [
|
||||
{ key: 'DINGTALK_APPKEY', label: 'AppKey' },
|
||||
{ key: 'DINGTALK_APPSECRET', label: 'AppSecret' },
|
||||
{ key: 'DINGTALK_AGENT_ID', label: 'AgentId' },
|
||||
{ key: 'DINGTALK_CORP_ID', label: 'CorpId' },
|
||||
]
|
||||
|
||||
const keyCols = KEY_COLS
|
||||
const busy = ref(false)
|
||||
const rows = ref([])
|
||||
const dlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const editing = ref(null)
|
||||
const form = ref({})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminCredsList()
|
||||
rows.value = r.accounts || []
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
|
||||
function openEdit(row) {
|
||||
editing.value = row
|
||||
form.value = {}
|
||||
keyCols.forEach(c => { form.value[c.key] = row.creds?.[c.key] || '' })
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!editing.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
const values = {}
|
||||
keyCols.forEach(c => { if (form.value[c.key]) values[c.key] = String(form.value[c.key]).trim() })
|
||||
const r = await adminCredsSeed({ account: editing.value.account, values })
|
||||
message.success(`已保存 ${r.seeded_keys.length} 个键(留空键已清除)`)
|
||||
dlg.value = false
|
||||
await refresh()
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.panel { padding: 22px 24px 26px; }
|
||||
.form { display: flex; flex-direction: column; gap: 16px; }
|
||||
.fitem { display: flex; flex-direction: column; gap: 7px; }
|
||||
.fitem label { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||
.fitem .dim { font-weight: 500; font-size: 12px; }
|
||||
.empty { color: var(--cp-ink-3); }
|
||||
.tip { font-size: 12px; color: var(--cp-ink-3); margin: 2px 0 0; }
|
||||
</style>
|
||||
@@ -0,0 +1,186 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>大文件源 <span class="badge">File Sources</span></h3>
|
||||
<p>内网大文件(壳子/Chrome 等)直链登记。中心机只存链接,文件本身走内网文件服务器</p>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<el-select v-model="filter" placeholder="按分类过滤" style="width: 150px" clearable @change="refresh">
|
||||
<el-option v-for="c in categories" :key="c" :label="c" :value="c" />
|
||||
</el-select>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">登记链接</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
<el-table :data="rows" v-loading="busy" size="default" style="width: 100%">
|
||||
<el-table-column prop="category" label="分类" width="110">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="catType(row.category)" size="small" effect="light">{{ row.category }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="version" label="版本" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ row.version }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="filename" label="文件" min-width="150" show-overflow-tooltip />
|
||||
<el-table-column label="内网直链" min-width="260" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span class="mono dim url">{{ row.url }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="SHA256" width="120">
|
||||
<template #default="{ row }">
|
||||
<el-button v-if="row.sha256" link type="primary" @click="copy(row.sha256, 'SHA256')">
|
||||
{{ row.sha256.slice(0, 8) }}…
|
||||
</el-button>
|
||||
<span v-else class="dim">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="说明" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.notes || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="updated_at" label="更新时间" width="160" />
|
||||
<el-table-column label="启用" width="70" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-switch :model-value="!!row.enabled" :loading="row._tog" @change="(v) => toggle(row, v)" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="copy(row.url, '链接')">复制</el-button>
|
||||
<el-button link type="danger" :icon="Delete" @click="remove(row)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<el-empty description="暂无登记的大文件源" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="dlg" title="登记内网直链" width="560px">
|
||||
<div class="form">
|
||||
<div class="fitem">
|
||||
<label>分类 <span class="dim">(shell / chrome / …)</span></label>
|
||||
<el-input v-model="form.category" placeholder="如 chrome" />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>版本</label>
|
||||
<el-input v-model="form.version" placeholder="如 1.0.0" />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>文件名</label>
|
||||
<el-input v-model="form.filename" placeholder="如 ChromeStandaloneSetup64.exe" />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>内网直链 url</label>
|
||||
<el-input v-model="form.url" placeholder="http://内网IP:8802/files/..." />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>SHA256 <span class="dim">(可选)</span></label>
|
||||
<el-input v-model="form.sha256" placeholder="文件校验值,客户端下载后校验" />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>说明 <span class="dim">(可选)</span></label>
|
||||
<el-input v-model="form.notes" type="textarea" :rows="2" placeholder="备注" />
|
||||
</div>
|
||||
<p class="tip">同一 分类+版本 会覆盖旧记录;删除仅移除中心机登记,不影响内网文件服务器上的文件。</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="dlg = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { Refresh, Plus, Delete } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message, ElMessageBox } from 'element-plus'
|
||||
import { adminFileSources, adminFileSourceCreate, adminFileSourcePatch, adminFileSourceDelete } from '../api'
|
||||
|
||||
const CATS = ['shell', 'chrome']
|
||||
const categories = CATS
|
||||
const busy = ref(false)
|
||||
const rows = ref([])
|
||||
const filter = ref('')
|
||||
const dlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const form = ref({})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminFileSources(filter.value || '')
|
||||
rows.value = r.files || []
|
||||
const seen = new Set(CATS)
|
||||
;(r.files || []).forEach((f) => seen.add(f.category))
|
||||
categories.length = 0
|
||||
;[...seen].sort().forEach((c) => categories.push(c))
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
|
||||
function catType(c) {
|
||||
return { shell: 'success', chrome: 'warning' }[c] || 'info'
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
form.value = { category: '', version: '', filename: '', url: '', sha256: '', notes: '', enabled: true }
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!form.value.category || !form.value.category.trim()) return message.error('分类不能为空')
|
||||
if (!form.value.url || !form.value.url.trim()) return message.error('内网直链不能为空')
|
||||
saving.value = true
|
||||
try {
|
||||
const { enabled, ...rest } = form.value
|
||||
const body = { ...rest, category: form.value.category.trim(), url: form.value.url.trim(), enabled: true }
|
||||
await adminFileSourceCreate(body)
|
||||
message.success('已登记')
|
||||
dlg.value = false
|
||||
await refresh()
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
async function toggle(row, v) {
|
||||
row._tog = true
|
||||
try { await adminFileSourcePatch(row.id, { enabled: v }); row.enabled = v; message.success(v ? '已启用' : '已停用') }
|
||||
catch (e) { message.error('操作失败:' + (e.message || e)) }
|
||||
finally { row._tog = false }
|
||||
}
|
||||
|
||||
async function remove(row) {
|
||||
try {
|
||||
await ElMessageBox.confirm(`删除「${row.category} ${row.version}」的登记?此操作仅移除中心机登记,不影响内网文件。`, '确认删除', { type: 'warning' })
|
||||
} catch (_) { return }
|
||||
try {
|
||||
await adminFileSourceDelete(row.id)
|
||||
message.success('已删除')
|
||||
await refresh()
|
||||
} catch (e) { message.error('删除失败:' + (e.message || e)) }
|
||||
}
|
||||
|
||||
async function copy(text, what) {
|
||||
try { await navigator.clipboard.writeText(text); message.success(what + '已复制') }
|
||||
catch (_) { message.error('复制失败,请手动选择') }
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.panel { padding: 22px 24px 26px; }
|
||||
.head-actions { display: flex; gap: 10px; align-items: center; }
|
||||
.form { display: flex; flex-direction: column; gap: 14px; }
|
||||
.fitem { display: flex; flex-direction: column; gap: 6px; }
|
||||
.fitem label { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||
.fitem .dim { font-weight: 500; font-size: 12px; }
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.url { font-size: 12px; }
|
||||
.tip { font-size: 12px; color: var(--cp-ink-3); margin: 0; }
|
||||
</style>
|
||||
@@ -73,88 +73,136 @@
|
||||
</div>
|
||||
|
||||
<!-- 编辑插件 -->
|
||||
<el-dialog v-model="editShow" :title="`编辑插件 · ${edit.pid}`" width="560px" align-center destroy-on-close>
|
||||
<el-form label-position="top">
|
||||
<el-form-item label="名称">
|
||||
<el-input v-model="edit.name" placeholder="插件显示名" />
|
||||
</el-form-item>
|
||||
<el-form-item label="分类">
|
||||
<el-input v-model="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||
</el-form-item>
|
||||
<el-form-item label="描述">
|
||||
<el-input v-model="edit.description" type="textarea" :rows="2" placeholder="插件用途说明" />
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-radio-group v-model="edit.status">
|
||||
<el-radio-button value="published">正常发布</el-radio-button>
|
||||
<el-radio-button value="disabled">禁用(停止分发)</el-radio-button>
|
||||
<el-radio-button value="revoked">下架(禁止运行)</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="强制更新(留空表示不强制)">
|
||||
<div class="force-row">
|
||||
<div class="force-line">
|
||||
<el-input v-model="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 180px" class="mono" />
|
||||
<el-input v-model="edit.force_dl" type="datetime-local" placeholder="截止时间" style="width: 200px" class="mono" />
|
||||
</div>
|
||||
<span class="hint">到达截止时间后,未升级到该版本的部署机会被禁止启动</span>
|
||||
<el-dialog v-model="editShow" width="720px" align-center destroy-on-close>
|
||||
<template #header>
|
||||
<div class="ed-head">
|
||||
<span class="ed-avatar">{{ (edit.name || edit.pid || '?').slice(0, 1) }}</span>
|
||||
<div class="ed-headmeta">
|
||||
<div class="ed-title mono">{{ edit.pid }}</div>
|
||||
<div class="ed-sub">修改基础信息、发布状态与强制更新策略</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" class="ed-form">
|
||||
<div class="ed-sec">
|
||||
<div class="ed-sec-title">基本信息</div>
|
||||
<div class="form-2col">
|
||||
<el-form-item label="插件名称">
|
||||
<el-input v-model="edit.name" placeholder="插件显示名" />
|
||||
</el-form-item>
|
||||
<el-form-item label="分类">
|
||||
<el-input v-model="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ed-sec">
|
||||
<div class="ed-sec-title">插件描述</div>
|
||||
<el-form-item>
|
||||
<el-input v-model="edit.description" type="textarea" :autosize="{ minRows: 5, maxRows: 12 }"
|
||||
maxlength="500" show-word-limit placeholder="插件用途说明(支持换行,执行端与详情页均会展示)" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="ed-sec">
|
||||
<div class="ed-sec-title">发布状态</div>
|
||||
<el-form-item>
|
||||
<el-radio-group v-model="edit.status">
|
||||
<el-radio-button value="published">正常发布</el-radio-button>
|
||||
<el-radio-button value="disabled">禁用(停止分发)</el-radio-button>
|
||||
<el-radio-button value="revoked">下架(禁止运行)</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="ed-sec">
|
||||
<div class="ed-sec-title">强制更新 <span class="ed-opt">可选 · 两项都填才会生效</span></div>
|
||||
<div class="force-box">
|
||||
<div class="force-line">
|
||||
<el-input v-model="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 190px" class="mono" />
|
||||
<el-date-picker v-model="edit.force_dl" type="datetime" value-format="YYYY-MM-DD[T]HH:mm"
|
||||
format="YYYY-MM-DD HH:mm" placeholder="截止时间" style="width: 220px" class="mono" />
|
||||
</div>
|
||||
<div class="hint">到达截止时间后,未升级到该版本的部署机会被禁止启动;留空表示不强制</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="editShow = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveEdit">保存修改</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 插件详情 -->
|
||||
<el-dialog v-model="detailShow" :title="`插件详情 · ${detail?.id || ''}`" width="640px" align-center destroy-on-close>
|
||||
<el-dialog v-model="detailShow" width="780px" align-center destroy-on-close>
|
||||
<template #header>
|
||||
<div class="dt-head" v-if="detail">
|
||||
<span class="dt-avatar">{{ (detail.name || detail.id || '?').slice(0, 1) }}</span>
|
||||
<div class="dt-headmeta">
|
||||
<div class="dt-title-row">
|
||||
<span class="dt-id mono">{{ detail.id }}</span>
|
||||
<el-tag size="small" round effect="light" :type="statusMeta[detail.status]?.type || 'info'">
|
||||
{{ statusMeta[detail.status]?.label || detail.status || '—' }}
|
||||
</el-tag>
|
||||
<el-tag v-if="detail.category" size="small" round effect="plain" type="info">{{ detail.category }}</el-tag>
|
||||
</div>
|
||||
<div class="dt-name">{{ detail.name || '未命名插件' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="detail" class="plg-detail">
|
||||
<div class="d-head">
|
||||
<span class="d-id mono">{{ detail.id }}</span>
|
||||
<span class="d-name">{{ detail.name }}</span>
|
||||
<el-tag size="small" round effect="light" :type="statusMeta[detail.status]?.type || 'info'">
|
||||
{{ statusMeta[detail.status]?.label || detail.status || '—' }}
|
||||
</el-tag>
|
||||
<div class="dt-grid">
|
||||
<div class="dt-item">
|
||||
<el-icon class="dt-ic"><Box /></el-icon>
|
||||
<div><label>最新版本</label><span class="mono">{{ detail.latest_version || '—' }}</span></div>
|
||||
</div>
|
||||
<div class="dt-item">
|
||||
<el-icon class="dt-ic"><Files /></el-icon>
|
||||
<div><label>表单字段</label><span class="mono">{{ detail.field_count || 0 }} 项</span></div>
|
||||
</div>
|
||||
<div class="dt-item">
|
||||
<el-icon class="dt-ic"><User /></el-icon>
|
||||
<div><label>授权账号</label><span class="mono">{{ detail.accounts?.length || 0 }} 个</span></div>
|
||||
</div>
|
||||
<div class="dt-item">
|
||||
<el-icon class="dt-ic" :class="{ 'dt-ic-on': detail.force_min_version && detail.force_deadline }"><Clock /></el-icon>
|
||||
<div><label>强制更新</label><span>{{ forceText(detail) }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-grid">
|
||||
<div class="d-item"><label>分类</label><span>{{ detail.category || '—' }}</span></div>
|
||||
<div class="d-item"><label>最新版本</label><span class="mono">{{ detail.latest_version || '—' }}</span></div>
|
||||
<div class="d-item"><label>表单字段</label><span class="mono">{{ detail.field_count || 0 }}</span></div>
|
||||
<div class="d-item"><label>强制更新</label><span>{{ forceText(detail) }}</span></div>
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">插件描述</div>
|
||||
<p class="dt-desc">{{ detail.description || '暂无描述' }}</p>
|
||||
</div>
|
||||
|
||||
<div class="d-sec"><label>描述</label><p class="d-desc">{{ detail.description || '—' }}</p></div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>能力</label>
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">能力声明</div>
|
||||
<div class="tags" v-if="detail.capabilities?.length">
|
||||
<el-tag v-for="c in detail.capabilities" :key="c" size="small" effect="plain" round>{{ c }}</el-tag>
|
||||
<el-tag v-for="c in detail.capabilities" :key="c" size="small" effect="plain" round class="mono">{{ c }}</el-tag>
|
||||
</div>
|
||||
<span v-else class="dim">—</span>
|
||||
</div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>版本历史</label>
|
||||
<div class="vlist" v-if="detail.versions?.length">
|
||||
<div class="vrow" v-for="v in detail.versions" :key="v.version">
|
||||
<el-tag size="small" round effect="light" class="mono"
|
||||
:type="v.version === detail.latest_version ? 'primary' : 'info'">{{ v.version }}</el-tag>
|
||||
<span class="vtime mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||
<div class="dt-cols">
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">版本历史</div>
|
||||
<div class="vlist" v-if="detail.versions?.length">
|
||||
<div class="vrow" v-for="v in detail.versions" :key="v.version">
|
||||
<el-tag size="small" round effect="light" class="mono"
|
||||
:type="v.version === detail.latest_version ? 'primary' : 'info'">{{ v.version }}</el-tag>
|
||||
<el-tag v-if="v.version === detail.latest_version" size="small" round effect="plain"
|
||||
type="success" class="v-latest">当前</el-tag>
|
||||
<span class="vtime mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span v-else class="dim">暂无版本</span>
|
||||
</div>
|
||||
<span v-else class="dim">暂无版本</span>
|
||||
</div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>授权账号</label>
|
||||
<div class="tags" v-if="detail.accounts?.length">
|
||||
<el-tag v-for="a in detail.accounts" :key="a" size="small" effect="plain" type="success" round class="mono">{{ a }}</el-tag>
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">授权账号</div>
|
||||
<div class="tags" v-if="detail.accounts?.length">
|
||||
<el-tag v-for="a in detail.accounts" :key="a" size="small" effect="plain" type="success" round class="mono">{{ a }}</el-tag>
|
||||
</div>
|
||||
<span v-else class="dim">未授权任何账号,执行端不可见</span>
|
||||
</div>
|
||||
<span v-else class="dim">未授权</span>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
@@ -167,7 +215,7 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View } from '@element-plus/icons-vue'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View, Box, Files, User, Clock } from '@element-plus/icons-vue'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
@@ -225,9 +273,10 @@ async function saveEdit() {
|
||||
saving.value = true
|
||||
try {
|
||||
const body = { name: edit.name, category: edit.category, description: edit.description, status: edit.status }
|
||||
// 强制更新:min 与 deadline 均填则成对下发;否则清除强制更新
|
||||
body.force_min_version = edit.force_min || null
|
||||
body.force_deadline = edit.force_dl ? new Date(edit.force_dl).toISOString() : null
|
||||
// 强制更新:min 与 deadline 均填则成对下发;否则清除强制更新。
|
||||
// 注意:后端 PluginPatchIn 的 str 字段不接受 null,空值必须传 ''(否则 422 保存失败)
|
||||
body.force_min_version = edit.force_min || ''
|
||||
body.force_deadline = edit.force_dl ? new Date(edit.force_dl).toISOString() : ''
|
||||
body.clear_force = !(edit.force_min && edit.force_dl)
|
||||
await adminPluginPatch(edit.pid, body)
|
||||
message.success(`已更新插件 ${edit.pid}`)
|
||||
@@ -271,27 +320,53 @@ onMounted(refresh)
|
||||
.up-form :deep(.el-form-item) { margin-bottom: 16px; }
|
||||
.file-row { display: flex; align-items: center; gap: 10px; }
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); margin-top: 2px; line-height: 1.7; }
|
||||
.force-row { display: flex; flex-direction: column; gap: 8px; width: 100%; }
|
||||
.force-line { display: flex; gap: 10px; }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
.cell-ops { display: flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.cell-ops .el-button { padding: 0 4px; }
|
||||
.cell-ops .el-button + .el-button { margin-left: 0; }
|
||||
|
||||
/* 插件详情 */
|
||||
.plg-detail { display: flex; flex-direction: column; gap: 18px; }
|
||||
.d-head { display: flex; align-items: center; gap: 10px; }
|
||||
.d-id { font-size: 16px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.d-name { font-size: 15px; color: var(--cp-ink-2); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.d-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
|
||||
.d-item { display: flex; flex-direction: column; gap: 5px; padding: 12px 14px; background: var(--cp-panel-2); border-radius: 12px; }
|
||||
.d-item label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.d-item span { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); }
|
||||
.d-sec { display: flex; flex-direction: column; gap: 8px; }
|
||||
.d-sec > label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.d-desc { margin: 0; font-size: 13px; line-height: 1.7; color: var(--cp-ink); background: var(--cp-panel-2); padding: 10px 14px; border-radius: 10px; }
|
||||
.vlist { display: flex; flex-direction: column; gap: 6px; }
|
||||
.vrow { display: flex; align-items: center; gap: 12px; }
|
||||
.vtime { font-size: 12px; }
|
||||
/* 弹窗通用 */
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
.form-2col { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); line-height: 1.7; }
|
||||
|
||||
/* 编辑弹窗:分区卡片 */
|
||||
.ed-head { display: flex; align-items: center; gap: 12px; }
|
||||
.ed-avatar { width: 42px; height: 42px; border-radius: 12px; display: grid; place-items: center; color: #fff; font-size: 18px; font-weight: 800; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); box-shadow: var(--cp-shadow); flex-shrink: 0; }
|
||||
.ed-headmeta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.ed-title { font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.ed-sub { font-size: 12px; color: var(--cp-ink-3); }
|
||||
.ed-sec { margin-bottom: 12px; padding: 13px 16px 3px; background: var(--cp-panel-2); border-radius: 12px; }
|
||||
.ed-sec :deep(.el-form-item) { margin-bottom: 13px; }
|
||||
.ed-sec-title { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 800; color: var(--cp-ink-2); letter-spacing: .5px; margin-bottom: 10px; }
|
||||
.ed-sec-title::before { content: ''; width: 3px; height: 13px; border-radius: 2px; background: var(--cp-blue); }
|
||||
.ed-opt { font-weight: 500; color: var(--cp-ink-3); letter-spacing: 0; }
|
||||
.force-box { display: flex; flex-direction: column; gap: 8px; padding-bottom: 13px; }
|
||||
.force-line { display: flex; gap: 10px; }
|
||||
|
||||
/* 详情弹窗:头部 + 统计卡 + 分区 */
|
||||
.plg-detail { display: flex; flex-direction: column; gap: 14px; max-height: 66vh; overflow-y: auto; padding-right: 6px; }
|
||||
.dt-head { display: flex; align-items: center; gap: 12px; }
|
||||
.dt-avatar { width: 46px; height: 46px; border-radius: 13px; display: grid; place-items: center; color: #fff; font-size: 20px; font-weight: 800; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); box-shadow: var(--cp-shadow); flex-shrink: 0; }
|
||||
.dt-headmeta { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||
.dt-title-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.dt-id { font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.dt-name { font-size: 13px; color: var(--cp-ink-2); }
|
||||
.dt-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
|
||||
.dt-item { display: flex; align-items: center; gap: 10px; padding: 12px 14px; background: var(--cp-panel-2); border-radius: 12px; min-width: 0; }
|
||||
.dt-ic { font-size: 20px; color: var(--cp-ink-3); flex-shrink: 0; }
|
||||
.dt-ic-on { color: var(--cp-amber); }
|
||||
.dt-item div { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||
.dt-item label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.dt-item span { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.dt-sec { display: flex; flex-direction: column; }
|
||||
.dt-desc { margin: 0; font-size: 13px; line-height: 1.9; color: var(--cp-ink); background: var(--cp-panel-2); padding: 12px 16px; border-radius: 10px; white-space: pre-wrap; word-break: break-word; }
|
||||
.dt-cols { display: grid; grid-template-columns: 1.15fr .85fr; gap: 14px; align-items: start; }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.vlist { display: flex; flex-direction: column; gap: 8px; }
|
||||
.vrow { display: flex; align-items: center; gap: 8px; padding: 7px 10px; background: var(--cp-panel-2); border-radius: 9px; }
|
||||
.vtime { font-size: 12px; margin-left: auto; }
|
||||
.dim-sm { color: var(--cp-ink-3); }
|
||||
.dim { font-size: 12px; color: var(--cp-ink-3); }
|
||||
</style>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -10,12 +10,13 @@
|
||||
- 查看插件 / 账号 / 运行统计
|
||||
|
||||
鉴权:
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。
|
||||
本脚本运行在中心机本机,直接复用 desktop/controlplane/.env 与 .admin_secret:
|
||||
- X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
- X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret
|
||||
对指定管理员账号临时签发短期票据(与 app.py 完全一致,签名不可伪造)。
|
||||
因此本 CLI 只在"中心机本机 + 拥有管理密钥"的环境下可用,等价于本地管理台白名单。
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。管理票据两种获取方式:
|
||||
- 密码登录(推荐,任意机器可用):--password 或环境变量 AGENT_ADMIN_PASSWORD,
|
||||
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret 本地自签。
|
||||
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
|
||||
@@ -61,6 +62,9 @@ _load_dotenv()
|
||||
BASE_URL = os.getenv("CONTROLPLANE_AGENT_BASE", "").rstrip("/") or \
|
||||
f"http://127.0.0.1:{os.getenv('CONTROLPLANE_PORT', '8800')}"
|
||||
API_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 内网文件服务器:上传直链来源(复用 controlplane/.env 新增键)
|
||||
FILESERVER_BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/")
|
||||
FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
@@ -86,17 +90,20 @@ def _mint_admin_token(account: str, secret: str) -> str:
|
||||
class Client:
|
||||
"""携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。"""
|
||||
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str):
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str, token: str = ""):
|
||||
self.base = base
|
||||
self.api_token = api_token
|
||||
self.admin = admin
|
||||
self.secret = secret
|
||||
self.token = token # 密码登录换取的票据;非空时直接使用,不再本地自签
|
||||
|
||||
def _headers(self, json_body: bool = True) -> dict:
|
||||
h = {}
|
||||
if self.api_token:
|
||||
h["X-API-Token"] = self.api_token
|
||||
if self.admin and self.secret:
|
||||
if self.admin and self.token:
|
||||
h["X-Admin-Token"] = self.token
|
||||
elif self.admin and self.secret:
|
||||
h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret)
|
||||
if json_body:
|
||||
h["Content-Type"] = "application/json"
|
||||
@@ -178,6 +185,68 @@ def _plugin_rows(plugins) -> None:
|
||||
f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||
|
||||
|
||||
def _run_file(args: argparse.Namespace, c: Client) -> int:
|
||||
"""file push / list / rm:内网大文件源管理。"""
|
||||
try:
|
||||
import requests as _rq
|
||||
except ModuleNotFoundError:
|
||||
raise SystemExit("[x] 缺少 requests,请用项目 .venv 运行。")
|
||||
fcmd = args.file_cmd
|
||||
|
||||
if fcmd == "push":
|
||||
path = Path(args.path)
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"[x] 文件不存在:{path}")
|
||||
if not FILESERVER_BASE_URL or not FILESERVER_TOKEN:
|
||||
raise SystemExit("[x] 未配置内网文件服务器:请设 controlplane/.env 的 "
|
||||
"FILESERVER_BASE_URL 与 FILESERVER_TOKEN")
|
||||
# 第一步:传到文件服务器
|
||||
try:
|
||||
with open(path, "rb") as fp:
|
||||
r = _rq.post(f"{FILESERVER_BASE_URL}/api/upload",
|
||||
headers={"X-API-Token": FILESERVER_TOKEN},
|
||||
files={"upload": (path.name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
except _rq.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接内网文件服务器 {FILESERVER_BASE_URL}({exc})")
|
||||
if r.status_code >= 400:
|
||||
raise SystemExit(f"[x] 上传到文件服务器失败 HTTP {r.status_code}:{r.text[:200]}")
|
||||
up = r.json()
|
||||
url = up.get("url", "")
|
||||
if not url:
|
||||
raise SystemExit("[x] 文件服务器未返回 url")
|
||||
sha256 = args.sha256 or up.get("sha256", "")
|
||||
# 第二步:登记到中心机 file_sources
|
||||
body = {"category": args.category, "version": args.version,
|
||||
"filename": up.get("filename", path.name), "url": url,
|
||||
"sha256": sha256, "notes": args.notes, "enabled": True}
|
||||
rec = c.call("POST", "/api/admin/file-sources", body)
|
||||
print(f"[ok] 已登记 {args.category} v{args.version or '?'} → {url}")
|
||||
print(f" id={rec.get('id')} filename={path.name} sha256={str(sha256)[:16]}…")
|
||||
return 0
|
||||
|
||||
if fcmd == "list":
|
||||
data = c.call("GET", f"/api/admin/file-sources?category={args.category}", None, False)
|
||||
files = data.get("files", [])
|
||||
if not files:
|
||||
print("(暂无大文件源)")
|
||||
return 0
|
||||
print(f"{'ID':<4}{'分类':<10}{'版本':<12}{'启用':<6}文件名 / 链接")
|
||||
for f in files:
|
||||
print(f"{str(f.get('id')):<4}{str(f.get('category') or ''):<10}"
|
||||
f"{str(f.get('version') or ''):<12}{'是' if f.get('enabled') else '否':<6}"
|
||||
f"{f.get('filename') or ''}")
|
||||
print(f" {f.get('url') or ''}")
|
||||
return 0
|
||||
|
||||
if fcmd == "rm":
|
||||
r = c.call("DELETE", f"/api/admin/file-sources/{args.id}", None, False)
|
||||
print(f"[ok] 已删除登记 id={args.id}")
|
||||
return 0
|
||||
|
||||
raise SystemExit(f"[x] 未知 file 子命令:{fcmd}")
|
||||
|
||||
|
||||
# ================================ main ================================
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
@@ -186,6 +255,9 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", ""),
|
||||
help="用于签发管理票据的管理员账号(须 is_admin=1)")
|
||||
parser.add_argument("--password", default=os.getenv("AGENT_ADMIN_PASSWORD", ""),
|
||||
dest="admin_password",
|
||||
help="管理员密码(密码登录模式,任意机器可用;须放在子命令之前。留空则回退本机密钥自签票据)")
|
||||
parser.add_argument("--base", default=BASE_URL, help="中心机服务地址")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
@@ -259,16 +331,43 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
p_shell.add_argument("--notes", default="", help="更新说明(可选,执行机前端提示展示)")
|
||||
p_shell.add_argument("--sha256", default="", help="安装包 sha256(可选,缺省自动计算)")
|
||||
|
||||
p_file = sub.add_parser("file", help="内网大文件源管理:push/list/rm")
|
||||
file_sub = p_file.add_subparsers(dest="file_cmd", required=True)
|
||||
p_fpush = file_sub.add_parser("push", help="上传到内网文件服务器并登记到中心机")
|
||||
p_fpush.add_argument("path", help="本地文件路径")
|
||||
p_fpush.add_argument("--category", required=True, help="分类:shell/chrome/browser 等")
|
||||
p_fpush.add_argument("--version", default="", help="版本号(可选)")
|
||||
p_fpush.add_argument("--notes", default="", help="说明(可选)")
|
||||
p_fpush.add_argument("--sha256", default="", help="sha256(可选,缺省自动计算)")
|
||||
p_flist = file_sub.add_parser("list", help="列出大文件源")
|
||||
p_flist.add_argument("--category", default="", help="按分类过滤")
|
||||
p_frm = file_sub.add_parser("rm", help="删除中心机登记(不动内网服务器文件)")
|
||||
p_frm.add_argument("id", type=int, help="file_sources.id")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> int:
|
||||
if not args.admin:
|
||||
raise SystemExit("[x] 未指定管理员账号:请用 --admin <账号> 或设置环境变量 AGENT_ADMIN_ACCOUNT。")
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),无法签发管理票据。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
if args.admin_password.strip():
|
||||
# 密码登录模式(推荐,任意机器可用):账号+密码换 1 小时票据,主密钥不出服务器
|
||||
c = Client(args.base, API_TOKEN, args.admin, "")
|
||||
r = c.call("POST", "/api/admin/auth",
|
||||
{"account": args.admin, "password": args.admin_password})
|
||||
if not r.get("token"):
|
||||
raise SystemExit("[x] 登录成功但未返回票据,请检查中心机版本。")
|
||||
if not r.get("is_admin"):
|
||||
raise SystemExit(f"[x] 账号 {args.admin} 不是管理员(is_admin=0),无法执行管理操作。")
|
||||
c.token = str(r["token"])
|
||||
print(f"[ok] 已以 {args.admin} 登录 {args.base}(密码模式,票据 1 小时有效)")
|
||||
else:
|
||||
# 本机密钥自签模式(中心机本机):复用 .env/.admin_secret 本地签发票据
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),"
|
||||
"无法签发管理票据;远程机器请改用密码登录:--password 或环境变量 AGENT_ADMIN_PASSWORD。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
cmd = args.command
|
||||
|
||||
if cmd == "shell-release":
|
||||
@@ -278,6 +377,9 @@ def _run(args: argparse.Namespace) -> int:
|
||||
print(f" 各执行机下次启动自动检测下载,前端提示后点击「重启更新」即静默升级。")
|
||||
return 0
|
||||
|
||||
if cmd == "file":
|
||||
return _run_file(args, c)
|
||||
|
||||
if cmd == "publish":
|
||||
r = c.upload_pkg(args.pkg, args.plugin_id, args.name, args.version)
|
||||
print(f"[ok] 已发布 {r.get('plugin_id')} v{r.get('version')} → {r.get('filename')}")
|
||||
|
||||
@@ -187,3 +187,31 @@ CREATE TABLE IF NOT EXISTS system_settings (
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机敏感凭证:中心机统一存明文源,下发时用执行机 RSA 公钥加密为密文
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS client_creds (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 大文件源:内网直链,走内网文件服务器(中心机不存大包)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)';
|
||||
|
||||
Reference in New Issue
Block a user