diff --git a/controlplane/agent_cli.py b/controlplane/agent_cli.py new file mode 100644 index 0000000..421dd9b --- /dev/null +++ b/controlplane/agent_cli.py @@ -0,0 +1,351 @@ +# -*- coding: utf-8 -*- +"""agent 脚手架 · 中心机插件发布与账号权限管理 CLI(单文件自包含)。 + +用途:让 agent / 运维以命令行方式管理中心机,无需打开浏览器即可: + - 发布 / 删除插件包(按最近 3 版自动裁剪保留) + - 变更插件状态(published / disabled / revoked)与强制更新阈值 + - 建号 / 重置密码 / 改部门昵称 / 授撤销管理员 / 删除账号 + - 按账号授予 / 撤销插件与平台权限 + - 查看插件 / 账号 / 运行统计 + +鉴权: + 管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。 + 本脚本运行在中心机本机,直接复用 controlplane/.env 与 .admin_secret: + - X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。 + - X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret + 对指定管理员账号临时签发短期票据(与 app.py 完全一致,签名不可伪造)。 + 因此本 CLI 只在"中心机本机 + 拥有管理密钥"的环境下可用,等价于本地管理台白名单。 + +管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。 + +运行(项目 .venv): + python -m controlplane.agent_cli publish plugin.zip --id report --version 1.2.0 + python -m controlplane.agent_cli plugins + python -m controlplane.agent_cli grant alice report # 默认授予 download+run + python -m controlplane.agent_cli users +需一次性传参的自包含要求:无外部参数依赖,配置固化/读取 .env 即可。 +""" +from __future__ import annotations + +import argparse +import base64 +import hashlib +import hmac +import json +import os +import time +from pathlib import Path +from typing import Optional + +APP_DIR = Path(__file__).resolve().parent + + +def _load_dotenv() -> None: + """读取 controlplane/.env(同 app.py 规则:环境变量优先,不覆盖已存在值)。""" + env_path = APP_DIR / ".env" + if not env_path.is_file(): + return + for _ln in env_path.read_text(encoding="utf-8").splitlines(): + _line = _ln.strip() + if not _line or _line.startswith("#") or "=" not in _line: + continue + _k, _v = _line.split("=", 1) + k, v = _k.strip(), _v.strip() + if k and k not in os.environ: + os.environ[k] = v + + +_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", "") + + +def _admin_secret() -> str: + """与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret。""" + cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or "" + if cand: + return cand + _f = APP_DIR / ".admin_secret" + if _f.is_file(): + return _f.read_text(encoding="utf-8").strip() + return "" + + +def _mint_admin_token(account: str, secret: str) -> str: + """临时签发 1 小时管理票据(算法必须与 app._sign_admin_token 一致)。""" + payload = base64.urlsafe_b64encode( + json.dumps({"a": account, "e": int(time.time()) + 3600}, separators=(",", ":")).encode() + ).decode().rstrip("=") + sig = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest() + return f"{payload}.{sig}" + + +class Client: + """携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。""" + + def __init__(self, base: str, api_token: str, admin: str, secret: str): + self.base = base + self.api_token = api_token + self.admin = admin + self.secret = secret + + 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: + h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret) + if json_body: + h["Content-Type"] = "application/json" + return h + + def call(self, method: str, path: str, json_body: Optional[dict] = None, + _hdrs_json: Optional[bool] = None) -> dict: + import requests + url = self.base + path # path 已是完整路径(含 query) + try: + if json_body is not None: + r = requests.request(method, url, headers=self._headers(True), json=json_body, timeout=30) + else: + r = requests.request(method, url, headers=self._headers(False), timeout=30) + except requests.ConnectionError as exc: + raise SystemExit(f"[x] 无法连接中心机 {self.base}({exc})。请确认服务已启动。") + try: + data = r.json() + except ValueError: + data = {"raw": r.text[:300]} + if r.status_code >= 400: + detail = data.get("detail") if isinstance(data, dict) else data + if isinstance(detail, dict): + detail = detail.get("msg") or detail + raise SystemExit(f"[x] HTTP {r.status_code}:{detail or r.text[:200]}") + return data if isinstance(data, dict) else {"result": data} + + def upload_pkg(self, path: str, plugin_id: str, name: str, version: str) -> dict: + import requests + import urllib.parse + qs = urllib.parse.urlencode({"plugin_id": plugin_id, "name": name, "version": version}) + with open(path, "rb") as fp: + r = requests.post(f"{self.base}/api/admin/pkg?{qs}", + headers=self._headers(False), + files={"upload": (Path(path).name, fp, "application/zip")}, + timeout=60) + try: + data = r.json() + except ValueError: + data = {"raw": r.text[:300]} + if r.status_code >= 400: + detail = data.get("detail") if isinstance(data, dict) else data + raise SystemExit(f"[x] HTTP {r.status_code}:{detail}") + return data + + +# ------------------------------ 输出辅助 ------------------------------ +def _plugin_rows(plugins) -> None: + """overview 的 plugins 为列表(含版本/授权明细),此处只打印核心字段。""" + rows = plugins if isinstance(plugins, list) else \ + (list(plugins.values()) if isinstance(plugins, dict) else []) + if not rows: + print("(暂无插件)") + return + print(f"{'ID':<28}{'名称':<16}{'最新版':<10}{'状态':<12}账号数") + for p in rows: + if not isinstance(p, dict): + continue + print(f"{str(p.get('id', '')):<28}{str(p.get('name') or ''):<16}" + f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}") + + +# ================================ main ================================ +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="agent_cli", + description="37du 中心机 · agent 插件发布与管理 CLI", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", ""), + help="用于签发管理票据的管理员账号(须 is_admin=1)") + parser.add_argument("--base", default=BASE_URL, help="中心机服务地址") + sub = parser.add_subparsers(dest="command", required=True) + + p_pub = sub.add_parser("publish", help="发布插件包 zip(自动裁剪保留最近 3 版)") + p_pub.add_argument("pkg", help="插件 zip 路径") + p_pub.add_argument("--id", dest="plugin_id", required=True, help="插件 ID(须与 plugin.json 内 id 一致)") + p_pub.add_argument("--name", default="", help="插件名称(缺省取 plugin.json 内 name 或 ID)") + p_pub.add_argument("--version", required=True, help="版本号,如 1.2.0") + + sub.add_parser("plugins", help="列出插件清单") + + p_del = sub.add_parser("plugin-del", help="删除插件(连带全部版本、授权、磁盘包)") + p_del.add_argument("plugin_id") + + p_status = sub.add_parser("plugin-status", help="变更插件状态/强制更新阈值") + p_status.add_argument("plugin_id") + p_status.add_argument("--status", choices=["published", "disabled", "revoked"], default="", + help="新状态(留空不改变)") + p_status.add_argument("--force-min-version", default="", help="强制最低版本(与 --force-deadline 成对)") + p_status.add_argument("--force-deadline", default="", help="强制更新截止时间(ISO 字符串)") + p_status.add_argument("--clear-force", action="store_true", help="清除强制更新配置") + + sub.add_parser("users", help="列出账号清单") + + p_user = sub.add_parser("user-add", help="新建账号") + p_user.add_argument("account") + p_user.add_argument("--password", required=True) + p_user.add_argument("--dept", default="") + p_user.add_argument("--nickname", default="") + p_user.add_argument("--admin", dest="is_admin_flag", action="store_true", help="设为管理员") + + p_upd = sub.add_parser("user-update", help="更新账号(部门/昵称/管理员)") + p_upd.add_argument("account") + p_upd.add_argument("--dept", default=None) + p_upd.add_argument("--nickname", default=None) + p_upd.add_argument("--is-admin", dest="is_admin_opt", type=lambda s: s in ("1", "true", "yes", "是"), + default=None) + + p_rp = sub.add_parser("user-reset-pwd", help="管理员重置账号密码") + p_rp.add_argument("account") + p_rp.add_argument("--password", required=True) + + p_del_u = sub.add_parser("user-del", help="删除账号") + p_del_u.add_argument("account") + + p_grant = sub.add_parser("grant", help="授予账号某插件权限(默认 download+run)") + p_grant.add_argument("account") + p_grant.add_argument("plugin_id") + p_grant.add_argument("--no-download", action="store_true", help="不授予下载权限") + p_grant.add_argument("--no-run", action="store_true", help="不授予运行权限") + + p_revoke = sub.add_parser("revoke", help="撤销账号某插件权限") + p_revoke.add_argument("account") + p_revoke.add_argument("plugin_id") + + p_gp = sub.add_parser("grant-platform", help="授予账号某平台登录权限") + p_gp.add_argument("account") + p_gp.add_argument("platform_id") + + p_rp_plt = sub.add_parser("revoke-platform", help="撤销账号某平台登录权限") + p_rp_plt.add_argument("account") + p_rp_plt.add_argument("platform_id") + + sub.add_parser("stats", help="运行统计看板") + + sub.add_parser("me", help="校验当前管理身份") + + 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) + cmd = args.command + + 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')}") + + elif cmd == "plugins": + data = c.call("GET", "/api/admin/overview") + _plugin_rows(data.get("plugins", {})) + + elif cmd == "plugin-del": + r = c.call("POST", "/api/admin/plugin/delete", {"plugin_id": args.plugin_id}) + print(f"[ok] 已删除插件 {r.get('plugin_id')}") + + elif cmd == "plugin-status": + import urllib.parse as _q + body = {} + if args.status: + body["status"] = args.status + if args.force_min_version and args.force_deadline: + body.update({"force_min_version": args.force_min_version, "force_deadline": args.force_deadline}) + elif args.clear_force: + body["clear_force"] = True + r = c.call("POST", f"/api/admin/plugin/patch?{_q.urlencode({'plugin_id': args.plugin_id})}", body) + print("[ok]", json.dumps(r, ensure_ascii=False)) + + elif cmd == "users": + data = c.call("GET", "/api/admin/accounts") + accounts = data.get("accounts", "") + if isinstance(accounts, dict): + accounts = list(accounts.values()) + accounts = [a for a in (accounts or []) if isinstance(a, dict)] + if not accounts: + print("(暂无账号)") + return 0 + print(f"{'账号':<16}{'昵称':<14}{'部门':<12}{'管理员'}") + for a in accounts: + print(f"{str(a.get('account', '')):<16}{str(a.get('nickname') or ''):<14}" + f"{str(a.get('dept') or ''):<12}{'是' if a.get('is_admin') else '否'}") + + elif cmd == "user-add": + r = c.call("POST", "/api/admin/account", { + "account": args.account, "password": args.password, + "dept": args.dept, "nickname": args.nickname, "is_admin": args.is_admin_flag}) + print(f"[ok] 已建号 {r.get('account')}" + ("(管理员)" if r.get("is_admin") else "")) + + elif cmd == "user-update": + body = {"account": args.account} + for k, v in (("dept", args.dept), ("nickname", args.nickname), ("is_admin", args.is_admin_opt)): + if v is not None: + body[k] = v + r = c.call("POST", "/api/admin/account/update", body) + print(f"[ok] 已更新 {r.get('account')}") + + elif cmd == "user-reset-pwd": + r = c.call("POST", "/api/admin/account/reset_pwd", {"account": args.account, "new_password": args.password}) + print(f"[ok] 已重置 {r.get('account')} 密码") + + elif cmd == "user-del": + r = c.call("POST", "/api/admin/account/delete", {"account": args.account}) + print(f"[ok] 已删除账号 {r.get('account')}") + + elif cmd == "grant": + r = c.call("POST", "/api/admin/account_plugins", { + "account": args.account, "plugin_id": args.plugin_id, "granted": True, + "can_download": not args.no_download, "can_run": not args.no_run}) + print(f"[ok] 已授予 {r.get('account')} → {r.get('plugin_id')}(download={'y' if not args.no_download else 'n'}" + f"/run={'y' if not args.no_run else 'n'})") + + elif cmd == "revoke": + r = c.call("POST", "/api/admin/account_plugins", { + "account": args.account, "plugin_id": args.plugin_id, "granted": False}) + print(f"[ok] 已撤销 {r.get('account')} → {r.get('plugin_id')}") + + elif cmd == "grant-platform": + r = c.call("POST", "/api/admin/account_platforms", { + "account": args.account, "platform_id": args.platform_id, "granted": True}) + print(f"[ok] 已授予 {r.get('account')} → 平台 {r.get('platform_id')}") + + elif cmd == "revoke-platform": + r = c.call("POST", "/api/admin/account_platforms", { + "account": args.account, "platform_id": args.platform_id, "granted": False}) + print(f"[ok] 已撤销 {r.get('account')} → 平台 {r.get('platform_id')}") + + elif cmd == "stats": + print(json.dumps(c.call("GET", "/api/admin/stats"), ensure_ascii=False, indent=2)) + + elif cmd == "me": + data = c.call("GET", "/api/admin/me") + print(f"登录账号:{data.get('account')} 管理员:{'是' if data.get('is_admin') else '否'} " + f"部门:{data.get('dept') or ''}") + return 0 + + +def main() -> None: + args = _build_parser().parse_args() + try: + _run(args) + except SystemExit as exc: + if exc.code: + print(str(exc.code)) + raise + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/controlplane/app.py b/controlplane/app.py index 5cdae3b..b2bbaa9 100644 --- a/controlplane/app.py +++ b/controlplane/app.py @@ -1413,23 +1413,21 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"), _require_admin(x_admin_token, x_api_token) with _db() as conn: users = dict(conn.execute( - "SELECT (SELECT COUNT(*) FROM accounts), " - "(SELECT COUNT(*) FROM accounts WHERE is_admin = 1), " - "(SELECT COUNT(DISTINCT account) FROM account_plugins)").fetchone()) + "SELECT (SELECT COUNT(*) FROM accounts) AS total, " + "(SELECT COUNT(*) FROM accounts WHERE is_admin = 1) AS admins, " + "(SELECT COUNT(DISTINCT account) FROM account_plugins) AS authorized").fetchone()) plugins = dict(conn.execute( - "SELECT " - " (SELECT COUNT(*) FROM plugins), " - " (SELECT COUNT(*) FROM plugins WHERE status = 'published'), " - " (SELECT COUNT(*) FROM plugins WHERE status = 'disabled'), " - " (SELECT COUNT(*) FROM plugins WHERE status = 'revoked')").fetchone()) + "SELECT (SELECT COUNT(*) FROM plugins) AS total, " + "(SELECT COUNT(*) FROM plugins WHERE status = 'published') AS published, " + "(SELECT COUNT(*) FROM plugins WHERE status = 'disabled') AS disabled, " + "(SELECT COUNT(*) FROM plugins WHERE status = 'revoked') AS revoked").fetchone()) runs = dict(conn.execute( - "SELECT " - " (SELECT COUNT(*) FROM runtime_reports WHERE status = 'start'), " - " (SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')), " - " (SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')), " - " (SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports), " - " (SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> ''), " - " (SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '')").fetchone()) + "SELECT (SELECT COUNT(*) FROM runtime_reports WHERE status = 'start') AS started, " + "(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')) AS success, " + "(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')) AS failed, " + "(SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports) AS duration_sec, " + "(SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> '') AS active_users, " + "(SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '') AS active_plugins").fetchone()) # 近 14 天运行趋势(按日:触发次数 / 成功 / 失败) trend_rows = conn.execute( @@ -1486,14 +1484,15 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"), for rc in recent: rc["nickname"] = nick.get(rc.get("account", ""), "") + now_day = datetime.now().strftime("%Y-%m-%d") return { - "users": {"total": int(users[0] or 0), "admins": int(users[1] or 0), - "authorized": int(users[2] or 0)}, - "plugins": {"total": int(plugins[0] or 0), "published": int(plugins[1] or 0), - "disabled": int(plugins[2] or 0), "revoked": int(plugins[3] or 0)}, - "runs": {"total": int(runs[0] or 0), "success": int(runs[1] or 0), - "failed": int(runs[2] or 0), "durationSec": int(runs[3] or 0), - "activeUsers": int(runs[4] or 0), "activePlugins": int(runs[5] or 0)}, + "users": {"total": int(users["total"] or 0), "admins": int(users["admins"] or 0), + "authorized": int(users["authorized"] or 0)}, + "plugins": {"total": int(plugins["total"] or 0), "published": int(plugins["published"] or 0), + "disabled": int(plugins["disabled"] or 0), "revoked": int(plugins["revoked"] or 0)}, + "runs": {"total": int(runs["started"] or 0), "success": int(runs["success"] or 0), + "failed": int(runs["failed"] or 0), "durationSec": int(runs["duration_sec"] or 0), + "activeUsers": int(runs["active_users"] or 0), "activePlugins": int(runs["active_plugins"] or 0)}, "trend": trend, "topPlugins": top_plugins, "topUsers": top_users, "recent": recent, "today": now_day, } diff --git a/controlplane/controlplane.db b/controlplane/controlplane.db index b33eec5..a0d4763 100644 Binary files a/controlplane/controlplane.db and b/controlplane/controlplane.db differ diff --git a/controlplane/frontend/src/components/LoginPage.vue b/controlplane/frontend/src/components/LoginPage.vue index f8bd47b..abdaf0e 100644 --- a/controlplane/frontend/src/components/LoginPage.vue +++ b/controlplane/frontend/src/components/LoginPage.vue @@ -1,48 +1,57 @@ +.form :deep(.n-form-item) { margin-bottom: 20px; } +.form :deep(.n-form-item-label) { font-size: 12.5px; font-weight: 600; color: var(--cp-ink-2, #4a5270); padding-bottom: 6px; } +.form :deep(.n-input) { border-radius: 8px; } +.form :deep(.n-input__inner) { font-size: 14px; } + +.primary.n-button--primary-type { height: 44px; border-radius: 8px; font-size: 14px; letter-spacing: .1em; } + +.foot { margin-top: 20px; text-align: center; font-size: 11.5px; color: var(--cp-ink-3, #8a93a6); } + \ No newline at end of file diff --git a/webhost/backend/main.py b/webhost/backend/main.py index 11787b6..d53054a 100644 --- a/webhost/backend/main.py +++ b/webhost/backend/main.py @@ -638,21 +638,53 @@ def _account_allowed_platforms(account: str) -> set | None: return None +def _cloud_plugin_ids(account: str) -> set | None: + """已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。 + + 降级策略(三态): + - 200 → 返回账号允许的插件 id 集(真正按员工权限过滤) + - 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露 + - 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5) + """ + token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None + if not token or not CONTROLPLANE_URL: + return None + import requests + + try: + r = requests.get(f"{CONTROLPLANE_URL}/api/plugins", + headers={"Authorization": f"Bearer {token}"}, timeout=5) + except Exception: # noqa: BLE001 云端不可达 → 离线兜底 + return None + if r.status_code == 401: + return set() + if r.status_code != 200: + return None + return {p["id"] for p in r.json().get("plugins", [])} + + @app.get("/api/meta") def meta(request: Request) -> dict: account = _sess_account(request) - # 插件清单仅对已登录账号可见(未登录不泄露插件元数据) - plugins = [_plugin_schema(p) for p in PLUGINS] if account else [] - allowed = _account_allowed_platforms(account) if account else None + # 插件清单仅对已登录账号可见(未登录不泄露插件元数据); + # 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。 + if account: + allowed = _cloud_plugin_ids(account) + plugins = ([_plugin_schema(p) for p in PLUGINS if p.id in allowed] + if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限) + else [_plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量 + else: + plugins = [] + allowed_plats = _account_allowed_platforms(account) if account else None platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid), # 已登录时按账号白名单;未登录/中心机不可达默认展示 - "allowed": (pid in allowed) if allowed is not None else True} + "allowed": (pid in allowed_plats) if allowed_plats is not None else True} for pid, m in PLATFORMS.items()] return { # controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口) "controlplane": CONTROLPLANE_URL, - "appName": "37du 业务场景工具集", + "appName": "37du 自动化工作台", "dingtalkScan": bool(DINGTALK_APP_KEY), "platforms": platforms, "plugins": plugins, diff --git a/webhost/frontend/index.html b/webhost/frontend/index.html index 5a6a934..43fa0f8 100644 --- a/webhost/frontend/index.html +++ b/webhost/frontend/index.html @@ -3,7 +3,7 @@ - 37du 业务场景工具集 + 37du 自动化工作台
diff --git a/webhost/frontend/src/App.vue b/webhost/frontend/src/App.vue index e364a84..be28356 100644 --- a/webhost/frontend/src/App.vue +++ b/webhost/frontend/src/App.vue @@ -1,5 +1,10 @@